<?php

namespace App\Http\Controllers;

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

class ClassSubjectController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [new Middleware('can:academics.update')];
    }

    /** Attach a subject to the class (optionally with a teacher). */
    public function store(Request $request, SchoolClass $class): RedirectResponse
    {
        $data = $request->validate([
            'subject_id' => ['required', 'exists:subjects,id'],
            'teacher_id' => ['nullable', 'exists:users,id'],
        ]);

        $class->subjects()->syncWithoutDetaching([
            $data['subject_id'] => ['teacher_id' => $data['teacher_id'] ?? null, 'branch_id' => $class->branch_id],
        ]);

        return back()->with('success', 'Subject allocated to class.');
    }

    /** Update the teacher for an allocated subject. */
    public function update(Request $request, SchoolClass $class): RedirectResponse
    {
        $data = $request->validate([
            'subject_id' => ['required', 'exists:subjects,id'],
            'teacher_id' => ['nullable', 'exists:users,id'],
        ]);

        $class->subjects()->updateExistingPivot($data['subject_id'], ['teacher_id' => $data['teacher_id'] ?? null]);

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

    public function destroy(SchoolClass $class, int $subject): RedirectResponse
    {
        $class->subjects()->detach($subject);

        return back()->with('success', 'Subject removed from class.');
    }
}
