<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\CalendarCategoryModel;
use App\Models\CalendarEventModel;
use App\Models\AcademicYearModel;
use App\Models\AcademicPeriodModel;

class AcademicCalendar extends BaseController
{
    protected CalendarCategoryModel $categoryModel;
    protected CalendarEventModel $eventModel;
    protected AcademicYearModel $yearModel;
    protected AcademicPeriodModel $periodModel;

    public function __construct()
    {
        $this->categoryModel = new CalendarCategoryModel();
        $this->eventModel    = new CalendarEventModel();
        $this->yearModel     = new AcademicYearModel();
        $this->periodModel   = new AcademicPeriodModel();

        helper(['calendar', 'logo', 'letter']);
    }

    // =========================================================
    // HELPER: Ambil pengaturan kalender dari DB
    // =========================================================
    private function getCalendarSettings(): array
    {
        $db   = \Config\Database::connect();
        $rows = $db->table('calendar_settings')->get()->getResultArray();
        $out  = [];
        foreach ($rows as $r) {
            $out[$r['key']] = $r['value'];
        }
        return $out;
    }

    // =========================================================
    // HALAMAN UTAMA
    // =========================================================
    public function index()
    {
        $years = $this->yearModel->where('deleted_at', null)
                    ->orderBy('name', 'DESC')
                    ->findAll();

        $activeYear = $this->yearModel->getActive();

        $yearId = $this->request->getGet('academic_year_id')
            ?: ($activeYear['id'] ?? ($years[0]['id'] ?? null));

        $selectedYear = null;
        foreach ($years as $y) {
            if ((int) $y['id'] === (int) $yearId) {
                $selectedYear = $y;
                break;
            }
        }

        $periods = $yearId ? $this->periodModel->getByYear($yearId) : [];

        $data = [
            'title'            => 'Kalender Pendidikan',
            'years'            => $years,
            'periods'          => $periods,
            'categories'       => $this->categoryModel->getActive(),
            'events'           => $yearId ? $this->eventModel->getByYear($yearId) : [],
            'selectedYearId'   => $yearId,
            'selectedYear'     => $selectedYear,
            'calendarSettings' => $this->getCalendarSettings(),
        ];

        return view('academic_calendar/index', $data);
    }

    // =========================================================
    // AJAX: Ambil data event untuk FullCalendar
    // =========================================================
    public function getEvents()
    {
        $yearId = $this->request->getGet('academic_year_id');
        $events = $this->eventModel->getByYear($yearId);

        $result = [];
        foreach ($events as $e) {
            $result[] = [
                'id'    => $e['id'],
                'title' => $e['title'],
                'start' => $e['start_date'],
                // FullCalendar: tanggal akhir bersifat exclusive -> tambah 1 hari
                'end'   => date('Y-m-d', strtotime($e['end_date'] . ' +1 day')),
                'color' => $e['color'],
                'extendedProps' => [
                    'category_id'      => $e['category_id'],
                    'category_name'    => $e['category_name'],
                    'category_code'    => $e['category_code'],
                    'description'      => $e['description'],
                    'start_date'       => $e['start_date'],
                    'end_date'         => $e['end_date'],
                    'academic_period_id' => $e['academic_period_id'],
                ],
            ];
        }

        return $this->response->setJSON($result);
    }

    // =========================================================
    // CRUD KEGIATAN
    // =========================================================
    public function store()
    {
        if (! $this->validate($this->eventModel->validationRules)) {
            return redirect()->back()->withInput()
                ->with('error', implode(', ', $this->validator->getErrors()));
        }

        $start = $this->request->getPost('start_date');
        $end   = $this->request->getPost('end_date');

        if (strtotime($end) < strtotime($start)) {
            return redirect()->back()->withInput()
                ->with('error', 'Tanggal selesai tidak boleh sebelum tanggal mulai.');
        }

        $this->eventModel->insert([
            'academic_year_id'   => $this->request->getPost('academic_year_id'),
            'academic_period_id' => $this->request->getPost('academic_period_id') ?: null,
            'category_id'        => $this->request->getPost('category_id'),
            'title'              => $this->request->getPost('title'),
            'start_date'         => $start,
            'end_date'           => $end,
            'description'        => $this->request->getPost('description'),
            'created_by'         => session('user_id'),
        ]);

        $yearId = $this->request->getPost('academic_year_id');
        return redirect()->to('/academic-calendar?academic_year_id=' . $yearId)->with('success', 'Kegiatan kalender pendidikan berhasil ditambahkan.');
    }

