<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\Invoice;
use App\Models\Payment;
use Illuminate\Http\Request;

class PaymentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($idBranch)
    {
        $today = Carbon::today()->toDateString(); // Y-m-d
        $payments = Payment::with('invoice')->where('branch_id', $idBranch)->whereDate('date', $today)->orderBy('id', 'desc')->get();
        //$payments = Payment::all();
        $invoices = Invoice::where('branch_id', $idBranch)->with('item', 'salesman', 'payment')->where('status', 'Processing')->withSum('payment', 'amount')->get();
        return view('payment/all', compact('invoices', 'idBranch', 'payments'));
    }

    /**
     * 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, $idInvoice)
    {
        $request->validate([
            'payment' => 'required|integer|gt:0'
        ]);



        try {
            $invoice = Invoice::findOrFail($idInvoice);
            $billAmount = $invoice->amount - $invoice->discount;
            $totalPaid = Payment::where('invoice_id', $idInvoice)->sum('amount');


            // dd($billAmount);
            //dd($totalPaid);


            $date = Carbon::now()->format('Y-m-d');
            if (($billAmount - $totalPaid) >= $request->payment) {
                $payment = [
                    'amount' => $request->payment,
                    'invoice_id' => $invoice->id,
                    'date' => $date,
                    'type' => 'Payment',
                    'branch_id' => $invoice->branch_id,
                ];

                $payment = Payment::create($payment);
                $payment->code =  "PYM-" . str_pad($payment->id, 5, '0', STR_PAD_LEFT); // LN-001, LN-002 etc.
                $payment->save();

                //if bill is paid finish then update status as complete
                if (($billAmount - $totalPaid) == $request->payment) {
                    $invoice->status = 'Complete';
                    $invoice->update();
                }

                $invoices = Invoice::where('branch_id', $invoice->branch_id)->with('item', 'salesman')->get();
                // return view('payment/all', compact('invoices'))->with('success', 'Payment created successfully');
                return back()->with('success', 'Payment saved successfully');
            } else {
                return back()->with('warning', 'Over payment not allow');
            }

            //validate payment amount is 
        } catch (\Throwable $th) {
            return back()->with('error', $th->getMessage());
        }
    }

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

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

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Payment  $payment
     * @return \Illuminate\Http\Response
     */
    public function destroy(Payment $payment, $idPayment)
    {
        $payment = Payment::findOrFail($idPayment);
        $invoice = Invoice::findOrFail($payment->invoice_id);


        try {
            //check invoice is complete tehen update as processing
            if ($invoice->status == 'Complete') {
                $invoice->status = 'Processing';
                $invoice->update();
            }

            //remove payment
            $payment->delete();
            return back()->with('success', 'Payment data removed');
        } catch (\Throwable $th) {
            return back()->with('error', $th->getMessage());
        }


        //finalize process

    }


    public function paymentSummery()
    {
        $payments = Payment::with('invoice','branch')
            ->orderBy('id', 'desc')
            ->paginate(10);
       // return $payments;
        return view('reports/paymentSummery',compact('payments'));
    }
}
