<?php

namespace Database\Seeders;

use App\Models\AppNotification;
use App\Models\Branch;
use App\Models\Evaluation;
use App\Models\EvaluationResult;
use App\Models\SchoolClass;
use App\Models\Student;
use App\Models\Subject;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        // Super admin + a branch manager.
        $admin = User::updateOrCreate(
            ['email' => 'admin@school.test'],
            ['name' => 'Super Admin', 'password' => Hash::make('password'), 'role' => 'super-admin', 'is_active' => true],
        );
        $manager = User::updateOrCreate(
            ['email' => 'manager@school.test'],
            ['name' => 'Branch Manager', 'password' => Hash::make('password'), 'role' => 'manager', 'is_active' => true,
                'permissions' => ['students.view', 'students.create', 'students.edit', 'evaluation.view', 'evaluation.edit']],
        );

        // Branches (a multi-branch school).
        $branches = collect([
            ['name' => 'Main Campus', 'code' => 'MC'],
            ['name' => 'North Branch', 'code' => 'NB'],
            ['name' => 'South Branch', 'code' => 'SB'],
        ])->map(fn ($b) => Branch::updateOrCreate(['code' => $b['code']], $b + ['is_active' => true]));

        $admin->branches()->sync($branches->pluck('id'));
        $manager->branches()->sync([$branches[0]->id]);

        // Subjects (bilingual, matching education-erp style).
        $subjects = collect([
            ['name' => 'Mathematics', 'name_en' => 'Mathematics', 'name_fa' => 'ریاضی'],
            ['name' => 'Dari', 'name_en' => 'Dari', 'name_fa' => 'دری'],
            ['name' => 'Pashto', 'name_en' => 'Pashto', 'name_fa' => 'پشتو'],
            ['name' => 'English', 'name_en' => 'English', 'name_fa' => 'انگلیسی'],
            ['name' => 'Science', 'name_en' => 'Science', 'name_fa' => 'علوم'],
            ['name' => 'Islamic Studies', 'name_en' => 'Islamic Studies', 'name_fa' => 'تعلیمات اسلامی'],
        ])->values()->map(fn ($s, $i) => Subject::updateOrCreate(['name' => $s['name']], $s + ['max_marks' => 100, 'sort_order' => $i]));

        // Classes: grades 1–12, each with sections A, B and C (main branch), full data.
        $mainBranch = $branches[0];
        $ordinalFa = [
            1 => 'اول', 2 => 'دوم', 3 => 'سوم', 4 => 'چهارم', 5 => 'پنجم', 6 => 'ششم',
            7 => 'هفتم', 8 => 'هشتم', 9 => 'نهم', 10 => 'دهم', 11 => 'یازدهم', 12 => 'دوازدهم',
        ];
        $sectionShift = ['A' => 'morning', 'B' => 'afternoon', 'C' => 'evening'];

        $classes = collect();
        foreach (range(1, 12) as $grade) {
            foreach (['A', 'B', 'C'] as $section) {
                $classes->push(SchoolClass::updateOrCreate(
                    ['name' => "Grade {$grade} - {$section}", 'branch_id' => $mainBranch->id],
                    [
                        'name_en' => "Grade {$grade}",
                        'name_fa' => "صنف {$ordinalFa[$grade]}",
                        'level' => $grade,
                        'section' => $section,
                        'shift' => $sectionShift[$section],
                    ],
                ));
            }
        }

        // Students — a full-featured cohort in every class.
        $maleNames = ['Ahmad', 'Mohammad', 'Ali', 'Hassan', 'Yusuf', 'Omar', 'Bilal', 'Karim', 'Rahim', 'Naveed', 'Farhad', 'Wali'];
        $femaleNames = ['Fatima', 'Zahra', 'Maryam', 'Sara', 'Hadia', 'Nadia', 'Sana', 'Lina', 'Rabia', 'Freshta', 'Marwa', 'Diba'];
        $lastNames = ['Ahmadi', 'Karimi', 'Noori', 'Rahimi', 'Sadat', 'Hashimi', 'Yusufi', 'Amini', 'Sultani', 'Barakzai', 'Popal', 'Sherzai'];
        $provinces = ['Kabul', 'Herat', 'Balkh', 'Kandahar', 'Nangarhar', 'Bamyan'];
        $bloods = ['A+', 'A-', 'B+', 'B-', 'AB+', 'O+', 'O-'];
        $occupations = ['Engineer', 'Doctor', 'Teacher', 'Shopkeeper', 'Farmer', 'Government Employee', 'Businessman'];

        $n = 1;
        foreach ($classes as $class) {
            $count = rand(8, 16);
            for ($i = 0; $i < $count; $i++) {
                $gender = $i % 2 ? 'female' : 'male';
                $first = $gender === 'female' ? $femaleNames[array_rand($femaleNames)] : $maleNames[array_rand($maleNames)];
                $last = $lastNames[array_rand($lastNames)];
                $province = $provinces[array_rand($provinces)];
                Student::updateOrCreate(
                    ['admission_number' => 'ADM-'.str_pad((string) $n, 5, '0', STR_PAD_LEFT)],
                    [
                        'branch_id' => $mainBranch->id,
                        'class_id' => $class->id,
                        'first_name' => $first,
                        'last_name' => $last,
                        'gender' => $gender,
                        'date_of_birth' => sprintf('%04d-%02d-%02d', 2010 - $class->level, rand(1, 12), rand(1, 28)),
                        'place_of_birth' => $province,
                        'nationality' => 'Afghan',
                        'religion' => 'Islam',
                        'mother_tongue' => rand(0, 1) ? 'Dari' : 'Pashto',
                        'blood_group' => $bloods[array_rand($bloods)],
                        'national_id' => (string) rand(1000000000, 1499999999),
                        'roll_number' => (string) ($i + 1),
                        'student_code' => 'STU-'.str_pad((string) $n, 5, '0', STR_PAD_LEFT),
                        'admission_date' => '2024-03-'.str_pad((string) rand(1, 28), 2, '0', STR_PAD_LEFT),
                        'section' => $class->section,
                        'shift' => $class->shift,
                        'academic_year' => '1403',
                        'status' => 'active',
                        'email' => strtolower($first.'.'.$last.$n).'@student.shams.edu',
                        'phone' => '07'.rand(10000000, 99999999),
                        'address' => 'House #'.rand(1, 300).', District '.rand(1, 15),
                        'city' => $province,
                        'province' => $province,
                        'country' => 'Afghanistan',
                        'father_name' => $maleNames[array_rand($maleNames)].' '.$last,
                        'father_occupation' => $occupations[array_rand($occupations)],
                        'father_mobile' => '07'.rand(10000000, 99999999),
                        'mother_name' => $femaleNames[array_rand($femaleNames)].' '.$last,
                        'emergency_contact_name' => $maleNames[array_rand($maleNames)].' '.$last,
                        'emergency_contact_phone' => '07'.rand(10000000, 99999999),
                    ],
                );
                $n++;
            }
        }

        // Link students into shared-parent families of varying sizes (4, 3, 2, 1)
        // so the Parents page shows real households with different child counts.
        $pool = Student::where('status', 'active')->inRandomOrder()->get();
        $idx = 0;
        $sizeCycle = [4, 3, 2, 1, 3, 2, 4, 2, 1, 3]; // mixed distribution
        $ci = 0;
        while ($idx < $pool->count()) {
            $size = $sizeCycle[$ci % count($sizeCycle)];
            $ci++;
            $group = $pool->slice($idx, $size);
            if ($group->isEmpty()) {
                break;
            }
            $idx += $group->count();
            if ($group->count() < 2) {
                continue; // single-child family keeps its own generated parent
            }
            $last = $group->first()->last_name;
            $fatherName = $maleNames[array_rand($maleNames)].' '.$last;
            $motherName = $femaleNames[array_rand($femaleNames)].' '.$last;
            $mobile = '07'.rand(30000000, 79999999);
            foreach ($group as $g) {
                $g->update(['father_name' => $fatherName, 'father_mobile' => $mobile, 'mother_name' => $motherName]);
            }
        }

        // One evaluation with marks for Grade 7 - A.
        $grade7 = $classes->firstWhere('name', 'Grade 7 - A') ?? $classes->first();
        $eval = Evaluation::updateOrCreate(
            ['class_id' => $grade7->id, 'month_shamsi' => 7],
            [
                'branch_id' => $mainBranch->id,
                'month_name_fa' => 'میزان',
                'year_shamsi' => 1403,
                'evaluator_name' => 'Branch Manager',
                'title_en' => 'Month میزان Evaluation 1403',
                'title_fa' => 'ارزیابی ماه میزان ۱۴۰۳',
                'status' => 'in_progress',
            ],
        );
        foreach (Student::where('class_id', $grade7->id)->get() as $student) {
            foreach ($subjects as $subject) {
                EvaluationResult::updateOrCreate(
                    ['evaluation_id' => $eval->id, 'student_id' => $student->id, 'subject_id' => $subject->id],
                    ['marks' => rand(45, 99), 'max_marks' => 100],
                );
            }
        }

        // ── Staff: teachers + employees ─────────────────────────────────
        $designations = ['Mathematics Teacher', 'Science Teacher', 'Language Teacher', 'Islamic Studies Teacher', 'English Teacher'];
        $fields = ['Mathematics', 'Physics', 'Chemistry', 'Biology', 'Dari Literature', 'English Literature', 'Islamic Studies', 'Computer Science', 'Education'];
        $universities = ['Kabul University', 'Herat University', 'Balkh University', 'Kabul Education University', 'Kandahar University', 'Nangarhar University'];
        $degrees = ['bachelor', 'bachelor', 'master', 'master', 'phd'];
        $expertises = ['Curriculum design', 'Exam preparation', 'Classroom management', 'STEM education', 'Bilingual teaching', 'Special needs support'];
        // ~7 teachers per subject so the auto-generated timetable can actually
        // staff every class without double-booking a teacher.
        $subjectFieldMap = ['Mathematics' => 'Mathematics', 'Dari' => 'Dari Literature', 'Pashto' => 'Pashto Literature', 'English' => 'English Literature', 'Science' => 'Physics', 'Islamic Studies' => 'Islamic Studies'];
        $tchIndex = 0;
        foreach ($subjects as $subject) {
            foreach (range(1, 7) as $k) {
                $tchIndex++;
                $gender = $tchIndex % 3 === 0 ? 'female' : 'male';
                $nm = ($gender === 'female' ? $femaleNames[array_rand($femaleNames)] : $maleNames[array_rand($maleNames)]).' '.$lastNames[array_rand($lastNames)];
                $deg = $degrees[array_rand($degrees)];
                \App\Models\Staff::updateOrCreate(
                    ['emp_no' => 'TCH-'.str_pad((string) $tchIndex, 3, '0', STR_PAD_LEFT)],
                    [
                        'branch_id' => $mainBranch->id, 'type' => 'teacher', 'name' => $nm, 'gender' => $gender,
                        'father_name' => $maleNames[array_rand($maleNames)].' '.$lastNames[array_rand($lastNames)],
                        'designation' => $subject->name.' Teacher', 'department' => 'Academics',
                        'subjects' => $subject->name,
                        'qualification' => $deg === 'phd' ? 'Doctorate' : ($deg === 'master' ? 'Master of Science' : 'Bachelor of Education'),
                        'degree_level' => $deg, 'field_of_study' => $subjectFieldMap[$subject->name] ?? $subject->name,
                        'university' => $universities[array_rand($universities)], 'expertise' => $expertises[array_rand($expertises)],
                        'experience_years' => rand(1, 22), 'blood_group' => $bloods[array_rand($bloods)],
                        'marital_status' => rand(0, 1) ? 'married' : 'single',
                        'bio' => 'Dedicated '.$subject->name.' educator with a passion for student success.',
                        'join_date' => '202'.rand(0, 4).'-0'.rand(1, 9).'-1'.rand(0, 9),
                        'employment_type' => 'full_time', 'contract_start' => '2024-01-01', 'contract_end' => '2026-12-31',
                        'basic_salary' => rand(15, 40) * 1000, 'shift' => ['morning', 'afternoon', 'evening'][rand(0, 2)],
                        'national_id' => (string) rand(1200000000, 1499999999),
                        'phone' => '07'.rand(10000000, 99999999), 'status' => 'active',
                    ],
                );
            }
        }
        foreach ([['Accountant', 'Finance', 'Accounting'], ['Librarian', 'Library', 'Library Science'], ['Receptionist', 'Administration', 'Business Administration'], ['IT Officer', 'Administration', 'Computer Science'], ['Guard', 'Security', null], ['Cleaner', 'Facilities', null]] as $i => [$desig, $dept, $field]) {
            $deg = $field ? $degrees[array_rand($degrees)] : null;
            \App\Models\Staff::updateOrCreate(
                ['emp_no' => 'EMP-'.str_pad((string) ($i + 1), 3, '0', STR_PAD_LEFT)],
                [
                    'branch_id' => $mainBranch->id, 'type' => 'employee',
                    'name' => $maleNames[array_rand($maleNames)].' '.$lastNames[array_rand($lastNames)],
                    'father_name' => $maleNames[array_rand($maleNames)].' '.$lastNames[array_rand($lastNames)],
                    'designation' => $desig, 'department' => $dept, 'employment_type' => 'contract',
                    'degree_level' => $deg, 'field_of_study' => $field,
                    'university' => $field ? $universities[array_rand($universities)] : null,
                    'experience_years' => rand(1, 15),
                    'contract_start' => '2024-01-01', 'contract_end' => '2025-12-31',
                    'basic_salary' => rand(8, 25) * 1000, 'join_date' => '2024-0'.rand(1, 9).'-01',
                    'phone' => '07'.rand(10000000, 99999999), 'status' => 'active',
                ],
            );
        }

        // ── Attendance: today for grade 7 A/B/C + staff ─────────────────
        $today = now()->toDateString();
        $statuses = ['present', 'present', 'present', 'present', 'present', 'present', 'late', 'absent', 'excused'];
        foreach (SchoolClass::where('level', 7)->get() as $cls) {
            foreach (Student::where('class_id', $cls->id)->get() as $s) {
                \App\Models\Attendance::updateOrCreate(
                    ['date' => $today, 'person_type' => 'student', 'person_id' => $s->id],
                    ['class_id' => $cls->id, 'branch_id' => $mainBranch->id, 'status' => $statuses[array_rand($statuses)], 'marked_by' => 'Seeder'],
                );
            }
        }
        foreach (\App\Models\Staff::all() as $st) {
            \App\Models\Attendance::updateOrCreate(
                ['date' => $today, 'person_type' => 'staff', 'person_id' => $st->id],
                ['branch_id' => $mainBranch->id, 'status' => rand(0, 9) ? 'present' : 'absent', 'marked_by' => 'Seeder'],
            );
        }

        // ── Fees: heads, monthly tuition invoices, some payments ────────
        $tuition = \App\Models\FeeHead::updateOrCreate(['name' => 'Tuition Fee'], ['name_fa' => 'فیس تدریسی', 'frequency' => 'monthly', 'amount' => 1500]);
        \App\Models\FeeHead::updateOrCreate(['name' => 'Admission Fee'], ['name_fa' => 'فیس شمولیت', 'frequency' => 'one_time', 'amount' => 3000]);
        \App\Models\FeeHead::updateOrCreate(['name' => 'Transport Fee'], ['name_fa' => 'فیس ترانسپورت', 'frequency' => 'monthly', 'amount' => 800]);
        \App\Models\FeeHead::updateOrCreate(['name' => 'Exam Fee'], ['name_fa' => 'فیس امتحان', 'frequency' => 'quarterly', 'amount' => 500]);

        $period = '1403-07';
        foreach (Student::limit(150)->get() as $s) {
            $inv = \App\Models\StudentFee::updateOrCreate(
                ['student_id' => $s->id, 'fee_head_id' => $tuition->id, 'period' => $period],
                ['title' => 'Tuition Fee '.$period, 'amount' => 1500, 'due_date' => $today],
            );
            // ~60% pay in full, ~15% partial. Spread across the last ~5 months
            // so dashboard collection trends look realistic.
            $r = rand(1, 100);
            $payDate = now()->subDays(rand(0, 150))->toDateString();
            if ($r <= 60) {
                \App\Models\FeePayment::updateOrCreate(
                    ['student_fee_id' => $inv->id, 'student_id' => $s->id, 'amount' => 1500],
                    ['method' => ['cash', 'bank', 'wallet'][rand(0, 2)], 'receipt_no' => 'RCP-'.str_pad((string) $inv->id, 6, '0', STR_PAD_LEFT), 'date' => $payDate, 'received_by' => 'Seeder'],
                );
            } elseif ($r <= 75) {
                \App\Models\FeePayment::updateOrCreate(
                    ['student_fee_id' => $inv->id, 'student_id' => $s->id, 'amount' => 700],
                    ['method' => 'cash', 'receipt_no' => 'RCP-'.str_pad((string) $inv->id, 6, '0', STR_PAD_LEFT).'P', 'date' => $payDate, 'received_by' => 'Seeder'],
                );
            }
            $inv->refreshStatus();
        }

        // ── Exams: one monthly (with marks) + one midterm scheduled ─────
        $exam = \App\Models\Exam::updateOrCreate(
            ['name' => 'Monthly Test — Mizan', 'class_id' => $grade7->id],
            ['branch_id' => $mainBranch->id, 'type' => 'monthly', 'date' => $today, 'max_marks' => 100, 'pass_marks' => 40, 'status' => 'ongoing'],
        );
        foreach (Student::where('class_id', $grade7->id)->get() as $s) {
            foreach ($subjects as $subj) {
                \App\Models\ExamMark::updateOrCreate(
                    ['exam_id' => $exam->id, 'student_id' => $s->id, 'subject_id' => $subj->id],
                    ['marks' => rand(30, 100), 'max_marks' => 100],
                );
            }
        }
        \App\Models\Exam::updateOrCreate(
            ['name' => 'Mid-term (چهارنیم ماه)', 'class_id' => $classes->firstWhere('name', 'Grade 8 - A')->id],
            ['branch_id' => $mainBranch->id, 'type' => 'midterm', 'date' => now()->addDays(14)->toDateString(), 'status' => 'scheduled'],
        );

        // ── Timetable: 6 bell periods + a full week for Grade 7 - A ─────
        $periods = collect();
        foreach ([['Period 1', '08:00', '08:45'], ['Period 2', '08:50', '09:35'], ['Period 3', '09:40', '10:25'], ['Break', '10:25', '10:45'], ['Period 4', '10:45', '11:30'], ['Period 5', '11:35', '12:20']] as $i => [$nm, $st, $en]) {
            $periods->push(\App\Models\Period::updateOrCreate(['name' => $nm], ['start_time' => $st, 'end_time' => $en, 'sort_order' => $i]));
        }
        $teachers = \App\Models\Staff::where('type', 'teacher')->get();
        foreach (range(0, 5) as $day) { // Sat..Thu
            foreach ($periods->where('name', '!=', 'Break') as $p) {
                \App\Models\TimetableSlot::updateOrCreate(
                    ['class_id' => $grade7->id, 'day' => $day, 'period_id' => $p->id],
                    ['subject_id' => $subjects->random()->id, 'teacher_id' => $teachers->random()->id, 'room' => 'R-'.rand(1, 12)],
                );
            }
        }

        // ── Notices ─────────────────────────────────────────────────────
        \App\Models\Notice::updateOrCreate(['title' => 'Parents\' Day'], ['body' => 'Parents\' day will be held next Thursday. All parents are invited.', 'audience' => 'parents', 'priority' => 'high', 'publish_at' => $today, 'created_by' => 'Seeder']);
        \App\Models\Notice::updateOrCreate(['title' => 'Mid-term exams schedule'], ['body' => 'Mid-term examinations start in two weeks. Timetables are published on the portal.', 'audience' => 'students', 'priority' => 'normal', 'publish_at' => $today, 'created_by' => 'Seeder']);
        \App\Models\Notice::updateOrCreate(['title' => 'Staff meeting'], ['body' => 'Monthly staff meeting on Saturday 10:00 in the main hall.', 'audience' => 'staff', 'priority' => 'normal', 'publish_at' => $today, 'created_by' => 'Seeder']);

        // ── Accounting: opening expenses (fee income flows in on payment) ─
        foreach ([['Rent', 25000, 'bank'], ['Utilities', 4200, 'cash'], ['Supplies', 6800, 'cash'], ['Maintenance', 3100, 'cash']] as [$cat, $amt, $m]) {
            \App\Models\Transaction::updateOrCreate(
                ['type' => 'expense', 'category' => $cat, 'date' => $today],
                ['amount' => $amt, 'method' => $m, 'created_by' => 'Seeder', 'branch_id' => $mainBranch->id],
            );
        }
        // Mirror seeded fee payments into income so the ledger balances.
        $feeTotal = \App\Models\FeePayment::sum('amount');
        \App\Models\Transaction::updateOrCreate(
            ['type' => 'income', 'category' => 'Fees', 'date' => $today, 'reference' => 'SEED-FEES'],
            ['amount' => $feeTotal, 'method' => 'cash', 'note' => 'Seeded fee collections', 'created_by' => 'Seeder'],
        );

        // ── Library ─────────────────────────────────────────────────────
        $bookRows = [
            ['ریاضی صنف هفتم', 'وزارت معارف', 'Ministry of Education', 'Textbook', 12],
            ['English Grammar in Use', 'Raymond Murphy', 'Cambridge', 'Language', 6],
            ['تاریخ افغانستان', 'میر غلام محمد غبار', 'Nashr', 'History', 4],
            ['Physics for Class 10', 'MoE', 'Ministry of Education', 'Textbook', 10],
            ['گلستان سعدی', 'سعدی', 'Classic', 'Literature', 3],
            ['Oxford Dictionary', 'Oxford', 'OUP', 'Reference', 2],
        ];
        foreach ($bookRows as [$title, $author, $pub, $cat, $copies]) {
            \App\Models\Book::updateOrCreate(['title' => $title], ['author' => $author, 'publisher' => $pub, 'category' => $cat, 'copies' => $copies, 'available' => $copies, 'shelf' => 'S-'.rand(1, 9)]);
        }
        $b1 = \App\Models\Book::first();
        if ($b1 && ! \App\Models\BookIssue::where('book_id', $b1->id)->exists()) {
            \App\Models\BookIssue::create(['book_id' => $b1->id, 'person_name' => 'Ahmad Karimi', 'person_type' => 'student', 'issue_date' => now()->subDays(10)->toDateString(), 'due_date' => now()->subDays(3)->toDateString()]);
            $b1->decrement('available');
        }

        // ── Transport ───────────────────────────────────────────────────
        $v1 = \App\Models\Vehicle::updateOrCreate(['name' => 'Bus 1'], ['number_plate' => 'KBL-1234', 'capacity' => 30, 'driver_name' => 'Rahim Sherzai', 'driver_phone' => '0788112233']);
        $v2 = \App\Models\Vehicle::updateOrCreate(['name' => 'Van 2'], ['number_plate' => 'KBL-5678', 'capacity' => 14, 'driver_name' => 'Karim Popal', 'driver_phone' => '0788445566']);
        $r1 = \App\Models\TransportRoute::updateOrCreate(['name' => 'Route A — City Center'], ['vehicle_id' => $v1->id, 'fare' => 800, 'stops' => 'Chowk, Park Road, Main Gate']);
        \App\Models\TransportRoute::updateOrCreate(['name' => 'Route B — North'], ['vehicle_id' => $v2->id, 'fare' => 600, 'stops' => 'North Sq, Bridge, School']);
        foreach (Student::limit(5)->get() as $s) {
            \App\Models\TransportAssignment::updateOrCreate(['route_id' => $r1->id, 'student_name' => $s->full_name], ['stop' => 'Chowk', 'pickup_time' => '07:10']);
        }

        // ── Hostel ──────────────────────────────────────────────────────
        foreach (range(1, 4) as $i) {
            \App\Models\HostelRoom::updateOrCreate(['name' => "Room {$i}"], ['building' => 'Block A', 'capacity' => 4, 'warden' => 'Wali Ahmadi', 'fee' => 1200]);
        }
        $room1 = \App\Models\HostelRoom::first();
        foreach (Student::limit(3)->get() as $i => $s) {
            \App\Models\HostelAllocation::updateOrCreate(['room_id' => $room1->id, 'student_name' => $s->full_name], ['bed_no' => 'B'.($i + 1), 'check_in' => $today]);
        }
        $room1->update(['occupied' => \App\Models\HostelAllocation::where('room_id', $room1->id)->count()]);

        // ── Inventory ───────────────────────────────────────────────────
        foreach ([['Whiteboard Markers', 'Stationery', 'box', 24, 10, false], ['A4 Paper', 'Stationery', 'ream', 40, 15, false], ['Student Desks', 'Furniture', 'pcs', 120, 0, true], ['Projector', 'IT', 'pcs', 4, 1, true], ['Lab Beakers', 'Lab', 'pcs', 60, 20, false], ['Footballs', 'Sports', 'pcs', 8, 3, false]] as [$nm, $cat, $unit, $qty, $min, $asset]) {
            \App\Models\InventoryItem::updateOrCreate(['name' => $nm], ['category' => $cat, 'unit' => $unit, 'quantity' => $qty, 'min_stock' => $min, 'is_asset' => $asset, 'location' => 'Main Store']);
        }

        // ── Discipline (students AND staff) ─────────────────────────────
        \App\Models\Incident::updateOrCreate(['person_name' => 'Ahmad Hashimi', 'date' => $today], ['person_type' => 'student', 'category' => 'Lateness', 'severity' => 'minor', 'description' => 'Late to first period three times this week.', 'action_taken' => 'Warning', 'status' => 'resolved', 'reported_by' => 'Head Teacher']);
        \App\Models\Incident::updateOrCreate(['person_name' => 'Sara Amini', 'date' => $today], ['person_type' => 'staff', 'category' => 'Absenteeism', 'severity' => 'moderate', 'description' => 'Unreported absence on Monday.', 'action_taken' => 'Deduction', 'status' => 'open', 'reported_by' => 'Administrator']);

        // ── Health / clinic ─────────────────────────────────────────────
        \App\Models\HealthVisit::updateOrCreate(['student_name' => 'Zahra Rahimi', 'date' => $today], ['complaint' => 'Headache', 'treatment' => 'Rest + paracetamol', 'given_by' => 'School Nurse']);

        // ── Visitors ────────────────────────────────────────────────────
        \App\Models\Visitor::updateOrCreate(['name' => 'Gul Ahmad', 'check_in' => $today.' 09:30'], ['phone' => '0788990011', 'purpose' => 'Meet principal', 'to_meet' => 'Principal', 'pass_no' => 'V-00001']);

        // ── Events ──────────────────────────────────────────────────────
        \App\Models\Event::updateOrCreate(['title' => 'Parents\' Day'], ['type' => 'event', 'date_from' => now()->addDays(7)->toDateString(), 'audience' => 'parents']);
        \App\Models\Event::updateOrCreate(['title' => 'Mid-term Examinations'], ['type' => 'exam', 'date_from' => now()->addDays(14)->toDateString(), 'date_to' => now()->addDays(21)->toDateString(), 'audience' => 'students']);
        \App\Models\Event::updateOrCreate(['title' => 'Eid Holidays'], ['type' => 'holiday', 'date_from' => now()->addDays(30)->toDateString(), 'date_to' => now()->addDays(33)->toDateString(), 'audience' => 'all']);

        // A couple of notifications.
        AppNotification::updateOrCreate(['title' => 'Welcome to SMS'], ['body' => 'Your School Management System is ready.', 'icon' => 'celebration', 'priority' => 'medium']);
        AppNotification::updateOrCreate(['title' => 'Backup completed'], ['body' => 'Nightly backup finished successfully.', 'icon' => 'cloud_done', 'priority' => 'low', 'read_at' => now()]);

        // A month of attendance for every student, so meters have live data.
        $this->call(AttendanceHistorySeeder::class);

        // WhatsApp CRM defaults (templates, automation rules, gateway settings).
        $this->call(CrmSeeder::class);

        // Rich evaluation history (months, toppers, critical, new students).
        $this->call(EvaluationSeeder::class);

        // Class subject + teacher assignments (drives timetable & subject dashboard).
        $this->call(ClassSubjectSeeder::class);

        // Promote father-grouping into real Guardian accounts + link students.
        $this->call(GuardianSeeder::class);

        // Roles + permission presets.
        $this->call(RoleSeeder::class);

        // Subject question bank (drives performance-based practice suggestions).
        $this->call(QuestionSeeder::class);

        // Monthly Student Evaluation module — templates, criteria, graded
        // months, integrity flags & confidence (see docs/EVALUATION_MODULE.md).
        $this->call(EvaluationModuleSeeder::class);

        // Fill otherwise-empty modules (visitors, clinic, incidents,
        // invitations, payroll, campaigns, stock, daily plans) with demo data.
        $this->call(EmptyModulesSeeder::class);

        // Book profiles + curriculum question bank (year → month → chapter).
        $this->call(BookQuestionsSeeder::class);
    }
}
