<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ClassType;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ClassTypeController extends Controller
{
    public function index(): View
    {
        return view('admin.class-types.index', [
            'items' => ClassType::query()->orderBy('sort_order')->get(),
        ]);
    }

    public function create(): View
    {
        return view('admin.class-types.form', ['item' => new ClassType]);
    }

    public function store(Request $request): RedirectResponse
    {
        ClassType::query()->create($this->validated($request));

        return redirect()->route('admin.class-types.index')->with('success', 'Class type created.');
    }

    public function edit(ClassType $classType): View
    {
        return view('admin.class-types.form', ['item' => $classType]);
    }

    public function update(Request $request, ClassType $classType): RedirectResponse
    {
        $classType->update($this->validated($request));

        return redirect()->route('admin.class-types.index')->with('success', 'Class type updated.');
    }

    public function destroy(ClassType $classType): RedirectResponse
    {
        $classType->delete();

        return redirect()->route('admin.class-types.index')->with('success', 'Class type deleted.');
    }

    /** @return array<string, mixed> */
    private function validated(Request $request): array
    {
        return $request->validate([
            'slug' => 'required|string|max:50',
            'number' => 'required|string|max:2',
            'name' => 'required|string|max:100',
            'description' => 'required|string',
            'duration_minutes' => 'required|integer|min:1',
            'level_label' => 'required|string|max:100',
            'intensity' => 'required|integer|min:1|max:5',
            'sort_order' => 'required|integer|min:0',
            'is_active' => 'sometimes|boolean',
        ]) + ['is_active' => $request->boolean('is_active')];
    }
}
