<?php

namespace App\Http\Controllers\Admin;

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

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

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

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

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

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

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

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

    public function destroy(ClassPack $classPack): RedirectResponse
    {
        $classPack->delete();

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

    /** @return array<string, mixed> */
    private function validated(Request $request): array
    {
        return $request->validate([
            'name' => 'required|string|max:255',
            'price_cents' => 'required|integer|min:0',
            'per_unit_label' => 'nullable|string|max:255',
            'sort_order' => 'required|integer|min:0',
            'is_active' => 'sometimes|boolean',
        ]) + ['is_active' => $request->boolean('is_active')];
    }
}
