<?php

namespace App\Http\Controllers;

use App\Models\AccountReceavable;
use App\Models\CashBook;
use App\Models\Client;
use App\Models\Invoice;
use App\Models\InvoiceTest;
use Illuminate\Http\Request;
//use Cart;
use App\Models\Test;
use function Symfony\Component\String\b;

class InvoiceController extends Controller
{
    public function index()
    {
        return view('admin.invoice.index');
    }
    public function list()
    {
        // Fetch all invoices ordered by 'id' in descending order
        $invoices = Invoice::orderBy('id', 'desc')->get();

        // Pass the invoices to the view
        return view('admin.invoice.list', compact('invoices'));
    }
    public function receipt($id)
    {
        $invoice = Invoice::where('id',$id)->get()->first();
        $invoiceTest = InvoiceTest::where('invoice_id', $id)->get();
        return view('admin.invoice.receipt',[
            'invoiceTests' => $invoiceTest,
            'invoice' => $invoice
        ]);
    }
    public function find(Request $request)
    {
        $invoice = Invoice::where('id', $request->invoiceId)->first();
        return view('admin.invoice.edit', [
            'invoice' => $invoice
        ]);

    }


    public function invoiceStore(Request $request)
    {
        // Validate request
        $request->validate([
            'mobile' => 'required|numeric',
            'subtotal' => 'required|numeric',
            'discount' => 'nullable|numeric',
            'total' => 'required|numeric',
            'test_ids' => 'required|array',
        ]);

        // Check if client exists, create if not
        $client = Client::where('mobile', $request->mobile)->first();

        if (!$client) {

            $client = new Client();
            $client->name        = $request->name;
            $client->mobile      = $request->mobile;
            $client->gender      = $request->sex;
            $client->age         = $request->age;
            $client->save();
        }

        $clientID = $client->id;

        // Save the invoice
        $invoice = new Invoice();
        $invoice->date = date('Y-m-d');
        $invoice->client_id = $clientID;
        $invoice->subtotal = $request->subtotal;
        $invoice->discount = $request->discount ?? 0; // Default to 0 if not provided
        $invoice->total = $request->total;
        $invoice->received = $request->received;
        $invoice->dr = $request->dr;
        $invoice->save();

        // Save the invoice tests
        foreach ($request->input('test_ids') as $index => $testId) {
            $invoiceTest = new InvoiceTest();
            $invoiceTest->invoice_id = $invoice->id;
            $invoiceTest->test_id = $testId;
            $invoiceTest->save();
        }
        // Redirect or return response
//        return redirect()->back()->with('success', 'Invoice saved successfully!');
        $invoices = Invoice::where('id',$invoice->id)->get()->first();
        $invoiceTest = InvoiceTest::where('invoice_id', $invoice->id)->get();
        $invoiceId = $invoices->id;
        if ($request->received != 0)
        {
            CashBook::invoice($request, $invoiceId);
        }
//        $due = $request->total - $request->received;
////        if ($due != 0)
////        {
////            AccountReceavable::invoice($request, $clientID);
////        }

        return view('admin.invoice.receipt',[
            'invoiceTests' => $invoiceTest,
            'invoice' => $invoices
        ]);

    }
    public function edit()
    {
        return view('admin.invoice.edit');
    }

    public function update(Request $request)
    {

        $invoice = Invoice::where('id', $request->id)->first();

        $invoice->received+= $request->received;
        $invoice->save();
        if ($request->received != 0)
        {
            CashBook::invoice($request,  $request->id);
        }
        $invoiceTest = InvoiceTest::where('invoice_id', $request->id)->get();
        return view('admin.invoice.receipt',[
            'invoiceTests' => $invoiceTest,
            'invoice' => $invoice
        ]);
    }

//    public function update(Request $request)
//    {
//        $invoice = Invoice::find($request->id);
//
//        // Calculate the current due amount
//        $dueAmount = $invoice->total - $invoice->received;
//
//        // Validate the received amount
//        $request->validate([
//            'received' => ['required', 'numeric', 'max:'.$dueAmount],
//        ], [
//            'received.max' => 'Received amount cannot be greater than the remaining due amount.',
//        ]);
//
//        // Update the invoice
//        $invoice->received += $request->received;
//        $invoice->save();
//
//        return redirect()->back()->with('success', 'Invoice updated successfully.');
//    }


    public function liveSearch(Request $request)
    {
        $query = $request->input('query');
        $invoices = Invoice::where('id', 'like', "%{$query}%")
            ->orWhereHas('client', function($q) use ($query) {
                $q->where('name', 'like', "%{$query}%");
            })
            ->take(5)  // Limit suggestions
            ->get(['id', 'client_name', 'total', 'received', 'due']);  // Add any additional fields needed

        return response()->json($invoices);
    }

    public function due()
    {
        // Fetch all invoices where 'total' is not equal to 'received'
        $invoices = Invoice::whereColumn('total', '!=', 'received')->get();

        // Pass the invoices to the view
        return view('admin.invoice.list', compact('invoices'));
    }




//    public function addCart(Request $request)
//    {
//        $this->product = Test::find($request->id);
//        Cart::add([
//            'id'      => $request->id,
//            'name'    => $this->product->name,
//            'qty'     => $request->qty,
//            'price'   => $this->product->selling_price,
//            'options' => [
//                'code'  => $this->product->code,
//                'image' => $this->product->image,
//            ]
//        ]);
//        return redirect('/card-show');
//    }
}
