<?php

namespace App\Http\Controllers;

use App\Models\Branch;
use App\Models\ChartOfAccount;
use App\Models\Company;
use App\Models\Product;
use App\Models\Project;
use App\Models\QuickSales;
use Illuminate\Http\Request;
use App\Models\QuickSalesProduct;
use App\Models\Supplier;
use Carbon\Carbon;

class QuickController extends Controller
{
    public function index()
    {
        return view('backend.pages.quick_sales.qsalsecreate');
    }
    public function report()
    {

        $title = 'Quick Purchase Report';
        $companyInfo = Company::latest('id')->first();
        $ledgers = ChartOfAccount::where('parent_id', 0)->get();
        $projects = Project::get();
        $branch = Branch::where('status', 'Active')->get();
        $supplier = Supplier::get()->where('status', 'Active');
        $product = Product::get()->where('status', 'Active');
        return view('backend.pages.reports.quicksale', get_defined_vars());
    }

    public function search(Request $request)
    {
        $query = QuickSales::query();


        if ($request->has('branch_id') && !empty($request->branch_id)) {
            $query->where('branch_id', $request->branch_id);
        }

        if ($request->has('dateRange') && !empty($request->dateRange)) {
            $dates = explode(' - ', $request->dateRange);
            $fromDate = Carbon::parse($dates[0])->startOfDay();
            $toDate = Carbon::parse($dates[1])->endOfDay();
            $query->whereBetween('date', [$fromDate, $toDate]);
        }

        $purchaseDetails = $query->get();




        return view('helpers', compact('purchaseDetails', 'fromDate', 'toDate'));
    }


    public function list()
    {
        $quickSales = QuickSales::all();

        return view('backend.pages.quick_sales.quicksaleslist', get_defined_vars());
    }

    public function store(Request $request)
    {

     


        $quickSale = QuickSales::create([
           'date' => $request->input('date'),
            'ledger_id' => $request->input('ledger_id'),
            'branch_id' => $request->input('branch_id'),
            'discount' => $request->discount,
            'received_amount' => 0, // Keeping original request variable name
            'payment_status' => 'due',
            'delivery_status' => $request->input('delivery_status'),
            'total_amount' => $request->reaminign,
            'due_balance' => $request->reaminign,
            'shipping_charge' => $request->shipping_charge,
        ]);


        foreach ($request->products as $product) {
            QuickSalesProduct::create([
                'sale_id' => $quickSale->id,
                'product_name' => $product['productName'],
                'price' => $product['price'],
                'quantity' => $product['quantity'],
                'total_price' => $product['totalPrice'],
                'productSpecification' => $product['productSpecification'],
                'fabric' => $product['fabric'],
                'fabricSpecification' => $product['fabricSpecification'],
            ]);
        }

        return redirect()->route('quick.sales.list')->with('message', 'Order created successfully!');
    }

    public function show($id)
    {
        $order = QuickSales::with('products')->findOrFail($id);
        return view('backend.pages.quick_sales.show', get_defined_vars());
    }

    public function edit($id)
    {
        $order = QuickSales::with('products')->findOrFail($id);
        return view('backend.pages.quick_sales.edit', get_defined_vars());
    }

    public function update(Request $request, $id)
    {
        $quickSale = QuickSales::findOrFail($id);

        $quickSale->update([
            'date' => $request->input('date'),
            'ledger_id' => $request->input('ledger_id'),
            'branch_id' => $request->input('branch_id'),
            'discount' => $request->discount,
            'received_amount' => 0, // Keeping original request variable name
            'payment_status' => 'due',
            'delivery_status' => $request->input('delivery_status'),
            'total_amount' => $request->reaminign,
            'due_balance' => $request->reaminign,
            'shipping_charge' => $request->shipping_charge,
        ]);

        // Get existing product IDs from the request
        $existingProducts = is_array($request->existingProducts) ? $request->existingProducts : [];

        // Delete products that are not in the existingProducts array
        QuickSalesProduct::where('sale_id', $id)
            ->whereNotIn('id', $existingProducts)
            ->delete();

        // Check if new products exist in the request
        if (!empty($request->productName)) {
            foreach ($request->productName as $key => $productName) {
                $productId = $request->productid[$key] ?? null;
        
                if ($productId === "undefined" || empty($productId)) {
                    QuickSalesProduct::create([
                        'sale_id' => $id,
                        'product_name' => $productName, // Fixed variable reference
                        'price' => $request->price[$key] ?? 0,
                        'quantity' => $request->quantity[$key] ?? 1, // Fixed reference
                        'total_price' => $request->totalPrice[$key] ?? 0, // Fixed reference
                        'fabric' => $request->fabric[$key] ?? 0, // Fixed reference
                        'productSpecification' => $request->productSpecification[$key] ?? null, // Fixed reference
                        'fabricSpecification' => $request->fabricSpecification[$key] ?? null, // Fixed reference
                    ]);
                }
            }
        }
        

        return redirect()->route('quick.sales.list')
            ->with('message', 'Order updated successfully!');
    }


    public function delete($id)
    {
        $quicksales = QuickSales::find($id);

        $quicksales->delete();

        return redirect()->back();
    }
}
