<?php

namespace App\Http\Controllers;

use App\Models\CategoryModel;
use App\Models\ProductHistoryModel;
use App\Models\ProductModel;
use App\Models\UomModel;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    protected $branch_id;

    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            $this->branch_id = session('branch_id');
            return $next($request);
        });
    }

    public function index()
    {
        // $categories = CategoryModel::where('branch_id', $this->branch_id)
        //     ->orderBy('id', 'desc')
        //     ->get();
         $categories = CategoryModel::orderBy('id', 'desc')
            ->get();

        return view('categories.index', compact('categories'));
    }

    public function add()
    {
        $uoms = UomModel::all();
        return view('categories.add', compact('uoms'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'categoryName' => 'required|string|max:255|unique:categories,name,NULL,id,branch_id,' . session('branch_id'),
            'selectedUOM' => 'required|exists:unit_of_measurement,id',
        ]);

        CategoryModel::create([
            'name' => $validated['categoryName'],
            'uom' => $validated['selectedUOM'],
            'branch_id' => $this->branch_id
        ]);

        return redirect()->route('category-index')
            ->with('success', 'Category added successfully!');
    }

    public function edit($id)
    {
        $category = CategoryModel::findOrFail($id);
        $uoms = UomModel::all();

        return view('categories.edit', compact('category', 'uoms'));
    }

    public function update(Request $request)
    {
        $category = CategoryModel::findOrFail($request->category_id);

        $validated = $request->validate([
            'categoryName' => 'required|string|max:255|unique:categories,name,' . $request->category_id,
            'selectedUOM' => 'required|exists:unit_of_measurement,id',
        ]);

        $category->update([
            'name' => $validated['categoryName'],
            'uom' => $validated['selectedUOM']
        ]);

        return redirect()->route('category-index')
            ->with('success', 'Category updated successfully!');
    }

    public function delete($id)
    {
        $category = CategoryModel::findOrFail($id);

        $products = ProductModel::where('category_id', $category->id)->where('active_flag', 'A')->first();
        $productHistory = ProductHistoryModel::where('category_id', $category->id)->first();
        if (!empty($products) || !empty($productHistory)) {
            return redirect()->route('category-index')
                ->with('error', 'Category cannot be deleted because it has active products.');
        }

        $category->delete();

        return redirect()->route('category-index')
            ->with('success', 'Category deleted successfully!');
    }
}