<?php

namespace App\Http\Controllers;

use App\Jobs\ResellerClientBillPaymentSyncJob;
use App\Models\Client;
use App\Models\ResellerBillGenerate;
use App\Models\ResellerBillPayment;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Mpdf\Tag\Bdi;

class ResellerBillPaymentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\ResellerBillPayment  $resellerBillPayment
     * @return \Illuminate\Http\Response
     */
    public function show(ResellerBillPayment $resellerBillPayment)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\ResellerBillPayment  $resellerBillPayment
     * @return \Illuminate\Http\Response
     */
    public function edit(ResellerBillPayment $resellerBillPayment)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\ResellerBillPayment  $resellerBillPayment
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, ResellerBillPayment $resellerBillPayment)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\ResellerBillPayment  $resellerBillPayment
     * @return \Illuminate\Http\Response
     */
    public function destroy(ResellerBillPayment $resellerBillPayment)
    {
        //
    }



    public function resellerClientPaymentSync($clientId)
    {
        DB::transaction(function () use ($clientId) {
            // Step 1: Calculate total paid amount (including discount)
            $totalPaidAmount = ResellerBillPayment::where('client_id', $clientId)
                ->selectRaw('SUM(paid_amount + discount_amount) as total')
                ->value('total');

            // Step 2: Get bills to apply the payments to (oldest first)
            $billGenerates = ResellerBillGenerate::where('client_id', $clientId)
                ->orderBy('id') // or order by month/year/etc
                ->get();

            // Step 3: Apply payment to bills
            foreach ($billGenerates as $billGenerate) {
                $amount = $billGenerate->amount;

                if ($totalPaidAmount >= $amount) {
                    $billGenerate->paid_amount = $amount;
                    $billGenerate->due_amount = 0;
                    $totalPaidAmount -= $amount;
                } elseif ($totalPaidAmount > 0) {
                    $billGenerate->paid_amount = $totalPaidAmount;
                    $billGenerate->due_amount = $amount - $totalPaidAmount;
                    $totalPaidAmount = 0;
                } else {
                    $billGenerate->paid_amount = 0;
                    $billGenerate->due_amount = $amount;
                }

                $billGenerate->save();
            }
        });
    }

    public function getPaymentHistoryOfResellerClient($id)
    {
        $client = Client::with('pops','packages','clientsinfo','subpack','resellerClientBillGenerates','resellerClientBillPayments.paymentBy')->find($id);

        $data = [
            'client' => $client,
            'billGenerates' => $client->resellerClientBillGenerates,
            'billPayments' => $client->resellerClientBillPayments,
            'subpack' => $client->subpack,
            'packages' => $client->packages,
            'pops' => $client->pops,
            'clientsinfo' => $client->clientsinfo
        ];

        return view('clients.resellerClientPayment.paymentHistory', $data);


    }

    public function resellerClientPaymentProcess(Request $request)
    {
        try{
            // dd($request->all());
            DB::transaction(function () use ($request) {
                $client = Client::with('pops')->find($request->client_id);

                $resellerBillPayment = new ResellerBillPayment();
                $resellerBillPayment->reseller_id = $client->pops->reseller_id;
                $resellerBillPayment->client_id = $request->client_id;
                // $resellerBillPayment->description = $request->description;
                $resellerBillPayment->discount_amount = $request->discount ?? 0;
                $resellerBillPayment->paid_amount = $request->amount;
                $resellerBillPayment->user_id = auth()->user()->id;
                $resellerBillPayment->money_receipt_number = createUUID();
                $resellerBillPayment->save();

                // Update client balance
                if($client->customer_account_balance_reseller < 0){
                    ResellerClientBillPaymentSyncJob::dispatch($client->id);
                }

                $paidAmount = $request->amount + ($request->discount ?? 0);

                $client->customer_account_balance_reseller -= $paidAmount;
                $client->save();

            });
            Toastr::success('Payment Processed Successfully');
            return redirect()->back();

        }catch(\Exception $e){
            dd($e);
            Toastr::error('Something went wrong');
            DB::rollback();
            return false;
        }
    }

    public function resellerClientPaymentDelete($id)
    {
        try {
            $clientId = null;
            $originalPaid = 0;
            $originalDiscount = 0;

            DB::transaction(function () use ($id, &$clientId, &$originalPaid, &$originalDiscount) {
                $resellerBillPayment = ResellerBillPayment::find($id);

                $originalPaid = $resellerBillPayment->paid_amount;
                $originalDiscount = $resellerBillPayment->discount_amount;

                if(($originalPaid + $originalDiscount) <= 0){
                    Toastr::error('Payment amount is less than 0');
                    return redirect()->back();
                }

                // Update payment record
                $resellerBillPayment->paid_amount = 0;
                $resellerBillPayment->discount_amount = 0;
                $resellerBillPayment->description = "Previous paid amount {$originalPaid} + discount amount {$originalDiscount} deleted by " . auth()->user()->name . " at " . now() . ",";
                $resellerBillPayment->save();

                // Update client balance
                $client = Client::find($resellerBillPayment->client_id);
                $client->customer_account_balance_reseller += $originalPaid + $originalDiscount;
                $client->save();

                $clientId = $client->id;
            },1);

            // Dispatch job outside transaction
            ResellerClientBillPaymentSyncJob::dispatch($clientId);

            Toastr::success('Payment deleted successfully');
        } catch (\Exception $e) {
            \Log::error("Payment deletion failed: " . $e->getMessage());
            Toastr::error('Something went wrong while deleting the payment.');
        }

        return redirect()->back();
    }





}
