<?php

namespace App\Http\Controllers;

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

class ProductMeasurementController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:products.details.measurements.view')->only(['index']);
        $this->middleware('permission:products.details.measurements.create')->only(['store']);
        $this->middleware('permission:products.details.measurements.update')->only(['update']);
        $this->middleware('permission:products.details.measurements.delete')->only(['destroy']);
    }

    public function index()
    {
        $items = ProductMeasurement::latest()->get();

        return view('products.product_details.measurements.index', compact('items'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
        ]);

        ProductMeasurement::create($request->only('name'));

        return redirect()->route('products.product_details.measurements.index')
            ->with('success', __('common.added_successfully'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
        ]);

        $item = ProductMeasurement::findOrFail($id);
        $item->update($request->only('name'));

        return redirect()->route('products.product_details.measurements.index')
            ->with('success', __('common.updated_successfully'));
    }

    public function destroy($id)
    {
        $item = ProductMeasurement::findOrFail($id);
        $item->delete();

        return redirect()->route('products.product_details.measurements.index')
            ->with('success', __('common.deleted_successfully'));
    }
}