    public function update($id)
    {
        $event = $this->eventModel->find($id);
        if (! $event) {
            return redirect()->back()->with('error', 'Kegiatan tidak ditemukan.');
        }

        if (! $this->validate($this->eventModel->validationRules)) {
            return redirect()->back()->withInput()
                ->with('error', implode(', ', $this->validator->getErrors()));
        }

        $start = $this->request->getPost('start_date');
        $end   = $this->request->getPost('end_date');

        if (strtotime($end) < strtotime($start)) {
            return redirect()->back()->withInput()
                ->with('error', 'Tanggal selesai tidak boleh sebelum tanggal mulai.');
        }

        $this->eventModel->update($id, [
            'academic_year_id'   => $this->request->getPost('academic_year_id'),
            'academic_period_id' => $this->request->getPost('academic_period_id') ?: null,
            'category_id'        => $this->request->getPost('category_id'),
            'title'              => $this->request->getPost('title'),
            'start_date'         => $start,
            'end_date'           => $end,
            'description'        => $this->request->getPost('description'),
        ]);

        $yearId = $this->request->getPost('academic_year_id');
        return redirect()->to('/academic-calendar?academic_year_id=' . $yearId)->with('success', 'Kegiatan kalender pendidikan berhasil diperbarui.');
    }

    public function delete($id)
    {
        $event = $this->eventModel->find($id);
        if (! $event) {
            return redirect()->back()->with('error', 'Kegiatan tidak ditemukan.');
        }

        $this->eventModel->delete($id);

        $yearId = $event['academic_year_id'] ?? '';
        return redirect()->to('/academic-calendar?academic_year_id=' . $yearId)->with('success', 'Kegiatan kalender pendidikan berhasil dihapus.');
    }

    // =========================================================
    // CRUD KATEGORI
    // =========================================================
    public function storeCategory()
    {
        $rules = [
            'name'  => 'required|min_length[3]|max_length[100]',
            'code'  => 'required|max_length[10]',
            'color' => 'required|max_length[10]',
        ];

        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()
                ->with('error', implode(', ', $this->validator->getErrors()));
        }

        $this->categoryModel->insert([
            'name'       => $this->request->getPost('name'),
            'code'       => strtoupper($this->request->getPost('code')),
            'color'      => $this->request->getPost('color'),
            'is_libur'   => $this->request->getPost('is_libur') ? 1 : 0,
            'sort_order' => (int) $this->request->getPost('sort_order'),
        ]);

