<?php

namespace App\Http\Controllers;

use App\Models\arrears_collection;
use App\Models\Beneficiary;
use App\Models\DeletedPayment;
use App\Models\Benefit;
use App\Models\Dependant;
use App\Models\Member;
use App\Models\Months_covered;
use App\Models\Oldmembers_status;
use App\Models\Payment_mode;
use App\Models\premium;
use App\Models\Premium_payment;
use App\Models\Sms;
use App\Models\User;
use App\Models\UserLog;
use App\Notifications\CompletedTask;
use App\Notifications\EditRequest;
use Carbon\Carbon;
use Illuminate\Support\Facades\Notification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;


class PaymentController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    //NEW PAYMENT VIEW
    public function index($id)
    {
        // Send a GET request to the Django API
        $apiReachable = @fsockopen('69.63.75.76', 8080, $errno, $errstr, 5);

        if (!$apiReachable) {
            // Set the "danger" message in the session
            session()->flash('danger', 'SMS System down');
            return redirect()->back();
        }

        $modes = Payment_mode::all();
        $member = Member::find($id);

        // Block payments when status is "Restart"
        if ($member && $member->status1 === 'Restart') {
            return back()->with('warning', 'Payments are disabled while this member is in "Restart" status.');
        }

        if ($member->deceased) {
            return back()->with('warning', 'Payments are disabled for deceased members.');
        }

        $payment = Premium_payment::where('member_id', $id)->latest()->first();
        $covers = DB::select('(SELECT DATE_FORMAT(months, "%Y-%M") as months FROM months_covereds WHERE payment_id IN (SELECT id FROM premium_payments WHERE member_id =' . $id . ')) ');
        $last_covers = DB::select('(SELECT months FROM months_covereds WHERE payment_id IN (SELECT id FROM premium_payments WHERE member_id =' . $id . ') order by id DESC limit 1) ');
        $arrears = DB::select('(SELECT DATE_FORMAT(months, "%Y-%M") as months FROM arrears_collections WHERE payment_id IN (SELECT id FROM premium_payments WHERE member_id =' . $id . ')) ');

        foreach ($last_covers as $last_coverr) {
            $last_cover = $last_coverr->months;
        }
        if (!$last_covers) {
            $last_cover = Carbon::today()->subDays(30)->toDateString();
        }

        //MONTHLY PAYMENT
        $premium = premium::where('member_id', $id)->first();

        $totalsons = Dependant::where('relationship', 'Son')
            ->where('member_id', $id)
            ->count();

        $totaldaughters = Dependant::where('relationship', 'Daughter')
            ->where('member_id', $id)
            ->count();

        $totalspouses = Dependant::where('relationship', 'Spouse')
            ->where('member_id', $id)
            ->count();

        $totalchildren = $totalsons + $totaldaughters;
        $totaldependents = $totalchildren + $totalspouses;

        if ($totalspouses <= 1) {
            $monthly_payment_spouse = $premium->cover->monthly_pay;
        } else {
            $monthly_payment_spouse = ($premium->cover->monthly_pay) + ($premium->cover->monthly_pay * (0.5 * ($totalspouses - 1)));
        }

        if ($totalchildren <= 6) {
            $monthly_payment1 = $monthly_payment_spouse;
        } elseif ($totalchildren > 6) {
            $childrenperc = ($totalchildren - 6) * 0.1;
            $amount = $monthly_payment_spouse;
            $monthly_payment1 = $amount + ($amount * $childrenperc);
        }

        //Additional Benefits
        $benefits = Benefit::where('member_id', $id)->first();
        if (!$benefits) {
            $benefits = Benefit::where('member_id', 1)->first();
        }

        $monthly_payment = round($monthly_payment1 + $benefits->airtime + $benefits->cow + $benefits->grocery, 2);

        //// END
        return view('payments/new_payment', compact(
            'premium',
            'benefits',
            'modes',
            'monthly_payment',
            'member',
            'covers',
            'last_cover',
            'arrears',
            'totaldependents',
            'totalchildren',
            'totalspouses'
        ));
    }


    // ALL PAYMENTS
    public function all()
    {
        $payments = Premium_payment::orderBy('id', 'desc')->paginate(20);
        return view('payments/allpayments', compact('payments'));
    }

    //WRONG PAYMENT

    public function wrong()
    {
        $user_id = Auth::id();
        if (Auth::id() == 143) {
            $payments = Premium_payment::where('amount_paid', 0)->get();
            return view('payments/wrong_payments', compact('payments'));
        } else {
            return redirect()->back()->with('danger', 'You are not allowed!');
        }
    }

    public function all1($id)
    {
        $beneficiary = Beneficiary::where('member_id', $id)->first();
        /* if (!$beneficiary) {
            return redirect()->back()->with('danger', 'Please add beneficiary first!');
        }*/
        $payments = Premium_payment::where('member_id', $id)
            ->latest()
            ->get();
        $member = Member::find($id);
        return view('payments/memberpayments', compact('payments', 'member'));
    }

    // RECORD PAYMENT 
    /*  public function store(Request $request)
    {
        //VALIDATION
        $this->validate($request, [
            'member_id' => 'required',
            'month_covered' => 'required',
            'payment_method' => 'required',
            'cash_tendered' => 'required',
            'months' => 'required',
            'cash' => 'required'
        ]);

        $latestRecord = DB::table('premium_payments')
            ->where('member_id', $request->member_id)
            //  ->where('user_id', Auth::user()->id)
            ->latest('created_at')
            ->first();

        if ($latestRecord && Carbon::now()->diffInMinutes($latestRecord->created_at) < 1) {
            return redirect('/memberpayments/' . $request->member_id)->with('danger', 'Please wait for at least one minute before trying again.');
        }


        $member = Member::find($request->member_id);
        $apiEndpoint = 'http://69.63.75.76:8080/api/send-sms';
        // Check if the API endpoint is reachable

        // if ($request->payment_method == 1) {
        // Check if the member's cell number has exactly 8 digits
        if (strlen($member->cell_number) !== 8) {
            return redirect()->back()->with('danger', 'Invalid cell number format');
        }


        // Send a GET request to the Django API
        $apiReachable = @fsockopen('69.63.75.76', 8080, $errno, $errstr, 5);

        if (!$apiReachable) {
            return redirect()->back()->with('danger', 'SMS System down');
        }
        // }


        $payment1 = Premium_payment::where('member_id', $request->member_id)
            ->latest()
            ->first();

        if ($payment1) {
            $pay_stat = $payment1->status;
        } else {
            $pay_stat = 0;
        }

        if ($pay_stat == 1) {
            return redirect()->back()->with('danger', 'You have a payment waiting deletion please contact the admin!');
        } else {
            $payment = new Premium_payment();

            //MEMBER PREMIUM 
            $premium = premium::where('member_id', $request->member_id)->first();

            //// END
            if (($request->monthly_payment * $request->months) > $request->cash_tendered) {
                return redirect()->back()->with('danger', 'The Amount is not suffcient for the option selected!');
            } else {
                //ONE MONTH
                if ($request->months == 1) {
                    $payment->cover_id = $premium->cover_id;
                    $payment->member_id = $request->member_id;
                    $payment->payment_method = $request->payment_method;
                    $payment->cash_tendered = $request->cash_tendered;
                    $payment->amount_paid =  $request->monthly_payment;
                    $payment->payment_change = $request->cash_tendered - ($request->monthly_payment * $request->months);
                    $payment->payment_date = Carbon::now()->toDateString();
                    $payment->months = $request->months;
                    $payment->user_id = Auth::id();
                    $payment->cash = $request->cash;
                    if ($request->cash == 1) {
                        $payment->cash_date = $request->cash_date;
                    }

                    $payment->save();

                    //MONTHS COVERED
                    $last_covers = DB::select('(SELECT months FROM months_covereds WHERE payment_id IN (SELECT id FROM premium_payments WHERE member_id =' . $request->member_id . ') order by id DESC limit 1) ');
                    foreach ($last_covers as $last_coverr) {
                        $last_cover = $last_coverr->months;
                    }
                    if (!$last_covers) {
                        $months_covered = new Months_covered();
                        $months_covered->cover_id = $premium->cover_id;

                        //Month covers 
                        $months_covered->months = Carbon::parse($request->month_covered)->addMonthsNoOverflow(1);

                        $months_covered->payment_id = $payment->id;
                        $months_covered->member_id = $request->member_id;
                        $months_covered->save();
                    } else {
                        $months_covered = new Months_covered();
                        $months_covered->cover_id = $premium->cover_id;

                        //Month covers 
                        $months_covered->months = Carbon::parse($last_cover)->addMonthsNoOverflow(1);

                        $months_covered->payment_id = $payment->id;
                        $months_covered->member_id = $request->member_id;
                        $months_covered->save();

                        //STORE AREAS
                        $last_date = Carbon::parse($last_cover);
                        $now = Carbon::now();
                        //$length = $last_date->diffInMonths($now);

                        $previousTime = strtotime($last_cover);
                        $difference = time() - $previousTime;
                        $length = round($difference / 2629746);
                        if ($length >  1) {
                            $arrears = new arrears_collection();
                            $arrears->cover_id = $premium->cover_id;

                            //Month covers 
                            $arrears->months = Carbon::parse($last_cover)->addMonthsNoOverflow(1);


                            $arrears->payment_id = $payment->id;
                            $arrears->member_id = $request->member_id;
                            $arrears->save();
                        }
                        if ($length >=  3) {
                            $status = Oldmembers_status::where('member_id', $request->member_id)->first();
                            if ($status) {
                            } else {
                                $oldmember_status = new Oldmembers_status();
                                $oldmember_status->status = '1';
                                $oldmember_status->member_id = $request->member_id;
                                $oldmember_status->save();
                            }
                        }
                    }

                    //SEND SMS


                    $link = url('/receipt/' . $payment->id);
                    $from = $member->code . $member->cell_number;
                    $cover_first = Months_covered::where('payment_id', $payment->id)->orderBy('months', 'asc')->first();
                    $cover_last = Months_covered::where('payment_id', $payment->id)->orderBy('months', 'desc')->first();

                    // $message_status = "A new payment of: E" . $payment->amount_paid . " Has been received at " . Carbon::now();
                    $message_status = "MBBS - MoMo: 151353" . "\n" .
                        "Created:" . $payment->payment_date . "\n" .
                        "Name:" . $member->surname . " " . $member->name . "\n" .
                        "Policy: " . $member->national_id . "\n" .
                        "\n" .
                        "# Months: " . $payment->months . "\n" .
                        "Months:";

                    if ($cover_first == $cover_last) {
                        $message_status .= date('F-Y', strtotime($cover_first->months));
                    } else {
                        $message_status .= date('F-Y', strtotime($cover_first->months)) . " to " . date('F-Y', strtotime($cover_last->months));
                    }

                    $message_status .= "\nTotal: E " . $payment->amount_paid;

                    if ($payment->cash == 1) {
                        $response = Http::get($apiEndpoint, [
                            'destination_number' => $from, // Replace with the desired destination number
                            'message' => $message_status, // Replace with your message
                        ]);

                        // Store SMS
                        $sms = new Sms();
                        $sms->user_id = Auth::id();
                        $sms->destination_number = $from;
                        $sms->message = $message_status;
                        $sms->payment_id = $payment->id;
                        $sms->member_id = $member->id;
                        $sms->status = 1;
                        $sms->save();
                    }




                    $link = url('/receipt/' . $payment->id);
                    $member_name = $member->name . "" . $member->surname;
                    $receipt_num = $payment->id;

                    //SEND EMAIL


                    //SEND NOTIFICATION               
                    $message = Auth::user()->name . " Has received payment # " . $receipt_num . " on " . Carbon::now();
                    $users = User::where('role', 3)->get();
                    foreach ($users as $userr) {
                        $userr->notify(new CompletedTask($message));
                    }

                    $history = new UserLog();
                    $history->user_id = Auth::id();
                    $history->action = Auth::user()->name . " received payment " . $receipt_num . " on " . Carbon::now();
                    $history->comment = "New Payment";
                    $history->save();

                    return redirect('memberpayments/' . $request->member_id)->with('success', 'Payment Saved! Your Change is: E ' . $payment->payment_change);
                } elseif ($request->months > 1) {
                    //MORE THAN ONE MONTH
                    $payment->cover_id = $premium->cover_id;
                    $payment->member_id = $request->member_id;
                    $payment->payment_method = $request->payment_method;
                    $payment->cash_tendered = $request->cash_tendered;
                    $payment->amount_paid =  $request->monthly_payment * $request->months;
                    $payment->payment_change = $request->cash_tendered - ($request->monthly_payment * $request->months);
                    $payment->payment_date = Carbon::now();
                    $payment->months = $request->months;
                    $payment->user_id = Auth::id();
                    $payment->cash = $request->cash;
                    if ($request->cash == 1) {
                        $payment->cash_date = $request->cash_date;
                    }
                    $payment->save();

                    for ($i = 0; $i < $request->months; $i++) {
                        $last_covers = DB::select('(SELECT months FROM months_covereds WHERE payment_id IN (SELECT id FROM premium_payments WHERE member_id =' . $request->member_id . ') order by id DESC limit 1) ');

                        foreach ($last_covers as $last_coverr) {
                            $last_cover = $last_coverr->months;
                        }

                        if (!$last_covers) {
                            $months_covered = new Months_covered();
                            $months_covered->cover_id = $premium->cover_id;

                            //Month covers 
                            $months_covered->months = Carbon::parse($request->month_covered)->addMonthsNoOverflow(1);

                            $months_covered->payment_id = $payment->id;
                            $months_covered->member_id = $request->member_id;
                            $months_covered->save();
                        } else {
                            $months_covered = new Months_covered();
                            $last_covers1 = DB::select('(SELECT months FROM months_covereds WHERE payment_id IN (SELECT id FROM premium_payments WHERE member_id =' . $request->member_id . ') order by id DESC limit 1) ');
                            foreach ($last_covers1 as $last_coverr1) {
                                $last_cover1 = $last_coverr1->months;
                            }

                            $last_date = Carbon::parse($last_cover1);
                            $now = Carbon::now();
                            // $length = $last_date->diffInMonths($now);
                            $previousTime = strtotime($last_cover);
                            $difference = time() - $previousTime;
                            $length = round($difference / 2629746);
                            if ($length >  1) {
                                $arrears = new arrears_collection();
                                $arrears->cover_id = $premium->cover_id;

                                //Month covers 
                                $arrears->months = Carbon::parse($last_cover1)->addMonthsNoOverflow(1);

                                $arrears->payment_id = $payment->id;
                                $arrears->member_id = $request->member_id;
                                $arrears->save();
                            }

                            if ($length >= 3) {
                                $status = Oldmembers_status::where('member_id', $request->member_id)->first();
                                if ($status) {
                                } else {
                                    $oldmember_status = new Oldmembers_status();
                                    $oldmember_status->status = '1';
                                    $oldmember_status->member_id = $request->member_id;
                                    $oldmember_status->save();
                                }
                            }

                            $months_covered->cover_id = $premium->cover_id;

                            //Month covers 
                            $months_covered->months = Carbon::parse($last_cover1)->addMonthsNoOverflow(1);

                            $months_covered->payment_id = $payment->id;
                            $months_covered->member_id = $request->member_id;
                            $months_covered->save();
                        }
                    }

                    $arrears = DB::select('(SELECT DATE_FORMAT(months, "%Y-%M") as months FROM arrears_collections WHERE payment_id IN (SELECT id FROM premium_payments WHERE member_id =' . $request->member_id . ')) ');
                    $payments = Premium_payment::find($payment->id);


                    $link = url('/receipt/' . $payment->id);
                    $from = $member->code . $member->cell_number;
                    $cover_first = Months_covered::where('payment_id', $payment->id)->orderBy('months', 'asc')->first();
                    $cover_last = Months_covered::where('payment_id', $payment->id)->orderBy('months', 'desc')->first();

                    // $message_status = "A new payment of: E" . $payment->amount_paid . " Has been received at " . Carbon::now();
                    $message_status = "MBBS - MoMo: 151353" . "\n" .
                        "Created:" . $payment->payment_date . "\n" .
                        "Name:" . $member->surname . " " . $member->name . "\n" .
                        "Policy: " . $member->national_id . "\n" .
                        "\n" .
                        "# Months: " . $payment->months . "\n" .
                        "Months:";

                    //   $this->sendSmsViaOzeki($from, $message_status);

                    if ($cover_first == $cover_last) {
                        $message_status .= date('F-Y', strtotime($cover_first->months));
                    } else {
                        $message_status .= date('F-Y', strtotime($cover_first->months)) . " to " . date('F-Y', strtotime($cover_last->months));
                    }

                    $message_status .= "\nTotal: E " . $payment->amount_paid;

                    if ($payment->cash == 1) {
                        $response = Http::get($apiEndpoint, [
                            'destination_number' => $from, // Replace with the desired destination number
                            'message' => $message_status, // Replace with your message
                        ]);

                        // Store SMS
                        $sms = new Sms();
                        $sms->user_id = Auth::id();
                        $sms->destination_number = $from;
                        $sms->message = $message_status;
                        $sms->payment_id = $payment->id;
                        $sms->member_id = $member->id;
                        $sms->status = 1;
                        $sms->save();
                    }



                    //SEND EMAIL
                    $member_name = $member->name . "" . $member->surname;
                    $receipt_num = $payment->id;

                    //SEND NOTIFICATION               
                    $message = Auth::user()->name . " Has received payment # " . $receipt_num . " on " . Carbon::now();
                    $users = User::where('role', 3)->get();
                    foreach ($users as $userr) {
                        $userr->notify(new CompletedTask($message));
                    }

                    $history = new UserLog();
                    $history->user_id = Auth::id();
                    $history->action = Auth::user()->name . " received payment " . $receipt_num . " on " . Carbon::now();
                    $history->comment = "New Payment";
                    $history->save();

                    return redirect('memberpayments/' . $request->member_id)->with('success', 'Payment Saved! Your Change is: E ' . $payment->payment_change);
                } elseif ($request->months <= 0) {
                    return redirect()->back()->with('danger', 'Months cannot be 0!');
                }
            }
        }
    }*/

    /* public function delete($id, $member_id)
    {
        $premium_payment = Premium_payment::find($id);


        if (Auth::User()->role == 3) {
            $payment = Premium_payment::where('member_id', $member_id)
                ->latest()
                ->first();

            if ($payment->id == $id) {
                // ✅ Save to deleted_payments table
                DeletedPayment::create([
                    'cover_id' => $premium_payment->cover_id,
                    'payment_method' => $premium_payment->payment_method,
                    'cash_tendered' => $premium_payment->cash_tendered,
                    'months' => $premium_payment->months,
                    'change' => $premium_payment->change,
                    'member_id' => $premium_payment->member_id,
                    'payment_date' => $premium_payment->payment_date,
                    'user_id' => $premium_payment->user_id,
                    'amount_paid' => $premium_payment->amount_paid,
                    'submission_status' => $premium_payment->submission_status,
                    'satus' => $premium_payment->satus,
                    'cash' => $premium_payment->cash,
                    'deleted_by' => Auth::id(),
                    'deleted_at' => now(),
                    'created_at' => now(),
                    'updated_at' => now()
                ]);
                Premium_payment::find($id)->forceDelete();

                //SEND NOTIFICATION               
                $message = Auth::user()->name . " Has deleted payment # " . $id . " on " . Carbon::now();
                $users = User::where('id', $premium_payment->user_id)->get();
                foreach ($users as $userr) {
                    $userr->notify(new CompletedTask($message));
                }

                //SEND NOTIFICATION ADMIN            
                $message = Auth::user()->name . " Has deleted payment # " . $id . " successfully on " . Carbon::now();
                $users = User::where('role', 3)->get();
                foreach ($users as $userr) {
                    $userr->notify(new CompletedTask($message));
                }

                $history = new UserLog();
                $history->user_id = Auth::id();
                $history->action = Auth::user()->name . " deleted payment # " . $id . " on " . Carbon::now();
                $history->comment = "Payment deletion";
                $history->save();

                return redirect()->back()->with('success', 'Deleted Successfully!');
            } else {
                return redirect('memberpayments/' . $member_id)->with('danger', 'Please select the recent payment!');
            }
        } else {
            //SEND NOTIFICATION ADMIN            
            $message = Auth::user()->name . " attempted to delete payment # " . $id . " on " . Carbon::now();
            $users = User::where('role', 3)->get();
            foreach ($users as $userr) {
                $userr->notify(new CompletedTask($message));
            }

            $history = new UserLog();
            $history->user_id = Auth::id();
            $history->action = Auth::user()->name . " attempted to delete payment # " . $id . " on " . Carbon::now();
            $history->comment = "Payment deletion";
            $history->save();
            return redirect('/')->with('danger', 'You are not allowed to delete a payment, please contact the system administrator!');
        }
    }*/


    public function delete($id, $member_id)
    {
        $premium_payment = Premium_payment::find($id);

        if (!$premium_payment) {
            return redirect()->back()->with('danger', 'Payment not found.');
        }

        // CREATOR CANNOT DELETE THEIR OWN PAYMENT
        if ($premium_payment->user_id == Auth::id()) {

            // Log attempt
            UserLog::create([
                'user_id' => Auth::id(),
                'action' => Auth::user()->name . " attempted to delete own payment #{$id}",
                'comment' => 'Self-deletion blocked',
            ]);

            return redirect()->back()
                ->with('danger', 'You are not allowed to delete a payment you created.');
        }

        // ================= ONLY ADMIN =================
        if (Auth::user()->role == 3) {

            $latestPayment = Premium_payment::where('member_id', $member_id)
                ->latest()
                ->first();

            if (!$latestPayment || $latestPayment->id != $id) {
                return redirect('memberpayments/' . $member_id)
                    ->with('danger', 'Please select the most recent payment!');
            }

            // ================= BACKUP =================
            DeletedPayment::create([
                'cover_id' => $premium_payment->cover_id,
                'payment_method' => $premium_payment->payment_method,
                'cash_tendered' => $premium_payment->cash_tendered,
                'months' => $premium_payment->months,
                'change' => $premium_payment->payment_change,
                'member_id' => $premium_payment->member_id,
                'payment_date' => $premium_payment->payment_date,
                'user_id' => $premium_payment->user_id,
                'amount_paid' => $premium_payment->amount_paid,
                'cash' => $premium_payment->cash,
                'deleted_by' => Auth::id(),
                'deleted_at' => now(),
            ]);

            // ================= DELETE PAYMENT =================
            $premium_payment->forceDelete();

            // ================= SMS REVERSAL =================
            $member = Member::find($member_id);
            $apiEndpoint = 'http://69.63.75.76:8080/api/send-sms';
            $from = $member->code . $member->cell_number;

            $reverseMessage =
                "MBBS NOTICE\n\n" .
                "Payment #{$id} made on " .
                Carbon::parse($premium_payment->payment_date)->toDateString() .
                " was reversed.\n\n" .
                "Amount: E " . number_format($premium_payment->amount_paid, 2) . "\n" .
                "Policy: " . $member->national_id;

            $apiReachable = @fsockopen('69.63.75.76', 8080, $errno, $errstr, 5);
            $smsStatus = 0;

            if ($apiReachable && strlen($member->cell_number) === 8) {
                Http::get($apiEndpoint, [
                    'destination_number' => $from,
                    'message' => $reverseMessage,
                ]);
                $smsStatus = 1;
            }

            // ================= SAVE SMS ALWAYS =================
            Sms::create([
                'user_id' => Auth::id(),
                'destination_number' => $from,
                'message' => $reverseMessage,
                'payment_id' => $id,
                'member_id' => $member_id,
                'status' => $smsStatus,
            ]);

            // ================= NOTIFICATIONS =================
            $message = Auth::user()->name . " deleted payment #{$id} on " . Carbon::now();
            User::where('role', 3)->each(fn($u) => $u->notify(new CompletedTask($message)));

            UserLog::create([
                'user_id' => Auth::id(),
                'action' => $message,
                'comment' => 'Payment deletion',
            ]);

            // ================= FINAL MESSAGE =================
            $finalMessage = $smsStatus
                ? 'Payment deleted and SMS sent to customer.'
                : 'Payment deleted successfully, but SMS could not be sent.';

            return redirect()->back()->with('success', $finalMessage);
        }

        // ================= UNAUTHORIZED =================
        UserLog::create([
            'user_id' => Auth::id(),
            'action' => Auth::user()->name . " attempted to delete payment #{$id}",
            'comment' => 'Unauthorized payment deletion',
        ]);

        return redirect('/')
            ->with('danger', 'You are not allowed to delete a payment.');
    }




    public function receipt($id)
    {
        $payment = Premium_payment::find($id);
        $member = Member::find($payment->member_id);
        $cover_first = Months_covered::where('payment_id', $payment->id)->orderBy('months', 'asc')->first();
        $cover_last = Months_covered::where('payment_id', $payment->id)->orderBy('months', 'desc')->first();
        $arrear_first = arrears_collection::where('payment_id', $payment->id)->orderBy('months', 'asc')->first();
        $arrear_last = arrears_collection::where('payment_id', $payment->id)->orderBy('months', 'desc')->first();
        $user = User::find($payment->user_id);
        return view('documents/receipt1', compact('member', 'cover_first', 'cover_last', 'arrear_first', 'arrear_last', 'user', 'payment'));
    }

    public function editView($id)
    {
        $payment = Premium_payment::find($id);
        return view('payments.editRequest', compact('payment'));
    }

    public function edit_request(Request $request, $id)
    {

        $this->validate($request, [
            'member_id' => 'required',
            'reason' => 'required'
        ]);

        $payment = Premium_payment::where('member_id', $request->member_id)
            ->latest()
            ->first();

        if ($payment->id == $id) {
            //SEND SMS
            if ($payment->status == 1) {
                return redirect()->back()
                    ->with('warning', 'You have submitted the request, please contact the admin!');
            } else {
                $pay_m = Premium_payment::find($id);
                $pay_m->status = 1;
                $pay_m->save();
                ///////////////////////////////////////////////////////////

                $link = url('/payment_preview/' . $id);
                $reason = $request->reason;
                $admins = User::where('role', 3)->get();
                $current_user = Auth::user()->name;
                foreach ($admins as $admin) {
                    $admin_name = $admin->name . "" . $admin->surname;
                    $payment_id1 = $id;

                    Notification::route('mail', $admin->email)
                        ->notify(new EditRequest($link, $admin_name, $payment_id1, $reason, $current_user));
                }

                //SEND NOTIFICATION ADMIN            
                $message = Auth::user()->name . " is requesting to delete payment # " . $id . " on " . Carbon::now() . " Please check your email.";
                $users = User::where('role', 3)->get();
                foreach ($users as $userr) {
                    $userr->notify(new CompletedTask($message));
                }

                $history = new UserLog();
                $history->user_id = Auth::id();
                $history->action = Auth::user()->name . " requested to delete payment # " . $id . " on " . Carbon::now();
                $history->comment = "Deletion Request";
                $history->save();

                return redirect('memberpayments/' . $request->member_id)->with('success', 'Request sent successfully!');
            }
        } else {
            return redirect('memberpayments/' . $request->member_id)->with('danger', 'Please select the recent payment!');
        }
    }

    public function preview($id)
    {
        $payment = Premium_payment::find($id);
        if (!$payment) {
            return redirect('/')->with('warning', 'Payment already deleted!');
        } else {
            $member = Member::find($payment->member_id);
            $covers = Months_covered::where('payment_id', $payment->id)->get();
            $arrears = arrears_collection::where('payment_id', $payment->id)->get();
            $user = User::find(Auth::id());
            return view('documents/preview', compact('member', 'covers', 'arrears', 'user', 'payment'));
        }
    }

    public function search(Request $request)
    {
        $this->validate($request, [
            'search' => 'required'
        ]);

        $payments = Premium_payment::where('id', $request->search)->orderBy('payment_date', 'desc')->paginate(20);
        return view('payments/allpayments', compact('payments'));
    }

    public function searchcover(Request $request)
    {
        $this->validate($request, [
            'search' => 'required'
        ]);

        $months_covereds = Months_covered::where('payment_id', $request->search)->paginate(20);
        return view('payments/monthcovered', compact('months_covereds'));
    }

    public function searcharrear(Request $request)
    {
        $this->validate($request, [
            'search' => 'required'
        ]);

        $areas = arrears_collection::where('payment_id', $request->search)->paginate(20);
        return view('payments/arrears', compact('arrears'));
    }

    public function monthscovered()
    {
        $months_covereds = Months_covered::paginate(20);
        return view('payments/monthcovered', compact('months_covereds'));
    }

    //DELETED PAYMENT

    public function alldeleted()
    {
        $user_id = Auth::id();
        if (Auth::user()->role == 3) {
            $payments = DeletedPayment::orderBy('id', 'desc')->get();
            return view('payments/deleted_payments', compact('payments'));
        } else {
            return redirect()->back()->with('danger', 'You are not allowed!');
        }
    }

    public function alltodelete()
    {
        $user_id = Auth::id();
        if (Auth::user()->role == 3) {
            $payments = Premium_payment::where('status', 1)
                ->orderBy('updated_at', 'desc')->get();
            return view('payments/allpayments', compact('payments'));
        } else {
            return redirect()->back()->with('danger', 'You are not allowed!');
        }
    }
}
