<?php

namespace App\Http\Controllers;

use App\Models\SchoolClass;
use App\Models\Section;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

class SectionController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:academics.create', only: ['store']),
            new Middleware('can:academics.update', only: ['update']),
            new Middleware('can:academics.delete', only: ['destroy']),
        ];
    }

    public function store(Request $request, SchoolClass $class): RedirectResponse
    {
        $data = $this->validateData($request);
        $class->sections()->create($data + ['branch_id' => $class->branch_id]);

        return back()->with('success', 'Section added.');
    }

    public function update(Request $request, Section $section): RedirectResponse
    {
        $section->update($this->validateData($request));

        return back()->with('success', 'Section updated.');
    }

    public function destroy(Section $section): RedirectResponse
    {
        if ($section->students()->exists()) {
            return back()->with('error', 'Cannot delete a section that has students.');
        }
        $section->delete();

        return back()->with('success', 'Section deleted.');
    }

    private function validateData(Request $request): array
    {
        return $request->validate([
            'name' => ['required', 'string', 'max:50'],
            'capacity' => ['nullable', 'integer', 'min:1'],
            'class_teacher_id' => ['nullable', 'exists:users,id'],
        ]);
    }
}
