<?php

namespace App\Http\Controllers;

use App\Suppliers;
use App\Products;
use App\ProductsCategory;
use App\ProductsSubCategory;
use App\ProductsCategoryMain;
use App\ProductsSubCategoryParent;
use App\ProductsSubCategoryChild;
use App\GoodReceipts;
use App\GoodReceiptTruck;
use App\GoodReceiptDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;

class GoodReceiptsController extends Controller
{
    protected string $module = 'Goods Receipts';

    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()
    {
        $good_receipts_truck = GoodReceiptTruck::with([
            'goodReceipts' => function ($query) {
                $query->with(['goodReceiptDetails.productMainCate', 'goodReceiptDetails.productParentCate', 'goodReceiptDetails.productChildCate', 'supplier', 'createdBy']);
            }
        ])->latest()->get();


        return view('goods_receipts.index', compact('good_receipts_truck'));
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $productCateMain = ProductsCategoryMain::all();
        $suppliers = Suppliers::all();
        return view('goods_receipts.create', compact('suppliers', 'productCateMain'));
    }

    public function checkCateParent(Request $request)
    {
        $productMainCateId = $request->input('productMainCateId');
        $productParentCate = ProductsSubCategoryParent::where('pro_cate_main_id', $productMainCateId)->get();

        if ($productParentCate->isNotEmpty()) {
            return response()->json([
                'productParentCate' => $productParentCate
            ]);
        } else {
            return response()->json(['productParentCate' => []]);
        }
    }

