<?php

namespace App\Database\Seeds;

use App\Models\SubjectCurriculumModel;
use CodeIgniter\Database\Seeder;

class SubjectCurriculumSeeder extends Seeder
{
    public function run()
    {
        $model = new SubjectCurriculumModel();
        $db = \Config\Database::connect();
        $classMap = $this->buildClassMap($db);
        if (empty($classMap)) {
            log_message('warning', 'SubjectCurriculumSeeder could not map any classes. Skipping import.');
            return;
        }

        $db->table($model->table)->truncate();

        $now = date('Y-m-d H:i:s');
        $this->importIslamic($model, $classMap, $now);
        $this->importQuran($model, $classMap, $now);
    }

    private function buildClassMap($db): array
    {
        $rows = $db->table('classes')
            ->select('id, class_name')
            ->get()
            ->getResultArray();

        $map = [];
        foreach ($rows as $row) {
            $key = $this->normalizeGradeKey($row['class_name'] ?? '');
            if ($key === '') {
                continue;
            }
            $map[$key] = (int) $row['id'];
        }

        return $map;
    }

    private function importIslamic(SubjectCurriculumModel $model, array $classMap, string $now): void
    {
        $entries = $this->readCsv(ROOTPATH . 'levels_1_to_9_table.csv');
        if (empty($entries)) {
            log_message('warning', 'SubjectCurriculumSeeder could not read levels_1_to_9_table.csv.');
            return;
        }

        $batch = [];
        foreach ($entries as $row) {
            $grade = $this->normalizeGradeKey($row['Grade'] ?? '');
            $classId = $classMap[$grade] ?? null;
            if (! $classId) {
                continue;
            }

            $unitNumber = is_numeric($row['Unit'] ?? null) ? (int) $row['Unit'] : null;
            $unitTitle = trim($row['Unit Title'] ?? '');
            $chapterName = trim($row['chapter'] ?? '');
            if ($chapterName === '') {
                continue;
            }

            $batch[] = [
                'class_id' => $classId,
                'subject' => 'islamic',
                'unit_number' => $unitNumber,
                'unit_title' => $unitTitle ?: null,
                'chapter_name' => $chapterName,
                'created_at' => $now,
                'updated_at' => $now,
            ];
        }

        if (! empty($batch)) {
            $model->insertBatch($batch);
        }
    }

    private function importQuran(SubjectCurriculumModel $model, array $classMap, string $now): void
    {
        $entries = $this->readCsv(ROOTPATH . 'quran_surahs_by_grade.csv');
        if (empty($entries)) {
            log_message('warning', 'SubjectCurriculumSeeder could not read quran_surahs_by_grade.csv.');
            return;
        }

        $batch = [];
        foreach ($entries as $row) {
            $grade = $this->normalizeGradeKey($row['Grade'] ?? '');
            $classId = $classMap[$grade] ?? null;
            if (! $classId) {
                continue;
            }

            $surah = trim($row['Surah'] ?? '');
            if ($surah === '') {
                continue;
            }

            $batch[] = [
                'class_id' => $classId,
                'subject' => 'quran',
                'unit_number' => null,
                'unit_title' => null,
                'chapter_name' => $surah,
                'created_at' => $now,
                'updated_at' => $now,
            ];
        }

        if (! empty($batch)) {
            $model->insertBatch($batch);
        }
    }

    private function readCsv(string $path): array
    {
        if (! is_file($path)) {
            return [];
        }

        $handle = fopen($path, 'r');
        if (! $handle) {
            return [];
        }

        $rows = [];
        $headers = fgetcsv($handle);
        if (! $headers) {
            fclose($handle);
            return [];
        }

        $headers = array_map('trim', $headers);
        while (($data = fgetcsv($handle)) !== false) {
            $row = [];
            foreach ($headers as $index => $header) {
                $row[$header] = $data[$index] ?? '';
            }
            $rows[] = $row;
        }

        fclose($handle);
        return $rows;
    }

    private function normalizeGradeKey(string $value): string
    {
        $value = strtolower(trim($value));
        $value = preg_replace('/^grade\s*/i', '', $value);
        return trim($value, " \t\n\r\0\x0B");
    }
}
