<?php

namespace App\Http\Controllers;

use App\Models\ProductCategory;
use Illuminate\Http\Request;

class ProductCategoryController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');

        $this->middleware('permission:list_products_category')->only(['index']);
        $this->middleware('permission:list_products_category')->only(['show']);
        $this->middleware('permission:create_products_category')->only(['create', 'store']);
        $this->middleware('permission:update_products_category')->only(['edit', 'update']);
        $this->middleware('permission:delete_products_category')->only(['destroy']);
    }

    public function create()
    {
        $productCategories = ProductCategory::all();
        return view('category.product-category-create', compact('productCategories'));
    }

    public function store(Request $request)
    {
        $productCategory = new ProductCategory();

        $productCategory->name = $request->input('category_name');
        $productCategory->category_type = $request->input('category_type');

        $productCategory->save();

        return redirect()->back()->with('success', 'Product Category added successfully!');
    }

    public function edit(Request $request)
    {
        $id = $request->query('id');
        $productCategories = ProductCategory::all();

        $productCategory = ProductCategory::find($id);
        return view('category.product-category-edit', compact('productCategory', 'productCategories'));
    }

    // Update method to store the edited data
    public function update(Request $request, $id)
    {
        $productCategory = ProductCategory::find($id);
        $productCategory->name = $request->category_name;
        $productCategory->category_type = $request->category_type;
        $productCategory->save();

        return redirect()->back()->with('success', 'Product Category updated successfully!');
    }
}
