<?php

namespace App\Http\Controllers;

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

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

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

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

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

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

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

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

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

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

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

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