<?php

namespace App\Http\Controllers;

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

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

    public function index()
    {
        $categories = StageAcademyCourseCategory::query()
            ->orderByDesc('id')
            ->get();

        return view('stage_academy.courses.categories', compact('categories'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name_ar' => ['required', 'string', 'max:255'],
            'name_en' => ['required', 'string', 'max:255'],
            'description_ar' => ['nullable', 'string'],
            'description_en' => ['nullable', 'string'],
        ]);

        StageAcademyCourseCategory::create($validated);

        return redirect()->route('stage-academy.courses.categories');
    }

    public function update(Request $request, int $id)
    {
        $category = StageAcademyCourseCategory::query()->findOrFail($id);

        $validated = $request->validate([
            'name_ar' => ['required', 'string', 'max:255'],
            'name_en' => ['required', 'string', 'max:255'],
            'description_ar' => ['nullable', 'string'],
            'description_en' => ['nullable', 'string'],
        ]);

        $category->update($validated);

        return redirect()->route('stage-academy.courses.categories');
    }

    public function destroy(int $id)
    {
        $category = StageAcademyCourseCategory::query()->findOrFail($id);
        $category->delete();

        return redirect()->route('stage-academy.courses.categories');
    }
}
