<?php

namespace App\Http\Controllers;

use App\Models\arrears_collection;
use App\Models\Member;
use App\Models\Months_covered;
use App\Models\Oldmembers_status;
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 Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Illuminate\Support\Facades\Http;

class PaymentProcessingController extends Controller
{
    protected $smsController;

    public function __construct(SendSmsController $smsController)
    {
        $this->smsController = $smsController;
    }


    public function paymentStore(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.762', 8080, $errno, $errstr, 5);


        $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) {

                        $smsStatus = 0;

                        if ($apiReachable) {
                            $response = Http::get($apiEndpoint, [
                                'destination_number' => $from,
                                'message' => $message_status,
                            ]);
                            $smsStatus = 1;
                        }

                        // 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 = $smsStatus;
                        $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 '
                                . number_format($payment->payment_change, 2)
                                . ($smsStatus === 1 ? ' | SMS sent successfully.' : ' | SMS NOT sent.')
                        );

                } 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) {
                        $smsStatus = 0;
                        $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 = $smsStatus;
                        $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 '
                                . number_format($payment->payment_change, 2)
                                . ($smsStatus === 1 ? ' | SMS sent successfully.' : ' | SMS NOT sent.')
                        );
                } elseif ($request->months <= 0) {
                    return redirect()->back()->with('danger', 'Months cannot be 0!');
                }
            }
        }
    }
}
