<?php

namespace App\Http\Controllers;

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

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

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $categories = MainCategory::latest()->get();

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name_ar' => 'required|string|max:255',
            'name_en' => 'required|string|max:255',
        ]);

        MainCategory::create($request->only('name_ar', 'name_en'));

        return redirect()->route('products.main_categories.index')
            ->with('success', __('products.main_categories.messages.added'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, MainCategory $mainCategory)
    {
        $request->validate([
            'name_ar' => 'required|string|max:255',
            'name_en' => 'required|string|max:255',
        ]);

        $mainCategory->update($request->only('name_ar', 'name_en'));

        return redirect()->route('products.main_categories.index')
            ->with('success', __('products.main_categories.messages.updated'));
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(MainCategory $mainCategory)
    {
        $mainCategory->delete();

        return redirect()->route('products.main_categories.index')
            ->with('success', __('products.main_categories.messages.deleted'));
    }
}