        return redirect()->back()->with('success', 'Kategori kegiatan berhasil ditambahkan.');
    }

    public function updateCategory($id)
    {
        $category = $this->categoryModel->find($id);
        if (! $category) {
            return redirect()->back()->with('error', 'Kategori tidak ditemukan.');
        }

        $rules = [
            'name'  => 'required|min_length[3]|max_length[100]',
            'code'  => 'required|max_length[10]',
            'color' => 'required|max_length[10]',
        ];

        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()
                ->with('error', implode(', ', $this->validator->getErrors()));
        }

        $this->categoryModel->update($id, [
            'name'       => $this->request->getPost('name'),
            'code'       => strtoupper($this->request->getPost('code')),
            'color'      => $this->request->getPost('color'),
            'is_libur'   => $this->request->getPost('is_libur') ? 1 : 0,
            'sort_order' => (int) $this->request->getPost('sort_order'),
        ]);

        return redirect()->back()->with('success', 'Kategori kegiatan berhasil diperbarui.');
    }

    public function deleteCategory($id)
    {
        $category = $this->categoryModel->find($id);
        if (! $category) {
            return redirect()->back()->with('error', 'Kategori tidak ditemukan.');
        }

        if ($this->categoryModel->isUsed($id)) {
            return redirect()->back()
                ->with('error', 'Kategori tidak bisa dihapus karena masih dipakai oleh kegiatan.');
        }

        $this->categoryModel->delete($id);

        return redirect()->back()->with('success', 'Kategori kegiatan berhasil dihapus.');
    }

    // =========================================================
    // PREVIEW: Tampilkan HTML preview di browser (tanpa mPDF)
    // =========================================================
    public function previewReport($yearId)
    {
        $year = $this->yearModel->find($yearId);
        if (! $year) {
            return redirect()->back()->with('error', 'Tahun ajaran tidak ditemukan.');
        }

        $events     = $this->eventModel->getByYear($yearId);
        $categories = $this->categoryModel->getActive();
        $school     = \Config\Database::connect()->table('school_settings')->get()->getRowArray();
        $settings   = $this->getCalendarSettings();

        $months = cal_academic_year_months($year['name']);
        $dayMap = cal_build_day_map($events);
        
        $sabtuLibur = isset($settings['sabtu_libur']) && (int) $settings['sabtu_libur'] === 1;
        $rekap = cal_effective_days_per_month($months, $dayMap, $sabtuLibur, $year['start_date'], $year['end_date']);

        $eventsByMonth = [];
        foreach ($months as $m) {
            $eventsByMonth[$m['year'] . '-' . $m['month']] = [];
        }
        foreach ($events as $e) {
            $key   = date('Y-n', strtotime($e['start_date']));
            $parts = explode('-', $key);
            $key   = $parts[0] . '-' . (int) $parts[1];
            if (isset($eventsByMonth[$key])) {
                $eventsByMonth[$key][] = $e;
            }
        }

        $letterSettings = [
            'kemenag_office'     => $school['letter_kemenag_office'] ?? 'Kantor Kementerian Agama',
            'letter_school_name' => $school['letter_school_name'] ?? strtoupper($school['school_name'] ?? 'MADRASAH'),
            'school_code'        => $school['letter_school_code'] ?? '',
            'city'               => $school['letter_city'] ?? $school['city'] ?? '',
            'logo_kemenag'       => $school['logo_kemenag'] ?? 'logo_kemenag.png',
        ];

        return view('academic_calendar/preview_report', [
            'year'          => $year,
            'school'        => $school,
            'schoolSettings'=> $school,
            'letterSettings'=> $letterSettings,
            'months'        => $months,
            'eventsByMonth' => $eventsByMonth,
            'categories'    => $categories,
            'rekap'         => $rekap,
            'settings'      => $settings,
        ]);
    }

    public function previewGrid($yearId, $orientation = 'landscape')
    {
        $year = $this->yearModel->find($yearId);
        if (! $year) {
            return redirect()->back()->with('error', 'Tahun ajaran tidak ditemukan.');
        }

        $orientation = strtolower($orientation) === 'portrait' ? 'portrait' : 'landscape';
        $events      = $this->eventModel->getByYear($yearId);
        $categories  = $this->categoryModel->getActive();
        $school      = \Config\Database::connect()->table('school_settings')->get()->getRowArray();
        $settings    = $this->getCalendarSettings();

        $months = cal_academic_year_months($year['name']);
        $dayMap = cal_build_day_map($events);
        
        $sabtuLibur = isset($settings['sabtu_libur']) && (int) $settings['sabtu_libur'] === 1;
        $rekap = cal_effective_days_per_month($months, $dayMap, $sabtuLibur, $year['start_date'], $year['end_date']);

        $viewName = $orientation === 'portrait'
            ? 'academic_calendar/preview_grid_portrait'
            : 'academic_calendar/preview_grid_landscape';

        $letterSettings = [
            'kemenag_office'     => $school['letter_kemenag_office'] ?? 'Kantor Kementerian Agama',
            'letter_school_name' => $school['letter_school_name'] ?? strtoupper($school['school_name'] ?? 'MADRASAH'),
            'school_code'        => $school['letter_school_code'] ?? '',
            'city'               => $school['letter_city'] ?? $school['city'] ?? '',
            'logo_kemenag'       => $school['logo_kemenag'] ?? 'logo_kemenag.png',
        ];

        return view($viewName, [
            'year'        => $year,
            'school'      => $school,
            'schoolSettings'=> $school,
            'letterSettings'=> $letterSettings,
            'months'      => $months,
            'dayMap'      => $dayMap,
            'categories'  => $categories,
            'rekap'       => $rekap,
            'orientation' => $orientation,
            'settings'    => $settings,
        ]);
    }

    // =========================================================
    // PENGATURAN SUMBER ACUAN
    // =========================================================
    public function settings()
    {
        $db       = \Config\Database::connect();
        $settings = $db->table('calendar_settings')->orderBy('id', 'ASC')->get()->getResultArray();

        return view('academic_calendar/settings', [
            'title'    => 'Pengaturan Kalender Pendidikan',
            'settings' => $settings,
        ]);
    }

    public function saveSettings()
    {
        $db   = \Config\Database::connect();
        $rows = $db->table('calendar_settings')->get()->getResultArray();

        foreach ($rows as $row) {
            $val = $this->request->getPost('setting_' . $row['key']);
            if ($val !== null) {
                $db->table('calendar_settings')
                   ->where('key', $row['key'])
                   ->update([
                       'value'      => trim($val),
                       'updated_at' => date('Y-m-d H:i:s'),
                   ]);
            }
        }

        return redirect()->to('/academic-calendar/settings')
                         ->with('success', 'Pengaturan kalender berhasil disimpan.');
    }

    // =========================================================
    // CETAK: LAPORAN (LIST KEGIATAN)
    // =========================================================
    public function printReport($yearId)
    {
        $year = $this->yearModel->find($yearId);
        if (! $year) {
            return redirect()->back()->with('error', 'Tahun ajaran tidak ditemukan.');
        }

        $events     = $this->eventModel->getByYear($yearId);
        $categories = $this->categoryModel->getActive();
        $school     = \Config\Database::connect()->table('school_settings')->get()->getRowArray();
        $settings   = $this->getCalendarSettings();

        $months = cal_academic_year_months($year['name']);
        $dayMap = cal_build_day_map($events);
        
        $sabtuLibur = isset($settings['sabtu_libur']) && (int) $settings['sabtu_libur'] === 1;
        $rekap = cal_effective_days_per_month($months, $dayMap, $sabtuLibur, $year['start_date'], $year['end_date']);

        // Kelompokkan kegiatan per bulan (berdasarkan tanggal mulai)
        $eventsByMonth = [];
        foreach ($months as $m) {
            $eventsByMonth[$m['year'] . '-' . $m['month']] = [];
        }
        foreach ($events as $e) {
            $key = date('Y-n', strtotime($e['start_date']));
            // normalisasi key agar sesuai format di atas (Y-m tanpa leading zero pada bulan)
            $parts = explode('-', $key);
            $key   = $parts[0] . '-' . (int) $parts[1];
            if (isset($eventsByMonth[$key])) {
                $eventsByMonth[$key][] = $e;
            }
        }

        $letterSettings = [
            'kemenag_office'     => $school['letter_kemenag_office'] ?? 'Kantor Kementerian Agama',
            'letter_school_name' => $school['letter_school_name'] ?? strtoupper($school['school_name'] ?? 'MADRASAH'),
            'school_code'        => $school['letter_school_code'] ?? '',
            'city'               => $school['letter_city'] ?? $school['city'] ?? '',
            'logo_kemenag'       => $school['logo_kemenag'] ?? 'logo_kemenag.png',
        ];

        $html = view('academic_calendar/print_report', [
            'year'          => $year,
            'school'        => $school,
            'schoolSettings'=> $school,
            'letterSettings'=> $letterSettings,
            'months'        => $months,
            'eventsByMonth' => $eventsByMonth,
            'categories'    => $categories,
            'rekap'         => $rekap,
            'settings'      => $settings,
        ]);

        $mpdf = new \Mpdf\Mpdf([
            'mode'        => 'utf-8',
            'format'      => 'A4',
            'orientation' => 'P',
            'margin_top'    => 15,
            'margin_bottom' => 15,
            'margin_left'   => 15,
            'margin_right'  => 15,
        ]);
        $mpdf->SetTitle('Kalender Pendidikan ' . $year['name']);
        $mpdf->WriteHTML($html);
        $mpdf->Output('Laporan-Kalender-Pendidikan-' . str_replace('/', '-', $year['name']) . '.pdf', 'I');
    }

    // =========================================================
    // CETAK: GRID 1 TAHUN (LANDSCAPE / PORTRAIT)
    // =========================================================
    public function printGrid($yearId, $orientation = 'landscape')
    {
        $year = $this->yearModel->find($yearId);
        if (! $year) {
            return redirect()->back()->with('error', 'Tahun ajaran tidak ditemukan.');
        }

        $orientation = strtolower($orientation) === 'portrait' ? 'portrait' : 'landscape';

        $events     = $this->eventModel->getByYear($yearId);
        $categories = $this->categoryModel->getActive();
        $school     = \Config\Database::connect()->table('school_settings')->get()->getRowArray();
        $settings   = $this->getCalendarSettings();

        $months = cal_academic_year_months($year['name']);
        $dayMap = cal_build_day_map($events);
        
        $sabtuLibur = isset($settings['sabtu_libur']) && (int) $settings['sabtu_libur'] === 1;
        $rekap = cal_effective_days_per_month($months, $dayMap, $sabtuLibur, $year['start_date'], $year['end_date']);

        $viewName = $orientation === 'portrait'
            ? 'academic_calendar/print_grid_portrait'
            : 'academic_calendar/print_grid_landscape';

        $letterSettings = [
            'kemenag_office'     => $school['letter_kemenag_office'] ?? 'Kantor Kementerian Agama',
            'letter_school_name' => $school['letter_school_name'] ?? strtoupper($school['school_name'] ?? 'MADRASAH'),
            'school_code'        => $school['letter_school_code'] ?? '',
            'city'               => $school['letter_city'] ?? $school['city'] ?? '',
            'logo_kemenag'       => $school['logo_kemenag'] ?? 'logo_kemenag.png',
        ];

        $html = view($viewName, [
            'year'       => $year,
            'school'     => $school,
            'schoolSettings'=> $school,
            'letterSettings'=> $letterSettings,
            'months'     => $months,
            'dayMap'     => $dayMap,
            'categories' => $categories,
            'rekap'      => $rekap,
            'settings'   => $settings,
        ]);

        $mpdf = new \Mpdf\Mpdf([
            'mode'        => 'utf-8',
            'format'      => 'A4',
            'orientation' => $orientation === 'portrait' ? 'P' : 'L',
            'margin_top'    => 8,
            'margin_bottom' => 8,
            'margin_left'   => 8,
            'margin_right'  => 8,
        ]);
        $mpdf->SetTitle('Grid Kalender Pendidikan ' . $year['name']);
        $mpdf->WriteHTML($html);
        $mpdf->Output('Grid-Kalender-Pendidikan-' . str_replace('/', '-', $year['name']) . '-' . $orientation . '.pdf', 'I');
    }

    // =========================================================
    // IMPORT HARI LIBUR NASIONAL
    // =========================================================
    public function importHolidays($yearId)
    {
        $year = $this->yearModel->find($yearId);
        if (! $year) {
            return redirect()->back()->with('error', 'Tahun ajaran tidak ditemukan.');
        }

        $startYear = (int) date('Y', strtotime($year['start_date']));
        $endYear   = (int) date('Y', strtotime($year['end_date']));

        $holidays = [];

        // 1. Tarik Hari Libur Nasional & Cuti Bersama dari API untuk tiap tahun beririsan
        for ($y = $startYear; $y <= $endYear; $y++) {
            $url = "https://libur.deno.dev/api?year=" . $y;
            $ch  = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 6);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            $yearHolidays = [];
            if ($httpCode === 200 && ! empty($response)) {
                $yearHolidays = json_decode($response, true);
            }

            if (empty($yearHolidays)) {
                // Fallback offline
                $yearHolidays = $this->getLocalHolidays($y);
            }

            if (! empty($yearHolidays)) {
                $holidays = array_merge($holidays, $yearHolidays);
            }
        }

        // 2. Cari atau buat Kategori "HL" (Libur Nasional/Keagamaan/Cuti Bersama)
        $category = $this->categoryModel->where('code', 'HL')
                                        ->where('deleted_at', null)
                                        ->first();
        if (! $category) {
            $catId = $this->categoryModel->insert([
                'name'       => 'Libur Nasional/Keagamaan/Cuti Bersama',
                'code'       => 'HL',
                'color'      => '#ff0040',
                'is_libur'   => 1,
                'sort_order' => 9,
            ]);
            $categoryId = $catId;
        } else {
            $categoryId = $category['id'];
        }

        // 3. Masukkan ke database
        $importedCount = 0;
        foreach ($holidays as $h) {
            $hDate = $h['date'];
            // Pastikan tanggal berada dalam rentang tahun ajaran terpilih
            if ($hDate >= $year['start_date'] && $hDate <= $year['end_date']) {
                // Hapus event lama pada tanggal yang sama agar ter-replace dengan data impor terbaru
                $this->eventModel->where('academic_year_id', $yearId)
                                 ->where('start_date', $hDate)
                                 ->delete();

                // Masukkan data impor terbaru dengan deskripsi kosong
                $this->eventModel->insert([
                    'academic_year_id'   => $yearId,
                    'academic_period_id' => null,
                    'category_id'        => $categoryId,
                    'title'              => $h['name'],
                    'start_date'         => $hDate,
                    'end_date'           => $hDate,
                    'description'        => '',
                    'created_by'         => session('user_id'),
                ]);
                $importedCount++;
            }
        }

        return redirect()->to('/academic-calendar?academic_year_id=' . $yearId)
                         ->with('success', "Berhasil mengimpor {$importedCount} hari libur.");
    }

    // =========================================================
    // KAMUS DATA HARI LIBUR OFFLINE (FALLBACK)
    // =========================================================
    private function getLocalHolidays($year)
    {
        $data = [
            2025 => [
                ['date' => '2025-01-01', 'name' => 'Tahun Baru 2025 Masehi'],
                ['date' => '2025-01-27', 'name' => 'Isra Mi\'raj Nabi Muhammad SAW'],
                ['date' => '2025-01-29', 'name' => 'Tahun Baru Imlek 2576 Kongzili'],
                ['date' => '2025-03-28', 'name' => 'Cuti Bersama Hari Raya Idul Fitri 1446 Hijriyah'],
                ['date' => '2025-03-29', 'name' => 'Hari Raya Nyepi'],
                ['date' => '2025-03-31', 'name' => 'Hari Raya Idul Fitri 1446 Hijriyah'],
                ['date' => '2025-04-01', 'name' => 'Hari Raya Idul Fitri 1446 Hijriyah'],
                ['date' => '2025-04-18', 'name' => 'Wafat Yesus Kristus'],
                ['date' => '2025-05-01', 'name' => 'Hari Buruh Internasional'],
                ['date' => '2025-05-12', 'name' => 'Hari Raya Waisak 2569 BE'],
                ['date' => '2025-05-29', 'name' => 'Kenaikan Yesus Kristus'],
                ['date' => '2025-06-01', 'name' => 'Hari Lahir Pancasila'],
                ['date' => '2025-06-06', 'name' => 'Hari Raya Idul Adha 1446 Hijriyah'],
                ['date' => '2025-06-27', 'name' => 'Tahun Baru Islam 1447 Hijriyah'],
                ['date' => '2025-08-17', 'name' => 'Hari Kemerdekaan Republik Indonesia'],
                ['date' => '2025-09-05', 'name' => 'Maulid Nabi Muhammad SAW'],
                ['date' => '2025-12-25', 'name' => 'Hari Raya Natal'],
            ],
            2026 => [
                ['date' => '2026-01-01', 'name' => 'Tahun Baru 2026 Masehi'],
                ['date' => '2026-01-16', 'name' => 'Isra Mi\'raj Nabi Muhammad SAW'],
                ['date' => '2026-02-16', 'name' => 'Cuti Bersama Tahun Baru Imlek 2577 Kongzili'],
                ['date' => '2026-02-17', 'name' => 'Tahun Baru Imlek 2577 Kongzili'],
                ['date' => '2026-03-18', 'name' => 'Cuti Bersama Hari Suci Nyepi Saka 1948'],
                ['date' => '2026-03-19', 'name' => 'Hari Suci Nyepi Saka 1948'],
                ['date' => '2026-03-20', 'name' => 'Cuti Bersama Hari Raya Idul Fitri 1447 Hijriyah'],
                ['date' => '2026-03-21', 'name' => 'Hari Raya Idul Fitri 1447 Hijriyah'],
                ['date' => '2026-03-22', 'name' => 'Hari Raya Idul Fitri 1447 Hijriyah'],
                ['date' => '2026-03-23', 'name' => 'Cuti Bersama Hari Raya Idul Fitri 1447 Hijriyah'],
                ['date' => '2026-03-24', 'name' => 'Cuti Bersama Hari Raya Idul Fitri 1447 Hijriyah'],
                ['date' => '2026-04-03', 'name' => 'Wafat Yesus Kristus / Jumat Agung'],
                ['date' => '2026-04-05', 'name' => 'Kebangkitan Yesus Kristus (Paskah)'],
                ['date' => '2026-05-01', 'name' => 'Hari Buruh Internasional'],
                ['date' => '2026-05-14', 'name' => 'Kenaikan Yesus Kristus'],
                ['date' => '2026-05-15', 'name' => 'Cuti Bersama Kenaikan Yesus Kristus'],
                ['date' => '2026-05-27', 'name' => 'Hari Raya Idul Adha 1447 Hijriyah'],
                ['date' => '2026-05-28', 'name' => 'Cuti Bersama Hari Raya Idul Adha 1447 Hijriyah'],
                ['date' => '2026-05-31', 'name' => 'Hari Raya Waisak 2570 BE'],
                ['date' => '2026-06-01', 'name' => 'Hari Lahir Pancasila'],
                ['date' => '2026-06-16', 'name' => 'Tahun Baru Islam 1448 Hijriyah'],
                ['date' => '2026-08-17', 'name' => 'Hari Kemerdekaan Republik Indonesia'],
                ['date' => '2026-08-25', 'name' => 'Maulid Nabi Muhammad SAW'],
                ['date' => '2026-12-24', 'name' => 'Cuti Bersama Hari Raya Natal'],
                ['date' => '2026-12-25', 'name' => 'Hari Raya Natal'],
            ],
            2027 => [
                ['date' => '2027-01-01', 'name' => 'Tahun Baru 2027 Masehi'],
                ['date' => '2027-01-05', 'name' => 'Isra Mi\'raj Nabi Muhammad SAW'],
                ['date' => '2027-02-06', 'name' => 'Tahun Baru Imlek 2578 Kongzili'],
                ['date' => '2027-03-09', 'name' => 'Hari Raya Nyepi Saka 1949'],
                ['date' => '2027-03-10', 'name' => 'Hari Raya Idul Fitri 1448 Hijriyah'],
                ['date' => '2027-03-11', 'name' => 'Hari Raya Idul Fitri 1448 Hijriyah'],
                ['date' => '2027-03-26', 'name' => 'Wafat Yesus Kristus'],
                ['date' => '2027-03-28', 'name' => 'Kebangkitan Yesus Kristus'],
                ['date' => '2027-05-01', 'name' => 'Hari Buruh Internasional'],
                ['date' => '2027-05-06', 'name' => 'Kenaikan Yesus Kristus'],
                ['date' => '2027-05-16', 'name' => 'Hari Raya Idul Adha 1448 Hijriyah'],
                ['date' => '2027-05-20', 'name' => 'Hari Raya Waisak 2571 BE'],
                ['date' => '2027-06-01', 'name' => 'Hari Lahir Pancasila'],
                ['date' => '2027-06-06', 'name' => 'Tahun Baru Islam 1449 Hijriyah'],
                ['date' => '2027-08-15', 'name' => 'Maulid Nabi Muhammad SAW'],
                ['date' => '2027-08-17', 'name' => 'Hari Kemerdekaan Republik Indonesia'],
                ['date' => '2027-12-25', 'name' => 'Hari Raya Natal'],
            ]
        ];

        return $data[$year] ?? [];
    }

    public function guruGrid()
    {
        $activeYear = $this->yearModel->getActive();
        if (!$activeYear) {
            return redirect()->back()->with('error', 'Belum ada tahun ajaran aktif!');
        }

        $events     = $this->eventModel->getByYear($activeYear['id']);
        $categories = $this->categoryModel->getActive();
        $school     = \Config\Database::connect()->table('school_settings')->get()->getRowArray();
        $settings   = $this->getCalendarSettings();

        $months = cal_academic_year_months($activeYear['name']);
        $dayMap = cal_build_day_map($events);

        $letterSettings = [
            'kemenag_office'     => $school['letter_kemenag_office'] ?? 'Kantor Kementerian Agama',
            'letter_school_name' => $school['letter_school_name'] ?? strtoupper($school['school_name'] ?? 'MADRASAH'),
            'school_code'        => $school['letter_school_code'] ?? '',
            'city'               => $school['letter_city'] ?? $school['city'] ?? '',
            'logo_kemenag'       => $school['logo_kemenag'] ?? 'logo_kemenag.png',
        ];

        return view('academic_calendar/guru_grid', [
            'title'          => 'Kalender Pendidikan (Grid)',
            'year'           => $activeYear,
            'school'         => $school,
            'schoolSettings' => $school,
            'letterSettings' => $letterSettings,
            'months'         => $months,
            'dayMap'         => $dayMap,
            'categories'     => $categories,
            'settings'       => $settings,
        ]);
    }

    public function guruList()
    {
        $activeYear = $this->yearModel->getActive();
        if (!$activeYear) {
            return redirect()->back()->with('error', 'Belum ada tahun ajaran aktif!');
        }

        $events     = $this->eventModel->getByYear($activeYear['id']);
        $categories = $this->categoryModel->getActive();
        $school     = \Config\Database::connect()->table('school_settings')->get()->getRowArray();
        $settings   = $this->getCalendarSettings();

        $months = cal_academic_year_months($activeYear['name']);
        $dayMap = cal_build_day_map($events);
        
        $sabtuLibur = isset($settings['sabtu_libur']) && (int) $settings['sabtu_libur'] === 1;
        $rekap = cal_effective_days_per_month($months, $dayMap, $sabtuLibur, $activeYear['start_date'], $activeYear['end_date']);

        $eventsByMonth = [];
        foreach ($months as $m) {
            $eventsByMonth[$m['year'] . '-' . $m['month']] = [];
        }
        foreach ($events as $e) {
            $key   = date('Y-n', strtotime($e['start_date']));
            $parts = explode('-', $key);
            $key   = $parts[0] . '-' . (int) $parts[1];
            if (isset($eventsByMonth[$key])) {
                $eventsByMonth[$key][] = $e;
            }
        }

        $letterSettings = [
            'kemenag_office'     => $school['letter_kemenag_office'] ?? 'Kantor Kementerian Agama',
            'letter_school_name' => $school['letter_school_name'] ?? strtoupper($school['school_name'] ?? 'MADRASAH'),
            'school_code'        => $school['letter_school_code'] ?? '',
            'city'               => $school['letter_city'] ?? $school['city'] ?? '',
            'logo_kemenag'       => $school['logo_kemenag'] ?? 'logo_kemenag.png',
        ];

        return view('academic_calendar/guru_list', [
            'title'          => 'Kalender Pendidikan (Daftar Kegiatan)',
            'year'           => $activeYear,
            'school'         => $school,
            'schoolSettings' => $school,
            'letterSettings' => $letterSettings,
            'months'         => $months,
            'eventsByMonth'  => $eventsByMonth,
            'categories'     => $categories,
            'rekap'          => $rekap,
            'settings'       => $settings,
        ]);
    }
}