<?php

namespace App\Http\Controllers;

use App\Sale;
use App\ProductStock;
use App\GoodReceiptTruck;
use App\ProductsCategory;
use App\ProductsCategoryMain;
use App\ProductsSubCategoryParent;
use App\ProductsSubCategoryChild;
use App\Http\Controllers\Controller;
use App\ProductsSubCategory;
use Google\Cloud\Vision\V1\Product;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;

class ProductsCategoryController extends Controller
{
    protected string $module = 'Product Category';

    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']);
        $this->middleware("permission:All Products Inventory list")->only(['allProducts']);
    }

    public function index()
    {
        $product = ProductsCategoryMain::all();
        return view('product_category.index', compact('product'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('product_category.create');
    }

    /** required
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'products_category_name' => 'string|max:255',
            'products_category_name_urdu' => 'nullable|string|max:255',
            'products_category_status' => 'nullable|in:1,0',
        ]);

        $productsCategoryMain = ProductsCategoryMain::create([
            'products_category_name' => $request->products_category_name,
            'products_category_name_urdu' => $request->products_category_name_urdu,
            'products_category_status' => $request->products_category_status,
            'created_by' => auth()->user()->name,
        ]);

        // Create a stock entry for the new product category
        // ProductStock::create([
        //     'pro_cate_main_id' => $productsCategoryMain->id_pro_cate_main,
        //     'quantity' => 0,
        //     'date' => now(),
        //     'status' => '1',
        //     'created_by' => auth()->user()->name,
        // ]);

        session()->flash('success', "New Product Category Added Successfully");
        return redirect('product_cate_main/list');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\ProductsCategory  $productsCategory
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $id = Crypt::decrypt($id);
        $edit = ProductsCategoryMain::where('id_pro_cate_main', $id)->first();

        return view('product_category.edit', compact('edit'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\ProductsCategory  $productsCategory
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $dec_id = Crypt::decrypt($id);

        $request->validate([
            'products_category_name' => 'string|max:255',
            'products_category_name_urdu' => 'nullable|string|max:255',
            'products_category_status' => 'nullable|in:1,0',
        ]);

        $proMain = ProductsCategoryMain::where('id_pro_cate_main', $dec_id)->first();
        $proMain->products_category_name = $request->products_category_name;
        $proMain->products_category_name_urdu = $request->products_category_name_urdu;
        $proMain->products_category_status = $request->products_category_status;
        $proMain->created_by = auth()->user()->name;
        $proMain->save();
        session()->flash('info', "Product Category  Updated  Successfully");
        return redirect('product_cate_main/list');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\ProductsCategory  $productsCategory
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $proCateMain = ProductsCategoryMain::findOrFail($id);
        $hasParentCategories = ProductsSubCategoryParent::where('pro_cate_main_id', $proCateMain->id_pro_cate_main)->exists();

        if ($hasParentCategories) {
            session()->flash('info', "This Category has Parent Categories and cannot be deleted!");
            return redirect()->back();
        }
        $proCateMain->delete();
        session()->flash('warning', "Product Main Category Removed!");
        return redirect()->back();
    }

    // For Product Parent Category
    public function product_cate_parent_list($id)
    {
        $id = Crypt::decrypt($id);
        $product = ProductsCategoryMain::findOrFail($id);
        $productsSubCategoryParent = ProductsSubCategoryParent::where('pro_cate_main_id', $product->id_pro_cate_main)->get();

        return view('product_category.product_sub_cat.product_sub_cat_index', compact('productsSubCategoryParent', 'product'));
    }

    public function product_cate_parent_store(Request $request)
    {
        $request->validate([
            'id_pro_cate_main' => 'required|string|max:255',
            'name' => 'string|max:255',
            'name_urdu' => 'nullable|string|max:255',
            'status' => 'nullable|in:1,0',
        ]);

        $productsSubCategoryParent = ProductsSubCategoryParent::create([
            'pro_cate_main_id' => $request->id_pro_cate_main,
            'name' => $request->name,
            'name_urdu' => $request->name_urdu,
            'status' => $request->status,
            'created_by' => auth()->user()->name,
        ]);

        session()->flash('success', "New Product Sub Parent Category Added Successfully");
        return redirect()->back();
    }

    public function product_cate_parent_update(Request $request, $id)
    {
        $request->validate([
            'id_pro_cate_main' => 'required|string|max:255',
            'name' => 'string|max:255',
            'name_urdu' => 'nullable|string|max:255',
            'status' => 'nullable|in:1,0',
        ]);

        $proCateParent = ProductsSubCategoryParent::findOrFail($id);
        $proCateParent->name = $request->name;
        $proCateParent->name_urdu = $request->name_urdu;
        $proCateParent->status = $request->status;
        $proCateParent->created_by = auth()->user()->name;
        $proCateParent->save();

        session()->flash('success', "Product Parent Category Updated Successfully");
        return redirect()->back();
    }

    public function product_cate_parent_destroy($id)
    {
        $proCateParent = ProductsSubCategoryParent::findOrFail($id);
        $hasChildCategories = ProductsSubCategoryChild::where('pro_sub_cat_parent_id', $proCateParent->id_pro_sub_cat_parent)->exists();

        if ($hasChildCategories) {
            session()->flash('info', "This Category has Child Categories and cannot be deleted!");
            return redirect()->back();
        }
        $proCateParent->delete();
        session()->flash('warning', "Product Parent Category Removed!");
        return redirect()->back();
    }

    // For Product Child Category
    public function product_cate_child_list($p_id, $id)
    {
        $id = Crypt::decrypt($id);
        $p_id = Crypt::decrypt($p_id);
        $product = ProductsCategoryMain::findOrFail($p_id);
        $currentSubCategory = ProductsSubCategoryParent::findOrFail($id);
        // $productsSubCategoryChild = ProductsSubCategoryChild::all();
        $productsSubCategoryChild = ProductsSubCategoryChild::where('pro_sub_cat_parent_id', $currentSubCategory->id_pro_sub_cat_parent)->get();

        return view('product_category.product_sub_sub_cat.product_sub_cat_index', compact('productsSubCategoryChild', 'product', 'currentSubCategory'));
    }

    public function product_cate_child_store(Request $request)
    {
        $request->validate([
            'pro_sub_cat_parent_id' => 'required|string|max:255',
            'name' => 'string|max:255',
            'name_urdu' => 'nullable|string|max:255',
            'status' => 'nullable|in:1,0',
        ]);

        $productsSubCategoryChild = ProductsSubCategoryChild::create([
            'pro_sub_cat_parent_id' => $request->pro_sub_cat_parent_id,
            'name' => $request->name,
            'name_urdu' => $request->name_urdu,
            'status' => $request->status,
            'created_by' => auth()->user()->name,
        ]);

        session()->flash('success', "New Product Sub Child Category Added Successfully");
        return redirect()->back();
    }

    public function product_cate_child_update(Request $request, $id)
    {
        $request->validate([
            'pro_sub_cat_parent_id' => 'required|string|max:255',
            'name' => 'string|max:255',
            'name_urdu' => 'nullable|string|max:255',
            'status' => 'nullable|in:1,0',
        ]);

        $proCateChild = ProductsSubCategoryChild::findOrFail($id);
        $proCateChild->name = $request->name;
        $proCateChild->name_urdu = $request->name_urdu;
        $proCateChild->status = $request->status;
        $proCateChild->created_by = auth()->user()->name;
        $proCateChild->save();

        session()->flash('success', "Product Child Category Updated Successfully");
        return redirect()->back();
    }

    public function product_cate_child_destroy($id)
    {
        $proCateChild = ProductsSubCategoryChild::findOrFail($id);
        if ($proCateChild) {
            $proCateChild->delete();
        }
        session()->flash('warning', "Product Child Category Removed!");
        return redirect()->back();
    }

    public function allProducts()
    {
        // Fetch products with their parent and child categories
        $products = ProductsCategoryMain::with(['subCategoriesParent', 'subCategoriesParent.subCategoriesChild'])->get();

        // Fetch sales details and truck goods receipts
        $sales = Sale::with(['salesItemsDetails', 'goodReceiptTruck', 'customer'])->get();
        $good_receipts_truck = GoodReceiptTruck::with([
            'goodReceipts' => function ($query) {
                $query->with(['goodReceiptDetails.productMainCate', 'goodReceiptDetails.productParentCate', 'goodReceiptDetails.productChildCate', 'supplier']);
            }
        ])->get();

        return view('products.allproducts', compact('good_receipts_truck', 'products', 'sales'));
    }


    // base old
    // public function allProducts()
    // {
    //     $products = ProductsSubCategory::with(['subCategories'])->get();
    //     $good_receipts_truck = GoodReceiptTruck::with(['goodReceipts.goodReceiptDetails', 'goodReceipts.supplier'])->get();
    //     $sales = Sale::with(['salesItemsDetails', 'salesPerBoriWeight', 'customer', 'goodReceiptTruck', 'goodReceiptTruck.goodReceiptDetails'])->get();
    //     return view('products.allproducts', compact('good_receipts_truck'));
    // }
}
