<?php

namespace App\Http\Controllers;

use App\GoodReceiptTruck;
use App\PurchaseOrder;
use App\PurchaseOrderDetails;
use App\SalesItemDetail;
use App\Suppliers;
use App\supplier_brand;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;

class PurchaseorderController extends Controller
{
    public function index()
    {
        $purchase_order = PurchaseOrder::with(['Purchasedetails', 'supplier'])->get();
        // dd($purchase_order);  // Debugging the data
        return view('purchase_order.index', compact('purchase_order'));
    }
    public function create()
    {
        $supplier = Suppliers::all();
        $trucks = GoodReceiptTruck::all();
        return view('purchase_order.create', compact('supplier', 'trucks'));
    }

    // public function store(Request $request)
    // {
    //     dd($request);
    //     $request->validate([
    //         'supplier_name' => 'required',
    //         'date' => 'required',
    //         'products' => 'required|array',
    //         'products.*.productId' => 'required',
    //         'products.*.brand' => 'required',
    //         'products.*.product' => 'required',
    //         'products.*.currency' => 'required',
    //         'products.*.unitPrice' => 'required|numeric',
    //         'products.*.qty' => 'required|integer',
    //         'products.*.totalPrice' => 'required|numeric',
    //     ]);

    //     foreach ($request->products as $product) {
    //         PurchaseOrder::create([
    //             'supplier_name' => $request->supplier_name,
    //             'date' => $request->date,
    //             'product_id' => $product['productId'],
    //             'brand' => $product['brand'],
    //             'purchase_order' => $product['purchase_order'],
    //             'currency' => $product['currency'],
    //             'unit_price' => $product['unitPrice'],
    //             'qty' => $product['qty'],
    //             'total_price' => $product['totalPrice'],
    //         ]);
    //     }
    //     return redirect()->route('po.list')->with('success', 'Purchase Order created successfully.');
    // }

    public function store(Request $request)
    {
        $request->validate([
            'po_date' => 'required|date',
            'po_no' => 'required|string',
            // 'good_receipts_truck_id' => 'required|exists:good_receipts_truck,id_truck',
            'supplier_id' => 'required|exists:customers,id_customers',
            // 'bill_no' => 'required|string',
            'details' => 'nullable|string',
            // 'bori_details' => 'nullable|string',
            'total_bori' => 'nullable|numeric',
            'bori_weight' => 'nullable|numeric',
            'rent_recieve' => 'nullable|numeric',
            'labour' => 'nullable|numeric',
            // 'remaining_amount' => 'nullable|numeric',
            // 'cash_received' => 'nullable|numeric',
            // 'total_amount' => 'nullable|numeric',
            'items_name.*' => 'required|string',
            'marka.*' => 'required|string',
            'bori.*' => 'required|numeric',
            'weight.*' => 'required|numeric',
            'rate.*' => 'required|numeric',
            'amount.*' => 'nullable|numeric',
        ]);

        // Po
        $po = PurchaseOrder::create([
            'business_id' => auth()->user()->business_id,
            // 'good_receipts_truck_id' => $request->good_receipts_truck_id,
            'supplier_id' => $request->supplier_id,
            'date' => $request->po_date,
            'po_no' => $request->po_no,
            // 'bill_no' => $request->bill_no,
            'details' => $request->details,
            'rent_recieve' => $request->rent_recieve,
            'labour' => $request->labour,
            // 'bori_details' => $request->bori_details,
            // 'balance' => $request->remaining_amount,
            // 'paid' => $request->cash_received,
            // 'total_amount' => $request->total_amount,
            'status' => $request->po_status,
            'created_by' => auth()->id(),
        ]);

        // Item Details
        $items = $request->items_name;
        $marka = $request->marka;
        $bori = $request->bori;
        $weight = $request->weight;
        $rate = $request->rate;
        $amount = $request->amount;

        foreach ($items as $index => $item) {
            $poItemDetail = PurchaseOrderDetails::create([
                'purchase_order_id' => $po->id_purchase_order,
                'items_name' => $item,
                'marka' => $marka[$index],
                'bori' => $bori[$index],
                'weight' => $weight[$index],
                'rate' => $rate[$index],
                'amount' => $amount[$index],
                'notes' => 'N/A',
                'status' => '1',
            ]);
        }

        // // Additional Bori Details
        // $bori_num = $request->bori_number;
        // $bori_weight = $request->per_bori_weight;

        // foreach ($bori_num as $index => $bori) {
        //     $salesPerBori = SalesPerBoriWeight::create([
        //         'sales_items_details_id' => $salesItemDetail->id_sid,
        //         'bori_number' => $bori_num[$index],
        //         'per_bori_weight' => $bori_weight[$index],
        //     ]);
        // }

        // dd($po,  $poItemDetail);
        return redirect()->route('po.list')->with('success', 'PO created successfully');
    }

    public function edit($id)
    {
        $id = Crypt::decrypt($id);
        $purchase_order = PurchaseOrder::findOrFail($id);
        $purchase_orderdet = PurchaseOrderDetails::where('purchase_order_id', $id)->first();
        $suppliers = Suppliers::all();

        return view('purchase_order.edit', [
            'purchase_order' => $purchase_order,
            'suppliers' => $suppliers,
            'purchase_orderdet' => $purchase_orderdet
        ]);
    }
    public function update(Request $request, $id)
    {
        $id = Crypt::decrypt($id);

        // Validate incoming request data
        $request->validate([
            'po_date' => 'required|date',
            'po_no' => 'required|string',
            'supplier_id' => 'required|exists:suppliers,id_supplier', // Updated validation rule
            'details' => 'nullable|string',
            'total_bori' => 'nullable|numeric',
            'bori_weight' => 'nullable|numeric',
            'rent_recieve' => 'nullable|numeric',
            'labour' => 'nullable|numeric',
            'items_name.*' => 'required|string',
            'marka.*' => 'required|string',
            'bori.*' => 'required|numeric',
            'weight.*' => 'required|numeric',
            'rate.*' => 'required|numeric',
            'amount.*' => 'nullable|numeric',
        ]);

        $purchase_order = PurchaseOrder::findOrFail($id);

        // Update the purchase order
        $purchase_order->update([
            'supplier_id' => $request->supplier_id,
            'date' => $request->po_date,
            'po_no' => $request->po_no,
            'details' => $request->details,
            'rent_recieve' => $request->rent_recieve,
            'labour' => $request->labour,
            'status' => $request->po_status,
            'updated_by' => auth()->id(), // Use updated_by for tracking updates
        ]);

        // Delete existing details
        PurchaseOrderDetails::where('purchase_order_id', $id)->delete();

        // Insert updated details
        $items = $request->items_name;
        $marka = $request->marka;
        $bori = $request->bori;
        $weight = $request->weight;
        $rate = $request->rate;
        $amount = $request->amount;

        foreach ($items as $index => $item) {
            PurchaseOrderDetails::create([
                'purchase_order_id' => $id,
                'items_name' => $item,
                'marka' => $marka[$index],
                'bori' => $bori[$index],
                'weight' => $weight[$index],
                'rate' => $rate[$index],
                'amount' => $amount[$index],
                'notes' => 'N/A',
                'status' => '1',
            ]);
        }

        return redirect()->route('po.list')->with('success', 'Purchase order updated successfully!');
    }


    public function destroy($id)
    {
        $purchase_order = PurchaseOrder::findOrFail(Crypt::decrypt($id));
        $purchase_order->delete();
        return redirect()->route('po.list')->with('success', 'Purchase Order deleted successfully');
    }
}
