<?php

namespace App\Http\Controllers;

use App\Models\SchoolClass;
use App\Models\Subject;
use App\Models\User;
use App\Support\BranchContext;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\View\View;

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

    public function index(): View
    {
        $classes = SchoolClass::withCount(['sections', 'students', 'subjects'])->orderBy('level')->get();

        return view('academics.classes.index', compact('classes'));
    }

    public function create(): View
    {
        return view('academics.classes.create', ['class' => new SchoolClass()]);
    }

    public function store(Request $request, BranchContext $context): RedirectResponse
    {
        $data = $this->validateData($request);
        $data['branch_id'] = $context->currentId() ?? auth()->user()->branch_id ?? \App\Models\Branch::min('id');
        SchoolClass::create($data);

        return redirect()->route('classes.index')->with('success', 'Class created.');
    }

    public function show(SchoolClass $class): View
    {
        $class->load(['sections.classTeacher', 'subjects' => fn ($q) => $q->orderBy('name')]);

        return view('academics.classes.show', [
            'class' => $class,
            'teachers' => $this->teachers(),
            'allSubjects' => Subject::active()->orderBy('name')->get(),
        ]);
    }

    public function edit(SchoolClass $class): View
    {
        return view('academics.classes.edit', ['class' => $class]);
    }

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

        return redirect()->route('classes.index')->with('success', 'Class updated.');
    }

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

        return redirect()->route('classes.index')->with('success', 'Class deleted.');
    }

    /** Teachers within the current branch context, for class-teacher / subject allocation. */
    private function teachers()
    {
        return User::role('Teacher')->orderBy('name')->get();
    }

    private function validateData(Request $request): array
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:80'],
            'level' => ['nullable', 'integer', 'min:0'],
            'is_active' => ['nullable', 'boolean'],
        ]);
        $data['is_active'] = (bool) ($data['is_active'] ?? false);
        $data['level'] = (int) ($data['level'] ?? 0);

        return $data;
    }
}
