<?php

namespace Database\Seeders;

use App\Models\AcademicSession;
use App\Models\Branch;
use App\Models\SchoolClass;
use App\Models\Section;
use App\Models\Subject;
use Illuminate\Database\Seeder;

class AcademicSeeder extends Seeder
{
    public function run(): void
    {
        // Academic sessions (shared across branches).
        AcademicSession::firstOrCreate(['name' => '2024-2025'], [
            'start_date' => '2024-04-01', 'end_date' => '2025-03-31', 'is_current' => false,
        ]);
        AcademicSession::firstOrCreate(['name' => '2025-2026'], [
            'start_date' => '2025-04-01', 'end_date' => '2026-03-31', 'is_current' => true,
        ]);

        $classNames = ['Grade 1', 'Grade 2', 'Grade 3', 'Grade 4', 'Grade 5', 'Grade 6', 'Grade 7', 'Grade 8'];
        $subjectNames = ['English', 'Urdu', 'Mathematics', 'Science', 'Islamiat', 'Social Studies', 'Computer'];

        foreach (Branch::all() as $branch) {
            // Subjects (per branch)
            $subjects = collect($subjectNames)->map(fn ($name, $i) => Subject::firstOrCreate(
                ['branch_id' => $branch->id, 'name' => $name],
                ['code' => strtoupper(substr($name, 0, 3)), 'is_active' => true]
            ));

            foreach ($classNames as $level => $name) {
                $class = SchoolClass::firstOrCreate(
                    ['branch_id' => $branch->id, 'name' => $name],
                    ['level' => $level + 1, 'is_active' => true]
                );

                foreach (['A', 'B'] as $sectionName) {
                    Section::firstOrCreate(
                        ['class_id' => $class->id, 'name' => $sectionName],
                        ['branch_id' => $branch->id, 'capacity' => 35, 'is_active' => true]
                    );
                }

                // Allocate every subject to the class (pivot, no teacher yet).
                $syncData = $subjects->mapWithKeys(fn ($s) => [$s->id => ['branch_id' => $branch->id]])->all();
                $class->subjects()->syncWithoutDetaching($syncData);
            }
        }
    }
}
