<?php

namespace App\Http\Controllers;

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

class PurchaseorderController extends Controller
{

    protected string $module = 'Purchase Order';

    public function __construct()
    {
        $module = $this->module;

        $this->middleware("permission:$module list")->only(['index']);
        $this->middleware("permission:$module view")->only(['show']);
        $this->middleware("permission:$module add")->only(['create', 'store']);
        $this->middleware("permission:$module edit")->only(['edit', 'update']);
        $this->middleware("permission:$module delete")->only(['destroy']);
    }
    public function index()
    {
        $purchase_order = PurchaseOrder::with(['Purchasedetails', 'purchaser', 'createdBy', 'Purchasedetails.proCateChild'])->latest()->get();
        return view('purchase_order.index', compact('purchase_order'));
    }
    public function create()
    {
        $purchasers = Purchaser::where('status', 1)->get();
        $productCateMain = ProductsCategoryMain::all();
        $trucks = GoodReceiptTruck::all();
        return view('purchase_order.create', compact('purchasers', 'productCateMain', '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)
    // {
    //     dd($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 store(Request $request)
    {
        // dd($request);
        $request->validate([
            'purchasers' => 'required|exists:purchasers,id_purchaser',
            'order_date' => 'required|date',
            'details' => 'nullable|string',

            'productMainCate.*' => 'required|integer',
            'productParentCate.*' => 'required|integer',
            'productChildCate.*' => 'required|integer',

            'marka.*' => 'required|string',
            'bori.*' => 'required|numeric',
            'weight.*' => 'required|numeric',
            'rate.*' => 'required|numeric',
            'amount.*' => 'nullable|numeric',
        ]);


        $po = PurchaseOrder::create([
            'business_id' => auth()->user()->business_id,
            'purchaser_id' => $request->purchasers,
            'order_date' => $request->order_date,
            'notes' => $request->details,
            'status' => 'pending',
            'total_amount' => 0,
            'custom_charges' => $request->custom_charges,
            'labour_charges' => $request->labour_charges,
            'local_charges' => $request->local_charges,
            'weight_charges' => $request->weight_charges,
            'tax' => $request->tax,
            'grand_total' => 0,
            'created_by' => auth()->id(),
        ]);


        $po->po_number = 'PO-' . str_pad($po->id, 6, '0', STR_PAD_LEFT);
        $po->save();
        $totalAmount = 0;
        $countItems = count($request->productMainCate);

        for ($i = 0; $i < $countItems; $i++) {


            $itemAmount = $request->amount[$i]
                ? floatval($request->amount[$i])
                : (floatval($request->weight[$i]) * floatval($request->rate[$i])) / 40;

            $totalAmount += $itemAmount;

            // Save item detail
            PurchaseOrderDetails::create([
                'purchase_order_id' => $po->id,
                'pro_cate_main_id' => $request->productMainCate[$i],
                'pro_cate_parent_id' => $request->productParentCate[$i],
                'pro_cate_child_id' => $request->productChildCate[$i],
                'marka' => $request->marka[$i],
                'bori' => $request->bori[$i],
                'weight' => $request->weight[$i],
                'rate' => $request->rate[$i],
                'amount' => $itemAmount,
                'created_by' => auth()->id(),

            ]);
        }


        $po->total_amount = $totalAmount;
        $po->grand_total = $totalAmount + ($po->custom_charges ?? 0) + ($po->tax ?? 0) + ($po->labour_charges ?? 0) + ($po->local_charges ?? 0) + ($po->weight_charges ?? 0);
        $po->save();

        return redirect()->route('po.list')->with('success', 'Purchase Order created successfully');
    }


    public function edit($id)
    {
        $dec_id = Crypt::decrypt($id);

        $purchase_order = PurchaseOrder::with('Purchasedetails')->findOrFail($dec_id);

        $purchasers = Purchaser::where('status', 1)->get();
        $productCateMain = ProductsCategoryMain::all();
        return view('purchase_order.edit', [
            'po' => $purchase_order,
            'purchasers' => $purchasers,
            'productCateMain' => $productCateMain,
        ]);
    }
    public function update(Request $request, $id)
    {
        $dec_id = Crypt::decrypt($id);


        $request->validate([
            'purchasers' => 'required|exists:purchasers,id_purchaser',
            'order_date' => 'required|date',
            'details' => 'nullable|string',

            'productMainCate.*' => 'required|integer',
            'productParentCate.*' => 'required|integer',
            'productChildCate.*' => 'required|integer',

            'marka.*' => 'required|string',
            'bori.*' => 'required|numeric',
            'weight.*' => 'required|numeric',
            'rate.*' => 'required|numeric',
            'amount.*' => 'nullable|numeric',
        ]);

        // Fetch PO
        $po = PurchaseOrder::findOrFail($dec_id);

        // Update PO fields
        $po->purchaser_id = $request->purchasers;
        $po->order_date = $request->order_date;
        $po->notes = $request->details;
        $po->custom_charges = $request->custom_charges;
        $po->labour_charges = $request->labour_charges;
        $po->local_charges = $request->local_charges;
        $po->weight_charges = $request->weight_charges;

        $po->tax = $request->tax;
        $po->save();

        PurchaseOrderDetails::where('purchase_order_id', $po->id)->delete();

        $totalAmount = 0;
        $countItems = count($request->productMainCate);

        for ($i = 0; $i < $countItems; $i++) {

            $itemAmount = (floatval($request->weight[$i]) * floatval($request->rate[$i])) / 40;

            $totalAmount += $itemAmount;

            PurchaseOrderDetails::create([
                'purchase_order_id' => $po->id,
                'pro_cate_main_id' => $request->productMainCate[$i],
                'pro_cate_parent_id' => $request->productParentCate[$i],
                'pro_cate_child_id' => $request->productChildCate[$i],
                'marka' => $request->marka[$i],
                'bori' => $request->bori[$i],
                'weight' => $request->weight[$i],
                'rate' => $request->rate[$i],
                'amount' => $itemAmount,
                'updated_by' => auth()->id(),
            ]);
        }

        $po->total_amount = $totalAmount;
        $po->grand_total = $totalAmount + ($po->custom_charges ?? 0) + ($po->tax ?? 0) + ($po->labour_charges ?? 0) + ($po->local_charges ?? 0) + ($po->weight_charges ?? 0);
        $po->save();

        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');
    }
}
