<?php

namespace Database\Seeders;

use App\Models\Exam;
use App\Models\Grade;
use App\Models\Lesson;
use App\Models\Student;
use App\Models\Classroom;
use App\Models\ExamSession;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;

class ChartDataSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // 1. Ensure we have at least 1 classroom
        $classroom = Classroom::firstOrCreate(
            ['title' => 'Kelas XII IPA 1']
        );

        // 2. Ensure we have at least 1 lesson
        $lesson = Lesson::firstOrCreate(
            ['title' => 'Matematika Terapan']
        );

        // 3. Generate 50 students if there are less than 50
        $existingStudentsCount = Student::count();
        if ($existingStudentsCount < 50) {
            $studentsToCreate = 50 - $existingStudentsCount;
            $studentsData = [];
            for ($i = 0; $i < $studentsToCreate; $i++) {
                $studentsData[] = [
                    'classroom_id' => $classroom->id,
                    'nisn' => 100000 + $i,
                    'name' => 'Siswa Simulasi ' . ($i + 1),
                    'password' => 100000 + $i,
                    'gender' => $i % 2 == 0 ? 'L' : 'P',
                    'created_at' => now(),
                    'updated_at' => now(),
                ];
            }
            Student::insert($studentsData);
        }

        // 4. Generate 12 varied exams (for the top 10 charts)
        $examsCount = Exam::count();
        if ($examsCount < 12) {
            $examsToCreate = 12 - $examsCount;
            $examsData = [];
            $examTitles = [
                'Ujian Tengah Semester - Biologi',
                'Ulangan Harian Fisika',
                'Tryout UN Matematika',
                'Ujian Akhir Kimia',
                'Pre-test Bahasa Indonesia',
                'Post-test Bahasa Inggris',
                'Ujian Praktik Kejuruan',
                'Simulasi UTBK Sejarah',
                'Ulangan Blok Geografi',
                'Kuis Sosiologi',
                'Ujian Kompetensi Dasar',
                'Ulangan Harian Olahraga'
            ];

            for ($i = 0; $i < $examsToCreate; $i++) {
                $examsData[] = [
                    'title' => $examTitles[$i] ?? "Ujian Simulasi " . ($i + 1),
                    'lesson_id' => $lesson->id,
                    'classroom_id' => $classroom->id,
                    'duration' => 90,
                    'description' => 'Ini adalah ujian simulasi untuk chart',
                    'random_question' => 'Y',
                    'random_answer' => 'Y',
                    'show_answer' => 'N',
                    'created_at' => now(),
                    'updated_at' => now(),
                ];
            }
            Exam::insert($examsData);
        }

        // 5. Ensure at least 1 session
        $exams = Exam::all();
        $examSession = ExamSession::firstOrCreate(
            ['title' => 'Sesi Pagi'],
            [
                'exam_id' => $exams->first()->id,
                'start_time' => now()->startOfDay()->addHours(7),
                'end_time' => now()->startOfDay()->addHours(12),
            ]
        );

        // 6. Generate Grades for charts
        $students = Student::all();

        $gradesData = [];

        // Add grades for each exam, varying the participant count to make chart interesting
        foreach ($exams as $exam) {
            // vary the participation from 10 to exactly the full class
            $participantCount = rand(15, $students->count());

            // shuffle and take the random participants
            $participants = $students->shuffle()->take($participantCount);

            foreach ($participants as $student) {
                // Determine a random score with a slight bias towards median to make doughnut chart look realistic
                $rand = rand(1, 100);
                if ($rand < 10) {
                    $score = rand(0, 40);      // 10% get 0-40
                } elseif ($rand < 30) {
                    $score = rand(41, 60);     // 20% get 41-60
                } elseif ($rand < 80) {
                    $score = rand(61, 80);     // 50% get 61-80
                } else {
                    $score = rand(81, 100);    // 20% get 81-100
                }

                $gradesData[] = [
                    'exam_id' => $exam->id,
                    'exam_session_id' => $examSession->id,
                    'student_id' => $student->id,
                    'duration' => 3600,
                    'start_time' => now()->subDays(rand(1, 10)),
                    'end_time' => now()->subDays(rand(1, 10))->addHour(),
                    'total_correct' => round($score / 10),
                    'grade' => $score,
                    'created_at' => now(),
                    'updated_at' => now(),
                ];
            }
        }

        // Clear existing grades to prevent compounding data on multiple seed runs
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        Grade::truncate();
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');

        // Chunk insertions to avoid driver limitations
        foreach (array_chunk($gradesData, 100) as $chunk) {
            Grade::insert($chunk);
        }

        $this->command->info('✅ Simulation data for charts (Students, Exams, Grades) seeded successfully.');
    }
}
