<?php

namespace App\Http\Controllers;

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

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

        $this->middleware('permission:list_products_unit')->only(['index']);
        $this->middleware('permission:list_products_unit')->only(['show']);
        $this->middleware('permission:create_products_unit')->only(['create', 'store']);
        $this->middleware('permission:update_products_unit')->only(['edit', 'update']);
        $this->middleware('permission:delete_products_unit')->only(['destroy']);
    }

    public function create()
    {
        $ProductUnits = ProductUnit::all();
        return view('unit.product-unit-create', compact('ProductUnits'));
    }

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

        $ProductUnit->name = $request->input('unit_name');
        $ProductUnit->unit_type = $request->input('unit_type');

        $ProductUnit->save();

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

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

        $productUnit = ProductUnit::find($id);
        return view('unit.product-unit-edit', compact('productUnit', 'ProductUnits'));
    }

    // Update method to store the edited data
    public function update(Request $request, $id)
    {
        $ProductUnit = ProductUnit::find($id);
        $ProductUnit->name = $request->unit_name;
        $ProductUnit->unit_type = $request->unit_type;
        $ProductUnit->save();

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