<?php

namespace App\Http\Controllers;

use App\Models\Stock;
use App\Models\branch;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\Salesman;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class InvoiceController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($idBranch)
    {
        $invoices = Invoice::where('branch_id', $idBranch)->with('item', 'salesman', 'payment')->withSum('payment', 'amount')->orderBy('id', 'desc')->paginate(10);
        return view('invoice/all', compact('invoices', 'idBranch'));
        // return $idBranch;
        // return 'sss';
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($idBranch)
    {
        //get all salesman list of branch
        $salesmans = Salesman::where('branch_id', $idBranch)->get();
        $stockItems = Stock::where('branch_id', $idBranch)->with('item')->get();

        //get all product list of branch
        return view('invoice/new', compact('salesmans', 'stockItems', 'idBranch'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $request->validate([
            'name' => 'required|string|max:50',
            'nic' => 'string|nullable|max:12',
            'mobile' => 'string|required|max:10',
            'land' => 'string|nullable|max:10',
            'address' => 'string|nullable:max:500',
            'branch' => 'integer|required|gt:0',
            'item' => 'integer|required|gt:0',
            'salesman' => 'integer|required|gt:0',
            'amount' => 'integer|required|gt:0',
            'billType' => 'required|in:Installment,Cash',
            'note' => 'string|nullable|max:200',
            'image' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
            'date' => 'required|date',
            'discount' => 'integer|lt:amount',
            'down_payment' => 'integer|nullable|gt:0'


        ], [
            'branch.gt' => 'Valid branch not found',
            'item.gt' => 'Valid item not found',
            'salesman.gt' => 'Valid salesman not found'
        ]);

        //validate branch id and salesman and stock item qty are same
        $stock = Stock::findOrFail($request->item);

        try {

            DB::beginTransaction();

            if ($stock->qty > 0) {
                //save invoice data

                $invoice = [
                    'customer_name' => $request->name,
                    'customer_nic' => $request->nic,
                    'customer_address' => $request->address,
                    'customer_mobile' => $request->mobile,
                    'customer_land' => $request->land,
                    'date' => $request->date,
                    'branch_id' => $request->branch,
                    'salesman_id' => $request->salesman,
                    'stock_id' => $request->item,
                    'item_id' => $stock->item_id,
                    'amount' => $request->amount,
                    'discount' => $request->discount,
                    'typee' => $request->billType,
                    'note' => $request->note,

                ];

                //if image is selected then upload and save
                if ($request->hasFile('picture')) {
                    $imageName = $request->file('picture')->store('images', 'public');
                    $invoice['image_name'] = $imageName;
                }

                $payment_type = 'Down Payment';
                //if bill type is ready cash then set status is Paid
                if ($request->billType == 'Cash') {
                    $invoice['status'] = 'Complete';
                    $payment_type = 'Payment';
                } else {
                    $invoice['status'] = 'Processing';
                }

                //save invoice data

                //upate invoice code
                $invoice = Invoice::create($invoice);
                $invoice->code = "INV-" . str_pad($invoice->id, 5, '0', STR_PAD_LEFT);
                $invoice->update();
                //save payment data
                //update stock
                $stock->qty--;
                $stock->update();

                //dd($request);

                if (($request->billType == 'Cash') || (($request->billType == 'Installment') && $request->down_payment > 0)) {

                    $payment = [
                        'date' => $request->date,
                        'invoice_id' => $invoice->id,
                        'branch_id' => $invoice->branch_id,
                        'type' => $payment_type,
                        'note' => $request->note,
                    ];

                    if ($request->billType == 'Installment') {
                        $payment['amount'] = $request->down_payment;
                    } else if ($request->billType == 'Cash') {
                        $payment['amount'] = $request->amount - $request->discount;
                    }

                    $payment = Payment::create($payment);
                    $payment->code = 'PYM-' . str_pad($payment->id, 5, '0', STR_PAD_LEFT);
                    $payment->update();
                }


                DB::commit();
                return redirect('invoice/all/' . $request->branch)->with('success', 'Invoice Created Successfully');
            } else {
                return redirect('invoice/create/' . $request->branch)->with('error', 'Sorry! item quantity is not available');
            }
        } catch (\Throwable $e) {
            return redirect('invoice/create/' . $request->branch)->with('error', $e->getMessage());
            DB::rollBack();
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Invoice  $invoice
     * @return \Illuminate\Http\Response
     */
    public function show(Invoice $invoice, $id)
    {
        $invoice = Invoice::with('item', 'salesman', 'stock', 'cancel', 'payment', 'return')
            ->withSum('payment', 'amount')
            ->findOrFail($id);
        return view('invoice/view', compact('invoice'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Invoice  $invoice
     * @return \Illuminate\Http\Response
     */
    public function edit(Invoice $invoice, $id)
    {
        $invoice = Invoice::with('item', 'salesman', 'stock')->findOrFail($id);
        return view('invoice/edit', compact('invoice'));
    }

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

        $request->validate([
            'name' => 'required|string|max:50',
            'nic' => 'string|nullable|max:12',
            'mobile' => 'string|required|max:10',
            'land' => 'string|nullable|max:10',
            'address' => 'string|nullable:max:500',
            'note' => 'string|nullable|max:200',
            'image' => 'nullable|image|mimes:jpg,jpeg,png|max:2048'
        ]);


        $invoice = Invoice::findOrFail($id);
        $invoice->customer_name = $request->name;
        $invoice->customer_nic = $request->nic;
        $invoice->customer_mobile =  $request->mobile;
        $invoice->customer_land = $request->land;
        $invoice->customer_address = $request->address;
        $invoice->note = $request->note;

        try {
            //check image is selected 
            if ($request->hasFile('picture')) {
                //check check previouse image is exist then remove
                if (($invoice->picture_name != "" || $invoice->picture_name != null) && Storage::disk('public')->exists($invoice->picture_name)) {
                    Storage::disk('public')->delete($invoice->picture_name);
                }

                //upate new one
                $imageName = $request->file('picture')->store('images', 'public');
                $invoice['picture_name'] = $imageName;
            } else if ($request->has('picture_remove')) {
                if (($invoice->picture_name != "" || $invoice->picture_name != null) && Storage::disk('public')->exists($invoice->picture_name)) {
                    $invoice->picture_name = '';
                    Storage::disk('public')->delete($invoice->picture_name);
                }
            }

            //update data
            $invoice->update();
        } catch (\Throwable $e) {
            return redirect('invoice/edit/' . $id)->with('error', $e->getMessage());
        }




        return redirect('invoice/edit/' . $id)->with('success', 'Invoice data edited successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Invoice  $invoice
     * @return \Illuminate\Http\Response
     */
    public function destroy(Invoice $invoice, $idInvoice)
    {
        try {
            DB::beginTransaction();
            //validate invoice has payment the warn to remove all payment first
            $invoice = Invoice::with('payment')->find($idInvoice);
            //return $invoice;
            if ($invoice->payment->isNotEmpty()) {
                //dd('data');
                return back()->with('warning', 'Sorry! the invoice has payment. Please remove payment and try again.');
            } else {
                $stock = Stock::findOrFail($invoice->stock_id);
                $stock->qty++;
                $stock->update();
                $invoice->delete();

                DB::commit();
                return back()->with('success', 'Invoice data removed successfully');
            }
        } catch (\Throwable $th) {
            //throw $th;
            DB::rollBack();
            $error = $th->getMessage() . ' / ' . $th->getLine();
            return back()->with('error', $error);
        }
    }


    //get all branches before crete invoice
    public function selectBranch()
    {
        $branches = branch::all();

        return view('invoice/selectBranch', compact('branches'));
    }


    //get invoice data by request
    public function getInvoiceDataByRequest(Request $request)
    {
        $request->validate([
            'invoice' => 'required|integer|gt:0'
        ], [
            'invoice.gt' => 'Please select valid invoice and try again. Thank you '
        ]);

        $invoice = Invoice::with('item', 'payment')->findOrFail($request->invoice);
        $invoices = Invoice::where('branch_id', $invoice->branch_id)->with('item', 'salesman', 'payment')->withSum('payment', 'amount')->orderBy('id', 'desc')->get();

        return view('invoice/payment', compact('invoice', 'invoices'))->with('success', 'Invoice data received');
    }


    public function getInvoiceDataByCustomerNameOrNicOrContactOrBillNumber(Request $request, $idBranch)
    {




        $query = Invoice::query();

        // if ($request->query) {
        //     $query->where('branch_id', $idBranch)->where('code', 'like', '%' . $request->query . '%')
        //         ->orWhere('customer_name', 'like', '%' . $request->query . '%')->orWhere('customer_nic', 'like', '%' . $request->query . '%');
        // }

        //   $invoices = $query->get();


        $invoices = Invoice::with('payment', 'item')->where('branch_id', $idBranch)
            ->where('customer_name', 'like', '%' . $request->query_type . '%')
            ->orWhere('customer_nic', 'like', '%' . $request->query_type . '%')
            ->orWhere('code', 'like', '%' . $request->query_type . '%')
            ->get();
        // $invoices = Invoice::with('item','payment')->where('customer_name','like','%'.$request->query.'%')->get();
        // return $invoices;
        // return 'ssssssssssssss';
        return view('payment/all', compact('invoices', 'idBranch'));
    }


    public function invoiceSummery()
    {


        // $request->validate([
        //     'date_start'=>'required|date',
        //     'date_end'=>'required|date|after:date_start'
        // ]);

        $invoices = Invoice::with('item')->withSum('payment', 'amount')->paginate(5);
        // $invoices = Invoice::with('branch','item')->where('date','>',$request->date_start)->where('date','<',$request->date_end)->get();
        return view('reports/invoiceSummery', compact('invoices'));
        // return 'sssssssss';

    }

    public function invoiceSummerySearch(Request $request)
    {

        // dd($request);

        // $request->validate([
        //     'start_date'=>'required|date',
        //     'end_date'=>'required|date|after:date_start'
        // ]);

        // $invoices = Invoice::all();

        $invoices = Invoice::with('branch', 'item', 'salesman')->whereBetween('date', [$request->strt_date, $request->end_date])->get();
        return view('reports/invoiceSummery', compact('invoices'));
        //return $invoices;
        // dd($invoices);
        // return $invoices;

    }
}