    public function checkCateChild(Request $request)
    {
        $productParentCateId = $request->input('productParentCateId');
        $productChildCate = ProductsSubCategoryChild::where('pro_sub_cat_parent_id', $productParentCateId)->get();

        if ($productChildCate->isNotEmpty()) {
            return response()->json([
                'productChildCate' => $productChildCate
            ]);
        } else {
            return response()->json(['productChildCate' => []]);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // Validate the request data
        $request->validate([
            'goods_date' => 'nullable|date',
            'truck_number' => 'required|string|max:255',
            'suppliers' => 'required|exists:suppliers,id_supplier',
            'builty_number' => 'nullable|string|max:255',
            'rent_received' => 'nullable|string',
            'goods_status' => 'required|in:1,0',
            'details' => 'nullable|string',
            'marka.*' => 'nullable|string|max:255',
            'bori.*' => 'required|numeric',
            //            'weight.*' => 'required|numeric',
            'rate.*' => 'nullable|numeric',
            'amount.*' => 'nullable|numeric',
            'remarks.*' => 'nullable|string',
            'productMainCate.*' => 'nullable|string',
            'productParentCate.*' => 'nullable|string',
            'productChildCate.*' => 'nullable|string',
        ]);

        // Create the GoodReceiptTruck entry
        $truck = GoodReceiptTruck::create(['truck_no' => $request->truck_number]);

        // Create the GoodReceipts entry
        $goodReceipt = GoodReceipts::create([
            'business_id' => auth()->user()->business_id,
            'supplier_id' => $request->suppliers,
            'good_receipts_truck_id' => $truck->id_truck,
            'date' => $request->goods_date,
            'p_no' => $request->p_no,
            'builty_no' => $request->builty_number,
            'rent_recieve' => $request->rent_received,
            'details' => $request->details,
            'status' => $request->goods_status,
            'created_by' => auth()->user()->id,
        ]);

        // Store GoodReceiptDetails
        foreach ($request->productMainCate as $key => $item) {
            // $product = Products::where('id_products', $item)->first();

            // if ($product) {
            //     $product->in_stock += $request->bori[$key] ?? 0;
            //     $product->save();
            // }

            GoodReceiptDetail::create([
                'good_receipts_id' => $goodReceipt->id_good_rec,
                'truck_id' => $truck->id_truck,
                'marka' => $request->marka[$key] ?? null,
                'bori' => $request->bori[$key] ?? null,
                'total_bori' => $request->bori[$key] ?? null,
                'weight' => $request->weight[$key] ?? null,
                'rate' => $request->rate[$key] ?? null,
                'amount' => $request->amount[$key] ?? null,
                'remarks' => $request->remarks[$key] ?? null,
                'pro_cate_main_id' => $request->productMainCate[$key] ?? null,
                'pro_cate_parent_id' => $request->productParentCate[$key] ?? null,
                'pro_cate_child_id' => $request->productChildCate[$key] ?? null,
            ]);
        }

        return redirect()->route('good_receipts.list')->with('success', 'Goods Receipt created successfully!');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\GoodReceipts  $goodReceipts
     * @return \Illuminate\Http\Response
     */
    public function show(GoodReceipts $goodReceipts)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\GoodReceipts  $goodReceipts
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $id = Crypt::decrypt($id);
        $goodReceipt = GoodReceipts::with(
            'goodReceiptDetails',
            'goodReceiptTruck',
            'goodReceiptDetails.productMainCate',
            'goodReceiptDetails.productParentCate',
            'goodReceiptDetails.productChildCate'
        )->findOrFail($id);
        $productCateMain = ProductsCategoryMain::all();
        $suppliers = Suppliers::all();

        return view('goods_receipts.edit', compact('goodReceipt', 'suppliers', 'productCateMain'));
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\GoodReceipts  $goodReceipts
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // Validate the request data
        $request->validate([
            'goods_date' => 'nullable|date',
            'truck_number' => 'required|string|max:255',
            'suppliers' => 'required|exists:suppliers,id_supplier',
            'builty_number' => 'nullable|string|max:255',
            'rent_received' => 'nullable|string',
            'goods_status' => 'required|in:1,0',
            'details' => 'nullable|string',
            'marka.*' => 'nullable|string|max:255',
            'bori.*' => 'nullable|numeric',
            //            'weight.*' => 'nullable|numeric',
            'rate.*' => 'nullable|numeric',
            'amount.*' => 'nullable|numeric',
            'remarks.*' => 'nullable|string',
            'productMainCate.*' => 'nullable|string',
            'productParentCate.*' => 'nullable|string',
            'productChildCate.*' => 'nullable|string',
        ]);

        DB::transaction(function () use ($request, $id) {
            $goodReceipt = GoodReceipts::findOrFail($id);

            // Update the truck info
            $truck = $goodReceipt->goodReceiptTruck;
            $truck->update([
                'truck_no' => $request->truck_number
            ]);

            // Update the main good receipt record
            $goodReceipt->update([
                'supplier_id' => $request->suppliers,
                'good_receipts_truck_id' => $truck->id_truck,
                'date' => $request->goods_date,
                'p_no' => $request->p_no,
                'builty_no' => $request->builty_number,
                'rent_recieve' => $request->rent_received,
                'details' => $request->details,
                'status' => $request->goods_status,
            ]);

            // Remove existing details and create new ones
            $goodReceipt->goodReceiptDetails()->delete();

            foreach ($request->productMainCate as $key => $item) {
                GoodReceiptDetail::create([
                    'good_receipts_id' => $goodReceipt->id_good_rec,
                    'truck_id' => $truck->id_truck,
                    'marka' => $request->marka[$key] ?? null,
                    'bori' => $request->bori[$key] ?? null,
                    'total_bori' => $request->bori[$key] ?? null,
                    'weight' => $request->weight[$key] ?? null,
                    'rate' => $request->rate[$key] ?? null,
                    'amount' => $request->amount[$key] ?? null,
                    'remarks' => $request->remarks[$key] ?? null,
                    'pro_cate_main_id' => $request->productMainCate[$key] ?? null,
                    'pro_cate_parent_id' => $request->productParentCate[$key] ?? null,
                    'pro_cate_child_id' => $request->productChildCate[$key] ?? null,
                ]);
            }
        });

        return redirect()->route('good_receipts.list')->with('success', 'Goods Receipt updated successfully!');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\GoodReceipts  $goodReceipts
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $goodReceiptId = Crypt::decrypt($id);

        $goodReceipt = GoodReceipts::findOrFail($goodReceiptId);

        $goodReceipt->goodReceiptDetails()->delete();

        $goodReceipt->goodReceiptTruck()->delete();

        $goodReceipt->delete();

        return redirect()->route('good_receipts.list')->with('success', 'Goods Receipt deleted successfully!');
    }
}
