<?php

namespace App\Http\Controllers;

use App\Models\SchoolClass;
use App\Models\Subject;
use App\Models\User;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\View\View;

/**
 * Timetable / Teacher Allocation — a system-wide view of which teacher teaches
 * which subject in which class. Reads the class_subject pivot (teacher_id).
 */
class TimetableController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [new Middleware('permission:academics.view')];
    }

    public function index(): View
    {
        $classes = SchoolClass::active()
            ->with(['subjects' => fn ($q) => $q->orderBy('name')])
            ->orderBy('level')->get();

        // Map user id => name for resolving teacher names on the pivot.
        $userMap = User::pluck('name', 'id');

        // Teacher-wise allocations: teacher => [ ['class','subject'], ... ]
        $teacherView = [];
        foreach ($classes as $class) {
            foreach ($class->subjects as $subject) {
                $tid = $subject->pivot->teacher_id;
                $name = $tid ? ($userMap[$tid] ?? 'Unknown') : '— Unassigned —';
                $teacherView[$name][] = ['class' => $class->name, 'subject' => $subject->name];
            }
        }
        ksort($teacherView);
        // Put "Unassigned" last.
        if (isset($teacherView['— Unassigned —'])) {
            $un = $teacherView['— Unassigned —'];
            unset($teacherView['— Unassigned —']);
            $teacherView['— Unassigned —'] = $un;
        }

        // Subject-wise allocations: subject => [ ['class','teacher'], ... ]
        $subjectView = [];
        foreach ($classes as $class) {
            foreach ($class->subjects as $subject) {
                $tid = $subject->pivot->teacher_id;
                $subjectView[$subject->name][] = [
                    'class' => $class->name,
                    'teacher' => $tid ? ($userMap[$tid] ?? 'Unknown') : null,
                ];
            }
        }
        ksort($subjectView);

        $totalAllocations = $classes->sum(fn ($c) => $c->subjects->count());
        $assigned = $classes->sum(fn ($c) => $c->subjects->filter(fn ($s) => $s->pivot->teacher_id)->count());

        return view('academics.timetable.index', [
            'classes' => $classes,
            'userMap' => $userMap,
            'teacherView' => $teacherView,
            'subjectView' => $subjectView,
            'totalAllocations' => $totalAllocations,
            'assigned' => $assigned,
            'unassigned' => $totalAllocations - $assigned,
        ]);
    }
}
