<?php

use CodeIgniter\Router\RouteCollection;

if (!defined('STDERR')) {
    define('STDERR', fopen('php://output', 'w'));
}
if (!defined('STDOUT')) {
    define('STDOUT', fopen('php://output', 'w'));
}

/** @var RouteCollection $routes */

// ── PUBLIC GRADUATION ROUTES (NO AUTH) ─────────────────────────
$routes->get('/install', 'Install::index');
$routes->get('/show-server-time', function() {
    header('Content-Type: text/plain');
    echo "=== SERVER TIME DIAGNOSTICS ===\n";
    echo "PHP Version: " . PHP_VERSION . "\n";
    echo "PHP date.timezone: " . ini_get('date.timezone') . "\n";
    echo "System date('Y-m-d H:i:s'): " . date('Y-m-d H:i:s') . "\n";
    echo "UTC gmdate('Y-m-d H:i:s'): " . gmdate('Y-m-d H:i:s') . "\n";
    echo "CodeIgniter App Timezone: " . config('App')->appTimezone . "\n";
    echo "ROOTPATH: " . ROOTPATH . "\n";
    echo "FCPATH: " . FCPATH . "\n";

    echo "\n=== PHP BINARY PATHS ===\n";
    $paths = [
        '/usr/bin/php',
        '/usr/bin/php8.2',
        '/usr/bin/php82',
        '/opt/alt/php82/usr/bin/php',
        '/usr/local/bin/php',
        '/usr/local/bin/php8.2',
    ];
    foreach ($paths as $path) {
        echo $path . ": " . (file_exists($path) ? "EXISTS ✓" : "not found") . "\n";
    }
    echo "\nwhich php: " . shell_exec('which php') . "\n";
    echo "php --version: " . shell_exec('php --version') . "\n";
});

$routes->get('/show-online-log', function() {
    header('Content-Type: text/plain');
    $logPath = WRITEPATH . 'logs/log-' . date('Y-m-d') . '.log';
    if (file_exists($logPath)) {
        echo file_get_contents($logPath);
    } else {
        echo "Log file not found at: " . $logPath;
    }
});

$routes->get('/run-daily-journal', function() {
    header('Content-Type: text/plain');
    try {
        echo "=== RUNNING DAILY JOURNAL REMINDER via command() helper ===\n";
        ob_start();
        $result = command('app:send-daily-journal-reminder --force');
        $output = ob_get_clean();
        echo "Output Command:\n" . $result . "\n";
    } catch (\Throwable $e) {
        echo "ERROR running command: " . $e->getMessage() . "\n";
        echo $e->getTraceAsString() . "\n";
    }
});

$routes->get('/run-daily-attendance', function() {
    header('Content-Type: text/plain');
    try {
        echo "=== RUNNING DAILY ATTENDANCE via command() helper ===\n";
        ob_start();
        $result = command('app:send-daily-attendance --force');
        $output = ob_get_clean();
        echo "Output Command:\n" . $output . "\n";
    } catch (\Throwable $e) {
        echo "ERROR running command: " . $e->getMessage() . "\n";
        echo $e->getTraceAsString() . "\n";
    }
});

$routes->get('/run-daily-schedule', function() {
    header('Content-Type: text/plain');
    try {
        echo "=== RUNNING DAILY SCHEDULE via command() helper ===\n";
        ob_start();
        $result = command('app:send-daily-schedule --force');
        $output = ob_get_clean();
        echo "Result: " . var_export($result, true) . "\n";
        echo "Buffered Output:\n" . $output . "\n";
    } catch (\Throwable $e) {
        echo "ERROR: " . $e->getMessage() . "\n";
        echo $e->getTraceAsString() . "\n";
    }
});
$routes->post('/install/process', 'Install::process');

$routes->get('/kelulusan', 'Graduation::index');
$routes->group('api/public/graduation', function ($routes) {
    $routes->get('status', 'Graduation::getPublicGraduationStatus'); // AJAX for countdown
    $routes->post('check', 'Graduation::checkGraduation', ['filter' => 'ratelimit']);
    $routes->get('skl/(:segment)', 'Graduation::downloadSkl/$1');
    $routes->get('csrf-token', 'Graduation::getCsrfToken');
});

$routes->get('/', 'Auth::index');
$routes->get('/login', 'Auth::login');
$routes->post('/login', 'Auth::loginProcess');
$routes->get('/logout', 'Auth::logout');

// ── GENERIC AUTHENTICATED ROUTES (ALL ROLES) ─────────────────────
$routes->group('', ['filter' => 'auth'], function ($routes) {
    $routes->get('/dashboard', 'Admin\Dashboard::index');
    $routes->post('/user-management/change-password', 'Admin\UserManagement::changePassword');
});

// ── GURU ONLY ROUTES ─────────────────────────────────────────────
$routes->group('guru', ['filter' => 'auth:guru'], function ($routes) {
    $routes->get('dashboard', 'Guru\Dashboard::index');
    $routes->get('kelas', 'Guru\Kelas::index');
    $routes->get('assessment', 'Guru\Assessment::index');
    $routes->get('assessment/create-ash', 'Guru\Assessment::createAsh');
    $routes->post('assessment/store-ash', 'Guru\Assessment::storeAsh');
    $routes->get('assessment/koreksi/(:num)/(:num)/(:num)', 'Guru\Assessment::koreksi/$1/$2/$3');
    $routes->post('assessment/save-setting/(:num)/(:num)/(:num)', 'Guru\Assessment::saveSetting/$1/$2/$3');
    $routes->post('assessment/save-score', 'Guru\Assessment::saveScore');
    $routes->get('assessment/export/(:num)/(:num)/(:num)', 'Guru\Assessment::export/$1/$2/$3');
    $routes->get('academic-calendar/grid', 'Admin\AcademicCalendar::guruGrid');
    $routes->get('academic-calendar/list', 'Admin\AcademicCalendar::guruList');
    
    // Wali Kelas Reports & Student List
    $routes->get('siswa-kelas', 'Guru\HomeroomReport::studentList');
    $routes->get('presensi-kelas', 'Guru\HomeroomReport::index');
    $routes->get('presensi-kelas/rekap', 'Guru\HomeroomReport::getRekap');
    $routes->get('presensi-kelas/export-pdf', 'Guru\HomeroomReport::exportPdf');

    // Bimbingan & Konseling / Pengaduan
    $routes->get('counseling', 'Guru\Counseling::index');
    $routes->get('counseling/chat/(:num)', 'Guru\Counseling::chat/$1');
    $routes->post('counseling/send-message/(:num)', 'Guru\Counseling::sendMessage/$1');
    $routes->post('counseling/close/(:num)', 'Guru\Counseling::closeTicket/$1');
    $routes->post('counseling/save-notes/(:num)', 'Guru\Counseling::saveNotes/$1');
    $routes->post('counseling/refer/(:num)', 'Guru\Counseling::referTicket/$1');
    $routes->get('counseling/export-recap', 'Guru\Counseling::exportRecap');
    $routes->get('counseling/get-new-messages/(:num)/(:num)', 'Guru\Counseling::getNewMessages/$1/$2');

    // ── PERANGKAT PEMBELAJARAN (LEARNING DEVICES) ────────────────────
    // Setup & Dashboard
    $routes->get('learning-devices', 'Guru\LearningDeviceSetupController::index');
    $routes->get('learning-devices/create', 'Guru\LearningDeviceSetupController::create');
    $routes->post('learning-devices/store-setup', 'Guru\LearningDeviceSetupController::storeSetup');
    $routes->post('learning-devices/delete/(:num)', 'Guru\LearningDeviceSetupController::delete/$1');
    $routes->post('learning-devices/update-jp-per-week', 'Guru\LearningDeviceSetupController::updateJpPerWeek');


    // CP (Capaian Pembelajaran)
    $routes->get('learning-devices/cp/(:num)', 'Guru\CpController::cp/$1');
    $routes->post('learning-devices/save-cp/(:num)', 'Guru\CpController::saveCp/$1');
    $routes->post('learning-devices/cp/save/(:num)', 'Guru\CpController::saveCpAction/$1');

    // TP (Tujuan Pembelajaran)
    $routes->get('learning-devices/tp/(:num)', 'Guru\TpController::tp/$1');
    $routes->post('learning-devices/tp/save/(:num)', 'Guru\TpController::saveTpAction/$1');
    $routes->post('learning-devices/tp/generate/(:num)', 'Guru\TpController::generateTpAction/$1');
    $routes->post('learning-devices/generate-tp/(:num)', 'Guru\TpController::generateTp/$1');
    $routes->post('learning-devices/save-tps/(:num)', 'Guru\TpController::saveTps/$1');
    $routes->get('learning-devices/tp/preview-cp-tp/(:num)', 'Guru\TpController::previewCpTP/$1');
    $routes->get('learning-devices/tp/download-cp-tp/(:num)', 'Guru\TpController::downloadCpTP/$1');

    // ATP (Alur Tujuan Pembelajaran)
    $routes->get('learning-devices/atp/(:num)', 'Guru\AtpController::atp/$1');
    $routes->post('learning-devices/atp/save/(:num)', 'Guru\AtpController::saveAtpAction/$1');
    $routes->get('learning-devices/atp/preview-atp/(:num)', 'Guru\AtpController::previewAtp/$1');
    $routes->get('learning-devices/atp/download-atp/(:num)', 'Guru\AtpController::downloadAtp/$1');

    // KKTP (Kriteria Ketercapaian TP)
    $routes->get('learning-devices/kktp/(:num)', 'Guru\KktpController::kktp/$1');
    $routes->post('learning-devices/kktp/generate/(:num)', 'Guru\KktpController::generateKktpAction/$1');
    $routes->post('learning-devices/kktp/save/(:num)', 'Guru\KktpController::saveKktpAction/$1');
    $routes->get('learning-devices/kktp/download-kktp/(:num)', 'Guru\KktpController::downloadKktp/$1');
    $routes->get('learning-devices/kktp/print/(:num)', 'Guru\KktpController::printKktp/$1');

    // RPE (Rincian Pekan Efektif)
    $routes->get('learning-devices/rpe/(:num)', 'Guru\RpeController::rpe/$1');
    $routes->post('learning-devices/rpe/save/(:num)', 'Guru\RpeController::saveRpeAction/$1');

    // PROTA (Program Tahunan)
    $routes->get('learning-devices/prota/(:num)', 'Guru\ProtaController::prota/$1');
    $routes->post('learning-devices/prota/save/(:num)', 'Guru\ProtaController::saveProtaAction/$1');
    $routes->get('learning-devices/prota/generate-ai/(:num)', 'Guru\ProtaController::protaGenerateAi/$1');

    // PROMES (Program Semester)
    $routes->get('learning-devices/promes/(:num)', 'Guru\PromesController::promes/$1');
    $routes->post('learning-devices/promes/save/(:num)', 'Guru\PromesController::savePromesAction/$1');
    $routes->get('learning-devices/promes/generate-ai/(:num)/(:num)', 'Guru\PromesController::promesGenerateAi/$1/$2');

    // RPG / Modul Ajar (RPM) — tetap di LearningDeviceController
    $routes->get('learning-devices/rpm/(:num)', 'Guru\LearningDeviceController::rpm/$1');
    $routes->post('learning-devices/rpm/generate/(:num)', 'Guru\LearningDeviceController::generateRpmAction/$1');
    $routes->post('learning-devices/generate-modul/(:num)', 'Guru\LearningDeviceController::generateModul/$1');
    $routes->get('learning-devices/rpm/(:num)/edit/(:num)', 'Guru\LearningDeviceController::rpmEdit/$1/$2');
    $routes->post('learning-devices/rpm/(:num)/generate-field', 'Guru\LearningDeviceController::rpmGenerateField/$1');
    $routes->post('learning-devices/rpm/(:num)/save-field', 'Guru\LearningDeviceController::rpmSaveField/$1');
    $routes->post('learning-devices/rpm/(:num)/clear-all-ai', 'Guru\LearningDeviceController::rpmClearAIFields/$1');
    $routes->get('learning-devices/rpm/(:num)/preview/(:num)', 'Guru\LearningDeviceController::rpmPreview/$1/$2');
    $routes->get('learning-devices/rpm/(:num)/export-doc/(:num)', 'Guru\LearningDeviceController::rpmExportDoc/$1/$2');

    // Penilaian
    $routes->get('learning-devices/penilaian/(:num)', 'Guru\PenilaianController::penilaian/$1');
    $routes->post('learning-devices/penilaian/generate/(:num)', 'Guru\PenilaianController::generatePenilaianAction/$1');
    $routes->post('learning-devices/penilaian/save/(:num)', 'Guru\PenilaianController::savePenilaianAction/$1');

    // Export
    $routes->get('learning-devices/export/(:num)/(:any)', 'Guru\ExportController::export/$1/$2');
    $routes->get('learning-devices/preview-all/(:num)', 'Guru\LearningDeviceController::previewAll/$1');

    // ── JURNAL MENGAJAR ─────────────────────────────────────
    $routes->get('journal', 'Guru\JournalController::index');
    $routes->get('journal/create', 'Guru\JournalController::create');
    $routes->post('journal/store', 'Guru\JournalController::store');
    $routes->get('journal/detail/(:num)', 'Guru\JournalController::detail/$1');
    $routes->post('journal/delete/(:num)', 'Guru\JournalController::delete/$1');
    $routes->get('journal/tp', 'Guru\JournalController::getTpByClassSubject');
    $routes->get('journal/students', 'Guru\JournalController::getStudentsByClassroom');
    $routes->get('journal/print/(:num)/(:num)', 'Guru\JournalController::print/$1/$2');
    $routes->get('journal/print-all', 'Guru\JournalController::printAll');

    // ── TAHFIDZ AL-QUR'AN (GURU) ─────────────────────────────
    $routes->get('tahfidz', 'Guru\TahfidzController::index');
    $routes->get('tahfidz/setoran', 'Guru\TahfidzController::setoran');
    $routes->get('tahfidz/setoran/(:num)', 'Guru\TahfidzController::setoran/$1');
    $routes->post('tahfidz/setoran/store', 'Guru\TahfidzController::storeSetoran');
    $routes->post('tahfidz/setoran/delete/(:num)', 'Guru\TahfidzController::deleteSetoran/$1');
    $routes->get('tahfidz/hafalan', 'Guru\TahfidzController::hafalan');
    $routes->get('tahfidz/hafalan/(:num)', 'Guru\TahfidzController::hafalan/$1');
    $routes->post('tahfidz/hafalan/save', 'Guru\TahfidzController::saveHafalan');
    $routes->get('tahfidz/progress', 'Guru\TahfidzController::progress');
    $routes->get('tahfidz/progress/(:num)', 'Guru\TahfidzController::progress/$1');
    $routes->get('tahfidz/laporan', 'Guru\TahfidzController::laporan');
    $routes->get('tahfidz/laporan/(:num)', 'Guru\TahfidzController::laporan/$1');
    $routes->get('tahfidz/surah-info/(:num)', 'Guru\TahfidzController::getSurahInfo/$1');
    $routes->post('tahfidz/wa-group', 'Guru\TahfidzController::sendWaGrup');
    $routes->post('tahfidz/wa-ortu', 'Guru\TahfidzController::sendWaOrtu');
    $routes->get('tahfidz/student-report', 'Guru\TahfidzController::studentReport');
    $routes->get('tahfidz/report-setup', 'Guru\TahfidzController::reportSetup');
    $routes->post('tahfidz/save-report', 'Guru\TahfidzController::saveReport');
});

// ── TATA USAHA ONLY ROUTES ───────────────────────────────────────
$routes->group('tata-usaha', ['filter' => 'auth:tata_usaha'], function ($routes) {
    $routes->get('dashboard', 'TataUsaha\Dashboard::index');
});

// ── SHARED TATA USAHA & ADMIN ROUTES ──────────────────────────────
 $routes->group('', ['filter' => 'auth:superadmin,admin,tata_usaha,guru'], function ($routes) {
    $routes->get('/attendance-sheet', 'Admin\AttendanceSheet::index');
    $routes->get('/attendance-sheet/print', 'Admin\AttendanceSheet::print');

    // Letters (Surat Resmi)
    $routes->get( '/letter',                         'Admin\LetterController::index');
    $routes->get( '/letter/keterangan-aktif',        'Admin\LetterController::keteranganAktif');
    $routes->post('/letter/keterangan-aktif/preview','Admin\LetterController::keteranganAktifPreview');
    $routes->get( '/letter/keterangan-aktif/print/(:num)', 'Admin\LetterController::keteranganAktifPrint/$1');
    $routes->get( '/letter/mutasi',                  'Admin\LetterController::mutasi');
    $routes->post('/letter/mutasi/preview',          'Admin\LetterController::mutasiPreview');
    $routes->get( '/letter/mutasi/print/(:num)',     'Admin\LetterController::mutasiPrint/$1');
    $routes->get( '/letter/get-student',             'Admin\LetterController::getStudentData');
    $routes->get( '/letter/get-teacher',             'Admin\LetterController::getTeacherData');
    $routes->get( '/letter/delete/(:num)',           'Admin\LetterController::deleteLog/$1');
    $routes->get( '/letter/surat-tugas',             'Admin\LetterController::suratTugas');
    $routes->post('/letter/surat-tugas/preview',     'Admin\LetterController::suratTugasPreview');
    $routes->get( '/letter/surat-tugas/print/(:num)','Admin\LetterController::suratTugasPrint/$1');
    $routes->get( '/letter/sppd',                    'Admin\LetterController::sppd');
    $routes->post('/letter/sppd/preview',            'Admin\LetterController::sppdPreview');
    $routes->get( '/letter/sppd/print/(:num)',       'Admin\LetterController::sppdPrint/$1');

    // Student by-class (shared with TU for tabungan)
    $routes->get('/student/by-class', 'Admin\Student::byClass');
});

// ── SHARED GURU & ADMIN ROUTES ───────────────────────────────────
$routes->group('', ['filter' => 'auth:superadmin,admin,guru'], function ($routes) {
    // Attendance BK (Manual)
    $routes->get('/attendance', 'Admin\Attendance::index');
    $routes->get('/attendance/get-classrooms', 'Admin\Attendance::getClassrooms');
    $routes->get('/attendance/get-students', 'Admin\Attendance::getStudents');
    $routes->post('/attendance/save', 'Admin\Attendance::save');
    $routes->get('/attendance/rekap-bulanan', 'Admin\Attendance::rekapBulanan');
    $routes->get('/attendance/get-rekap-bulanan', 'Admin\Attendance::getRekapBulanan');
    $routes->get('/attendance/rekap-semester', 'Admin\Attendance::rekapSemester');
    $routes->get('/attendance/get-rekap-semester', 'Admin\Attendance::getRekapSemester');
    $routes->get('/attendance/export-pdf-bulanan', 'Admin\Attendance::exportPdfBulanan');
    $routes->get('/attendance/export-pdf-semester', 'Admin\Attendance::exportPdfSemester');
    $routes->get('/attendance/export-excel-bulanan', 'Admin\Attendance::exportExcelMonthly');
    $routes->get('/attendance/export-excel-semester', 'Admin\Attendance::exportExcelSemester');

    // Attendance QR Code Report & Rekap
    $routes->get( '/attendance/qr-report',                'Admin\AttendanceQr::dailyReport');
    $routes->get( '/attendance/qr-rekap-bulanan',         'Admin\AttendanceQr::qrRekapBulanan');
    $routes->get( '/attendance/qr-get-rekap-bulanan',     'Admin\AttendanceQr::qrGetRekapBulanan');
    $routes->get( '/attendance/qr-rekap-semester',        'Admin\AttendanceQr::qrRekapSemester');
    $routes->get( '/attendance/qr-get-rekap-semester',    'Admin\AttendanceQr::qrGetRekapSemester');
    $routes->get( '/attendance/qr-export-pdf-bulanan',    'Admin\AttendanceQr::qrExportPdfBulanan');
    $routes->get( '/attendance/qr-export-pdf-semester',   'Admin\AttendanceQr::qrExportPdfSemester');
    $routes->post('/attendance/qr-mark-present',          'Admin\AttendanceQr::markPresentManual');
    $routes->post('/attendance/qr-mark-present-bulk',     'Admin\AttendanceQr::markPresentBulk');
    $routes->post('/attendance/qr-save-status',           'Admin\AttendanceQr::saveStatusManual');
    $routes->post('/attendance/send-wa-grup',              'Admin\AttendanceQr::sendWaGrup');

    // CP Management
    $routes->get('/cp-management', 'Admin\CpManagement::index');
    $routes->get('/cp-management/create', 'Admin\CpManagement::create');
    $routes->post('/cp-management/store', 'Admin\CpManagement::store');
    $routes->get('/cp-management/edit/(:num)', 'Admin\CpManagement::edit/$1');
    $routes->post('/cp-management/update/(:num)', 'Admin\CpManagement::update/$1');
    $routes->post('/cp-management/delete/(:num)', 'Admin\CpManagement::delete/$1');

    // Master TP
    $routes->get('/tp-management', 'Admin\TpManagement::index');
    $routes->post('/tp-management/delete/(:num)', 'Admin\TpManagement::delete/$1');
});

// ── ADMIN ONLY ROUTES ────────────────────────────────────────────
$routes->group('', ['filter' => 'auth:superadmin,admin'], function ($routes) {
    // ── TAHFIDZ ADMIN ─────────────────────────────────────────────
    $routes->get('/admin/tahfidz/create', 'Admin\TahfidzAdmin::create');
    $routes->post('/admin/tahfidz/store', 'Admin\TahfidzAdmin::store');
    $routes->get('/admin/tahfidz/(:num)/edit', 'Admin\TahfidzAdmin::edit/$1');
    $routes->post('/admin/tahfidz/(:num)/update', 'Admin\TahfidzAdmin::update/$1');
    $routes->post('/admin/tahfidz/(:num)/delete', 'Admin\TahfidzAdmin::delete/$1');
    $routes->get('/admin/tahfidz/programs/(:num)/students', 'Admin\TahfidzAdmin::students/$1');
    $routes->post('/admin/tahfidz/programs/(:num)/add-from-classrooms', 'Admin\TahfidzAdmin::addFromClassrooms/$1');
    $routes->post('/admin/tahfidz/programs/(:num)/add-students-bulk', 'Admin\TahfidzAdmin::addStudentsBulk/$1');
    $routes->post('/admin/tahfidz/programs/(:num)/toggle-student', 'Admin\TahfidzAdmin::toggleStudent/$1');
    $routes->post('/admin/tahfidz/programs/(:num)/clear-students', 'Admin\TahfidzAdmin::clearStudents/$1');
    $routes->get('/admin/tahfidz/get-wa-groups', 'Admin\TahfidzAdmin::getWaGroups');

    // Graduation Module
    $routes->group('admin/graduation', function ($routes) {
        $routes->get('settings', 'Admin\\Graduation::settings');
        $routes->post('settings/save', 'Admin\\Graduation::saveSettings');
        $routes->get('students', 'Admin\\Graduation::students');
        $routes->get('students/ajax', 'Admin\\Graduation::getFinalYearStudentsAjax');
        $routes->post('students/bulk-status', 'Admin\\Graduation::bulkStatus');
        $routes->post('students/(:num)/status', 'Admin\\Graduation::updateStatus/$1');
        $routes->get('skl/upload', 'Admin\\Graduation::uploadSkl');
        $routes->get('skl/student-list', 'Admin\\Graduation::getSklStudentListAjax');
        $routes->post('skl/upload-process', 'Admin\\Graduation::processSklUpload');
        $routes->get('skl/summary', 'Admin\\Graduation::uploadSkl'); // Reuse uploadSkl view for summary
        $routes->delete('skl/(:num)', 'Admin\\Graduation::deleteSklMassal/$1');
    });
    // Settings
    $routes->get('/settings', 'Admin\Settings::index');
    $routes->post('/settings/save', 'Admin\Settings::save');
    $routes->get('/settings/remove-logo/(:any)', 'Admin\Settings::removeLogo/$1');
    $routes->get('/settings/attendance-features', 'Admin\Settings::attendanceFeatures');
    $routes->post('/settings/attendance-features/save', 'Admin\Settings::saveAttendanceFeatures');
    $routes->get('/settings/ai', 'Admin\Settings::aiSettings');
    $routes->post('/settings/ai/save', 'Admin\Settings::saveAiSettings');
    $routes->get('/settings/student-portal', 'Admin\Settings::studentPortal');
    $routes->post('/settings/student-portal/save', 'Admin\Settings::saveStudentPortal');
    $routes->get('/settings/whatsapp', 'Admin\Settings::waSettings');
    $routes->get('/settings/whatsapp/test', 'Admin\Settings::testWa');
    $routes->post('/settings/whatsapp/save', 'Admin\Settings::saveWaSettings');
    $routes->get('/settings/storage', 'Admin\StorageSettings::index');
    $routes->post('/settings/storage/save', 'Admin\StorageSettings::save');
    $routes->get('/settings/storage/oauth', 'Admin\StorageSettings::oauthInit');
    $routes->get('/settings/storage/oauth-callback', 'Admin\StorageSettings::oauthCallback');


    // Database Management
    $routes->get('/settings/database', 'Admin\Database::index');
    $routes->get('/settings/database/migrate', 'Admin\Database::migrate');
    $routes->get('/settings/database/backup', 'Admin\Database::backup');
    $routes->get('/settings/database/backup/full', 'Admin\Database::fullBackup');
    $routes->get('/settings/database/backup/download/(:segment)', 'Admin\Database::downloadBackup/$1');
    $routes->post('/settings/database/backup/delete', 'Admin\Database::deleteBackup');
    $routes->post('/settings/database/reset', 'Admin\Database::reset');
    // System Updater (Offline Only)
    $routes->get('/updater', 'Admin\Updater::index');
    $routes->post('/updater/offline', 'Admin\Updater::offlineUpdate');

    // Academic Year
    $routes->get('/academic-year', 'Admin\AcademicYear::index');
    $routes->post('/academic-year/store', 'Admin\AcademicYear::store');
    $routes->post('/academic-year/update/(:num)', 'Admin\AcademicYear::update/$1');
    $routes->get('/academic-year/set-active/(:num)', 'Admin\AcademicYear::setActive/$1');
    $routes->get('/academic-year/delete/(:num)', 'Admin\AcademicYear::delete/$1');

    // Academic Period
    $routes->get('/academic-period', 'Admin\AcademicPeriod::index');
    $routes->post('/academic-period/store', 'Admin\AcademicPeriod::store');
    $routes->post('/academic-period/update/(:num)', 'Admin\AcademicPeriod::update/$1');
    $routes->get('/academic-period/set-active/(:num)', 'Admin\AcademicPeriod::setActive/$1');
    $routes->get('/academic-period/delete/(:num)', 'Admin\AcademicPeriod::delete/$1');

    // Grade
    $routes->get('/grade', 'Admin\Grade::index');
    $routes->post('/grade/store', 'Admin\Grade::store');
    $routes->post('/grade/update/(:num)', 'Admin\Grade::update/$1');
    $routes->get('/grade/delete/(:num)', 'Admin\Grade::delete/$1');

    // Major
    $routes->get('/major', 'Admin\Major::index');
    $routes->post('/major/store', 'Admin\Major::store');
    $routes->post('/major/update/(:num)', 'Admin\Major::update/$1');
    $routes->get('/major/delete/(:num)', 'Admin\Major::delete/$1');

    // Classroom
    $routes->get('/classroom', 'Admin\Classroom::index');
    $routes->post('/classroom/store', 'Admin\Classroom::store');
    $routes->post('/classroom/update/(:num)', 'Admin\Classroom::update/$1');
    $routes->get('/classroom/delete/(:num)', 'Admin\Classroom::delete/$1');
    $routes->post('/classroom/copy-from-year', 'Admin\Classroom::copyFromYear');
    $routes->get('/classroom/get-wa-group/(:num)', 'Admin\Classroom::getWaGroup/$1');

    // Student
    $routes->get('/student', 'Admin\Student::index');
    $routes->get('/student/completeness', 'Admin\Student::completeness');
    $routes->get('/student/create', 'Admin\Student::create');
    $routes->get('/student/suggest-nis', 'Admin\Student::getSuggestNis');
    $routes->get('/student/import', 'Admin\Student::importExcel');
    $routes->post('/student/import-process', 'Admin\Student::importProcess');
    $routes->get('/student/download-template', 'Admin\Student::downloadTemplate');
    $routes->get('/student/generate-accounts', 'Admin\Student::generateMissingAccounts');
    $routes->post('/student/store', 'Admin\Student::store');
    $routes->get('/student/show/(:num)', 'Admin\Student::show/$1');
    $routes->get('/student/edit/(:num)', 'Admin\Student::edit/$1');
    $routes->post('/student/update/(:num)', 'Admin\Student::update/$1');
    $routes->get('/student/delete/(:num)', 'Admin\Student::delete/$1');
    $routes->post('/student/reset-password/(:num)', 'Admin\Student::resetPassword/$1');
    $routes->get('/student/alumni', 'Admin\Student::alumni');
    $routes->post('/student/reactivate/(:num)', 'Admin\Student::reactivate/$1');
    $routes->post('/student/exit-process/(:num)', 'Admin\Student::exitProcess/$1');

    // Buku Induk
    $routes->get('/buku-induk', 'Admin\BukuInduk::index');
    $routes->get('/buku-induk/view/(:num)', 'Admin\BukuInduk::view/$1');
    $routes->get('/buku-induk/print/(:num)', 'Admin\BukuInduk::print/$1');

    // Student History
    $routes->get('/student-history', 'Admin\StudentHistory::index');
    $routes->get('/student-history/search', 'Admin\StudentHistory::search');
    $routes->get('/student-history/history/(:num)', 'Admin\StudentHistory::history/$1');

    // Move Class
    $routes->get('/move-class', 'Admin\MoveClass::index');
    $routes->get('/move-class/students', 'Admin\MoveClass::getStudents');
    $routes->post('/move-class/process', 'Admin\MoveClass::process');

    // Promote Class
    $routes->get('/promote-class', 'Admin\PromoteClass::index');
    $routes->get('/promote-class/students', 'Admin\PromoteClass::getStudents');
    $routes->get('/promote-class/classrooms-by-year', 'Admin\PromoteClass::getClassroomsByYear');
    $routes->get('/promote-class/target-students', 'Admin\PromoteClass::getTargetStudents');
    $routes->post('/promote-class/promote', 'Admin\PromoteClass::promote');
    $routes->post('/promote-class/graduate', 'Admin\PromoteClass::graduate');

    // Class Assignment
    $routes->get('/class-assignment', 'Admin\ClassAssignment::index');
    $routes->get('/class-assignment/students', 'Admin\ClassAssignment::students');
    $routes->post('/class-assignment/assign', 'Admin\ClassAssignment::assign');
    $routes->post('/class-assignment/move', 'Admin\ClassAssignment::move');

    // Teacher
    $routes->get('/teacher', 'Admin\Teacher::index');
    $routes->get('/teacher/create', 'Admin\Teacher::create');
    $routes->post('/teacher/store', 'Admin\Teacher::store');
    $routes->get('/teacher/edit/(:num)', 'Admin\Teacher::edit/$1');
    $routes->post('/teacher/update/(:num)', 'Admin\Teacher::update/$1');
    $routes->get('/teacher/delete/(:num)', 'Admin\Teacher::delete/$1');
    $routes->get('/teacher/restore/(:num)', 'Admin\Teacher::restore/$1');
    $routes->get('/teacher/force-delete/(:num)', 'Admin\Teacher::forceDelete/$1');
    $routes->post('/teacher/create-account/(:num)', 'Admin\Teacher::createAccount/$1');
    $routes->post('/teacher/create-account-bulk', 'Admin\Teacher::createAccountBulk');
    $routes->post('/teacher/reset-password/(:num)', 'Admin\Teacher::resetPassword/$1');
    $routes->get('/teacher/import', 'Admin\Teacher::importExcel');
    $routes->post('/teacher/import-process', 'Admin\Teacher::importProcess');
    $routes->get('/teacher/download-template', 'Admin\Teacher::downloadTemplate');
    $routes->get('/teacher/export', 'Admin\Teacher::exportExcel');

    // Subject
    $routes->get('/subject', 'Admin\Subject::index');
    $routes->post('/subject/store', 'Admin\Subject::store');
    $routes->post('/subject/update/(:num)', 'Admin\Subject::update/$1');
    $routes->get('/subject/delete/(:num)', 'Admin\Subject::delete/$1');

    // School Subject
    $routes->get('/school-subject', 'Admin\SchoolSubject::index');
    $routes->get('/school-subject/get-master-subjects', 'Admin\SchoolSubject::getMasterSubjects');
    $routes->post('/school-subject/import-from-master', 'Admin\SchoolSubject::importFromMaster');
    $routes->post('/school-subject/store', 'Admin\SchoolSubject::store');
    $routes->post('/school-subject/update/(:num)', 'Admin\SchoolSubject::update/$1');
    $routes->get('/school-subject/delete/(:num)', 'Admin\SchoolSubject::delete/$1');
    $routes->post('/school-subject/toggle-active/(:num)', 'Admin\SchoolSubject::toggleActive/$1');
    $routes->post('/school-subject/update-order', 'Admin\SchoolSubject::updateOrder');

    // BK Assignment
    $routes->get('/bk-assignment', 'Admin\BkAssignment::index');
    $routes->get('/bk-assignment/get-by-teacher', 'Admin\BkAssignment::getByTeacher');
    $routes->post('/bk-assignment/save', 'Admin\BkAssignment::save');
    $routes->get('/bk-assignment/delete/(:num)', 'Admin\BkAssignment::delete/$1');

    // Homeroom Assignment
    $routes->get('/homeroom-assignment', 'Admin\HomeroomAssignment::index');
    $routes->post('/homeroom-assignment/save', 'Admin\HomeroomAssignment::save');

    // Teaching Assignment
    $routes->get('/teaching-assignment', 'Admin\TeachingAssignment::index');
    $routes->get('/teaching-assignment/get-classrooms', 'Admin\TeachingAssignment::getClassrooms');
    $routes->get('/teaching-assignment/get-subjects', 'Admin\TeachingAssignment::getSubjects');
    $routes->get('/teaching-assignment/sync-from-asc', 'Admin\TeachingAssignment::syncFromAsc');
    $routes->get('/teaching-assignment/sync-from-local', 'Admin\TeachingAssignment::syncFromLocal');
    $routes->get('/teaching-assignment/sync-from-manual', 'Admin\TeachingAssignment::syncFromManual');
    $routes->post('/teaching-assignment/save', 'Admin\TeachingAssignment::save');

    // Student Card
    $routes->get('/student-card', 'Admin\StudentCard::index');
    $routes->get('/student-card/get-students', 'Admin\StudentCard::getStudents');
    $routes->get('/student-card/print', 'Admin\StudentCard::print');
    $routes->get('/student-card/settings', 'Admin\StudentCard::settings');
    $routes->post('/student-card/save-settings', 'Admin\StudentCard::saveSettings');
    $routes->post('/student-card/upload-photo', 'Admin\StudentCard::uploadPhoto');
    $routes->post('/student-card/upload-mass-photo', 'Admin\StudentCard::uploadMassPhoto');
    $routes->post('/student-card/delete-photo/(:num)', 'Admin\StudentCard::deletePhoto/$1');

    // Leger Import
    $routes->get('/leger-import',                    'Admin\LegerImport::index');
    $routes->post('/leger-import/upload',            'Admin\LegerImport::upload');
    $routes->post('/leger-import/confirm',           'Admin\LegerImport::confirm');
    $routes->get('/leger-import/view',               'Admin\LegerImport::view');
    $routes->get('/leger-import/print',              'Admin\LegerImport::print');
    $routes->get('/leger-import/delete/(:num)',      'Admin\LegerImport::delete/$1');
    $routes->get('/leger-import/get-periods',        'Admin\LegerImport::getPeriods');
    $routes->get('/leger-import/get-classrooms',     'Admin\LegerImport::getClassrooms');
    $routes->get('/leger-import/export-excel',        'Admin\LegerImport::exportExcel');

    // Assessment Admin
    $routes->get('/assessment', 'Admin\Assessment::index');
    $routes->get('/assessment/create', 'Admin\Assessment::create');
    $routes->post('/assessment/store', 'Admin\Assessment::store');
    $routes->get('/assessment/edit/(:num)', 'Admin\Assessment::edit/$1');
    $routes->post('/assessment/update/(:num)', 'Admin\Assessment::update/$1');
    $routes->get('/assessment/delete/(:num)', 'Admin\Assessment::delete/$1');
    $routes->get('/assessment/toggle-open/(:num)', 'Admin\Assessment::toggleOpen/$1');
    $routes->get('/assessment/toggle-visible/(:num)', 'Admin\Assessment::toggleVisible/$1');
    $routes->get('/assessment/get-classrooms-by-grade', 'Admin\Assessment::getClassroomsByGrade');

    // Exam Event
    $routes->group('exam-event', ['namespace' => 'App\Controllers\Admin'], function ($routes) {
        $routes->get('/', 'ExamEvent::index');
        $routes->get('create', 'ExamEvent::create');
        $routes->post('store', 'ExamEvent::store');
        $routes->get('edit/(:num)', 'ExamEvent::edit/$1');
        $routes->post('update/(:num)', 'ExamEvent::update/$1');
        $routes->get('delete/(:num)', 'ExamEvent::delete/$1');
        
        $routes->get('(:num)/schedule', 'ExamEvent::schedule/$1');
        $routes->post('(:num)/schedule/store', 'ExamEvent::storeSchedule/$1');
        $routes->post('schedule/update/(:num)', 'ExamEvent::updateSchedule/$1');
        $routes->get('schedule/delete/(:num)', 'ExamEvent::deleteSchedule/$1');
        $routes->post('(:num)/schedule/copy-from-event', 'ExamEvent::copyScheduleFromEvent/$1');

        $routes->get('(:num)/proctor', 'ExamEvent::proctor/$1');
        $routes->post('(:num)/proctor/save-settings', 'ExamEvent::saveProctorSettings/$1');
        $routes->post('(:num)/proctor/generate', 'ExamEvent::generateProctors/$1');
        $routes->get('(:num)/proctor/clear', 'ExamEvent::clearProctors/$1');
        $routes->get('(:num)/proctor/matrix', 'ExamEvent::proctorMatrix/$1');
        $routes->get('(:num)/print/proctor-schedule', 'ExamEvent::printProctorSchedule/$1');
        $routes->get('(:num)/print/proctor-attendance', 'ExamEvent::printProctorAttendance/$1');
        $routes->get('(:num)/print/exam-schedule', 'ExamEvent::printExamSchedule/$1');

        $routes->get('(:num)/rooms', 'ExamEvent::rooms/$1');
        $routes->post('(:num)/rooms/store', 'ExamEvent::storeRoom/$1');
        $routes->post('rooms/update/(:num)', 'ExamEvent::updateRoom/$1');
        $routes->get('rooms/delete/(:num)', 'ExamEvent::deleteRoom/$1');
        $routes->post('(:num)/rooms/generate-from-classes', 'ExamEvent::generateFromClasses/$1');
        $routes->post('(:num)/rooms/copy-from-event', 'ExamEvent::copyFromEvent/$1');
        
        $routes->get('(:num)/allocation', 'ExamEvent::allocation/$1');
        $routes->post('(:num)/allocation/save-rule', 'ExamEvent::saveRule/$1');
        $routes->get('allocation/delete-rule/(:num)', 'ExamEvent::deleteRule/$1');
        $routes->post('(:num)/allocation/save-pairing-plan', 'ExamEvent::savePairingPlan/$1');
        $routes->get('(:num)/allocation/validate', 'ExamEvent::validateAllocation/$1');
        
        $routes->post('(:num)/finalize', 'ExamEvent::finalize/$1');
        $routes->post('(:num)/unfinalize', 'ExamEvent::unfinalize/$1');
        
        $routes->get('(:num)/print/cards', 'ExamEvent::printCards/$1');
        $routes->get('(:num)/print/desk-labels', 'ExamEvent::printDeskLabels/$1');
        $routes->get('(:num)/print/attendance', 'ExamEvent::printAttendance/$1');
        $routes->get('(:num)/print/seating-chart', 'ExamEvent::printSeatingChart/$1');
        $routes->get('(:num)/print/official-report', 'ExamEvent::printOfficialReport/$1');
        $routes->get('(:num)/print/room-summary', 'ExamEvent::printRoomSummary/$1');
        $routes->get('(:num)/print/room-participants', 'ExamEvent::printRoomParticipants/$1');
        $routes->get('(:num)/print/door-label', 'ExamEvent::printDoorLabel/$1');
        $routes->get('(:num)/print/bell-schedule', 'ExamEvent::printBellSchedule/$1');
        $routes->get('(:num)/print/proctor-rules', 'ExamEvent::printProctorRules/$1');
        $routes->get('(:num)/print/student-rules', 'ExamEvent::printStudentRules/$1');
        $routes->get('(:num)/print/absent-students', 'ExamEvent::printAbsentStudents/$1');
        $routes->get('(:num)/print/blank-cards', 'ExamEvent::printBlankCards/$1');
    });

    // Schedule Timeslot
    $routes->get( '/schedule-timeslot',                    'Admin\ScheduleTimeslot::index');
    $routes->post('/schedule-timeslot/store',              'Admin\ScheduleTimeslot::store');
    $routes->post('/schedule-timeslot/update/(:num)',      'Admin\ScheduleTimeslot::update/$1');
    $routes->get( '/schedule-timeslot/delete/(:num)',      'Admin\ScheduleTimeslot::delete/$1');
    $routes->get( '/schedule-timeslot/toggle-active/(:num)','Admin\ScheduleTimeslot::toggleActive/$1');
    $routes->post('/schedule-timeslot/copy-day',           'Admin\ScheduleTimeslot::copyDay');
    $routes->post('/schedule-timeslot/delete-day',          'Admin\ScheduleTimeslot::deleteDay');
     
    // Schedule Load
    $routes->get( '/schedule-load',                              'Admin\ScheduleLoad::index');
    $routes->post('/schedule-load/store',                        'Admin\ScheduleLoad::store');
    $routes->post('/schedule-load/update/(:num)',                'Admin\ScheduleLoad::update/$1');
    $routes->get( '/schedule-load/delete/(:num)',                'Admin\ScheduleLoad::delete/$1');
    $routes->post('/schedule-load/delete-ajax/(:num)',           'Admin\ScheduleLoad::deleteAjax/$1');
    $routes->post('/schedule-load/delete-bulk',                  'Admin\ScheduleLoad::deleteBulk');
    $routes->post('/schedule-load/delete-all-by-teacher/(:num)','Admin\ScheduleLoad::deleteAllByTeacher/$1');
    $routes->get( '/schedule-load/delete-all',                   'Admin\ScheduleLoad::deleteAll');
    $routes->get( '/schedule-load/get-subjects-by-teacher',      'Admin\ScheduleLoad::getSubjectsByTeacher');
    $routes->get( '/schedule-load/get-suggest-split',            'Admin\ScheduleLoad::getSuggestSplit');
    $routes->post('/schedule-load/save-target',                  'Admin\ScheduleLoad::saveTarget');
    $routes->get( '/schedule-load/get-target-info/(:num)',       'Admin\ScheduleLoad::getTargetInfo/$1');
    $routes->post('/schedule-load/validate-target',              'Admin\ScheduleLoad::validateTarget');
    $routes->get( '/schedule-load/get-rekap',                    'Admin\ScheduleLoad::getRekap');
     
    // Schedule Availability
    $routes->get( '/schedule-availability',                      'Admin\ScheduleAvailability::index');
    $routes->get( '/schedule-availability/edit/(:num)',          'Admin\ScheduleAvailability::edit/$1');
    $routes->post('/schedule-availability/save/(:num)',          'Admin\ScheduleAvailability::save/$1');
    $routes->post('/schedule-availability/save-settings/(:num)','Admin\ScheduleAvailability::saveSettings/$1');
    $routes->post('/schedule-availability/reset/(:num)',         'Admin\ScheduleAvailability::reset/$1');
     
    // Schedule Generator
    $routes->get( '/schedule-generator',             'Admin\ScheduleGenerator::index');
    $routes->get( '/schedule-generator/create',      'Admin\ScheduleGenerator::create');
    $routes->post('/schedule-generator/store',       'Admin\ScheduleGenerator::store');
    $routes->get( '/schedule-generator/get-periods', 'Admin\ScheduleGenerator::getPeriods');
    $routes->get('/schedule-generator/detail/(:num)', 'Admin\ScheduleGenerator::detail/$1');
    $routes->post('/schedule-generator/update/(:num)', 'Admin\ScheduleGenerator::update/$1');
    $routes->get('/schedule-generator/get-timeslots/(:num)', 'Admin\ScheduleGenerator::getTimeslots/$1');
    $routes->get('/schedule-generator/get-teacher-availability/(:num)/(:num)', 'Admin\ScheduleGenerator::getTeacherAvailability/$1/$2');
    $routes->post('/schedule-generator/save-global-max-hours', 'Admin\ScheduleGenerator::saveGlobalMaxHours');
    $routes->post('/schedule-generator/save-subject-targets', 'Admin\ScheduleLoad::saveTarget');
    $routes->get('/schedule-generator/view/(:num)',   'Admin\ScheduleGenerator::view/$1');
    $routes->post('/schedule-generator/run/(:num)',   'Admin\ScheduleGenerator::run/$1');
    $routes->get('/schedule-generator/validateSchedule/(:num)', 'Admin\ScheduleGenerator::validateSchedule/$1');
    $routes->get('/schedule-generator/get-failed-blocks/(:num)', 'Admin\ScheduleGenerator::getFailedBlocks/$1');
    $routes->post('/schedule-generator/entry-lock/(:num)/(:num)/(:alpha)', 'Admin\ScheduleGenerator::entryLock/$1/$2/$3');
    $routes->post('/schedule-generator/lock-teacher/(:num)/(:num)/(:alpha)', 'Admin\ScheduleGenerator::lockTeacher/$1/$2/$3');
    $routes->post('/schedule-generator/move-entry/(:num)', 'Admin\ScheduleGenerator::moveEntry/$1');
    $routes->get('/schedule-generator/publish/(:num)', 'Admin\ScheduleGenerator::publish/$1');
    $routes->get('/schedule-generator/reset/(:num)',   'Admin\ScheduleGenerator::reset/$1');
    $routes->get('/schedule-generator/delete/(:num)',  'Admin\ScheduleGenerator::delete/$1');
    $routes->get('/schedule-generator/export-excel/(:num)/(:segment)', 'Admin\ScheduleExport::exportExcel/$1/$2');
    $routes->get('/schedule-generator/export-pdf/(:num)/(:segment)',   'Admin\ScheduleExport::exportPdf/$1/$2');
    $routes->get('/schedule-generator/conflict-detail/(:num)', 'Admin\ScheduleGenerator::getConflictDetail/$1');
    $routes->get( '/schedule-generator/find-opportunity/(:num)',          'Admin\ScheduleGenerator::findOpportunity/$1');
    $routes->post('/schedule-generator/insert-failed/(:num)',             'Admin\ScheduleGenerator::insertFailed/$1');
    $routes->get( '/schedule-generator/find-opportunity-advanced/(:num)','Admin\ScheduleGenerator::findOpportunityAdvanced/$1');
    $routes->post('/schedule-generator/shift-one-hour/(:num)',            'Admin\ScheduleGenerator::shiftOneHourBlocks/$1');
    $routes->post('/schedule-generator/run-by-block/(:num)/(:num)',       'Admin\ScheduleGenerator::runByBlockSize/$1/$2');
    $routes->get( '/schedule-generator/check-opportunity-3jam/(:num)',   'Admin\ScheduleGenerator::checkOpportunity3Jam/$1');
    $routes->post('/schedule-generator/generate-2jam/(:num)',             'Admin\ScheduleGenerator::generateOnly2Jam/$1');
    $routes->post('/schedule-generator/repair-2jam/(:num)',               'Admin\ScheduleGenerator::repairTwoHourBlocks/$1');
    $routes->post('/schedule-generator/generate-3jam/(:num)',             'Admin\ScheduleGenerator::generateOnly3Jam/$1');
    $routes->post('/schedule-generator/generate-1jam/(:num)',             'Admin\ScheduleGenerator::generateOnly1Jam/$1');
    $routes->get( '/schedule-generator/get-3hour-opportunity/(:num)',    'Admin\ScheduleGenerator::getThreeHourOpportunity/$1');

    // Manual Schedule
    $routes->get( '/manual-schedule/input',                  'Admin\ManualSchedule::inputActive');
    $routes->get( '/manual-schedule',                         'Admin\ManualSchedule::index');
    $routes->get( '/manual-schedule/create',                  'Admin\ManualSchedule::create');
    $routes->post('/manual-schedule/store',                   'Admin\ManualSchedule::store');
    $routes->get( '/manual-schedule/edit/(:num)',             'Admin\ManualSchedule::edit/$1');
    $routes->get( '/manual-schedule/publish/(:num)',          'Admin\ManualSchedule::publish/$1');
    $routes->get( '/manual-schedule/delete/(:num)',           'Admin\ManualSchedule::delete/$1');
    $routes->post('/manual-schedule/save-entry',              'Admin\ManualSchedule::saveEntry');
    $routes->post('/manual-schedule/delete-entry',            'Admin\ManualSchedule::deleteEntry');
    $routes->get( '/manual-schedule/by-class/(:num)',         'Admin\ManualSchedule::byClass/$1');
    $routes->get( '/manual-schedule/by-teacher/(:num)',       'Admin\ManualSchedule::byTeacher/$1');
    $routes->get( '/manual-schedule/export/class/excel/(:num)', 'Admin\ManualSchedule::exportClassExcel/$1');
    $routes->get( '/manual-schedule/export/class/pdf/(:num)',   'Admin\ManualSchedule::exportClassPdf/$1');
    $routes->get( '/manual-schedule/export/class/pdf-all/(:num)', 'Admin\ManualSchedule::exportAllClassPdf/$1');
    $routes->get( '/manual-schedule/export/teacher/excel/(:num)', 'Admin\ManualSchedule::exportTeacherExcel/$1');
    $routes->get( '/manual-schedule/export/teacher/pdf/(:num)',   'Admin\ManualSchedule::exportTeacherPdf/$1');
    $routes->get( '/manual-schedule/export/teacher/pdf-all/(:num)', 'Admin\ManualSchedule::exportAllTeacherPdf/$1');
    // "no times" variations
    $routes->get( '/manual-schedule/export/class/excel-notimes/(:num)', 'Admin\ManualSchedule::exportClassExcelNoTimes/$1');
    $routes->get( '/manual-schedule/export/class/pdf-notimes/(:num)',   'Admin\ManualSchedule::exportClassPdfNoTimes/$1');
    $routes->get( '/manual-schedule/export/class/pdf-all-notimes/(:num)', 'Admin\ManualSchedule::exportAllClassPdfNoTimes/$1');
    $routes->get( '/manual-schedule/export/teacher/excel-notimes/(:num)', 'Admin\ManualSchedule::exportTeacherExcelNoTimes/$1');
    $routes->get( '/manual-schedule/export/teacher/pdf-notimes/(:num)',   'Admin\ManualSchedule::exportTeacherPdfNoTimes/$1');
    $routes->get( '/manual-schedule/export/teacher/pdf-all-notimes/(:num)', 'Admin\ManualSchedule::exportAllTeacherPdfNoTimes/$1');

    // Settings Schedule
    $routes->get( '/settings/schedule',       'Admin\SettingsController::schedule');
    $routes->post('/settings/schedule/save',  'Admin\SettingsController::saveSchedule');

    // ASC Import
    $routes->group('asc-import', ['namespace' => 'App\Controllers\Admin'], function ($routes) {
        $routes->get('/',              'AscImport::index');
        $routes->get('create',         'AscImport::create');
        $routes->post('store',         'AscImport::store');
        $routes->get('set-active/(:num)', 'AscImport::setActive/$1');
        $routes->get('set-inactive/(:num)', 'AscImport::setInactive/$1');
        $routes->get('delete/(:num)',  'AscImport::delete/$1');
        $routes->get('detail/(:num)',  'AscImport::detail/$1');
        $routes->get('edit-periods/(:num)', 'AscImport::editPeriods/$1');
        $routes->post('update-periods/(:num)', 'AscImport::updatePeriods/$1');
        $routes->post('update-metadata/(:num)', 'AscImport::updateMetadata/$1');
    });

    // User Management
    $routes->get( '/user-management',                       'Admin\UserManagement::index');
    $routes->post('/user-management/store',                 'Admin\UserManagement::store');
    $routes->post('/user-management/update/(:num)',          'Admin\UserManagement::update/$1');
    $routes->post('/user-management/reset-password/(:num)', 'Admin\UserManagement::resetPassword/$1');
    $routes->get( '/user-management/toggle-active/(:num)',  'Admin\UserManagement::toggleActive/$1');
    $routes->get( '/user-management/delete/(:num)',          'Admin\UserManagement::delete/$1');

    // ASC Schedule
    $routes->group('asc-schedule', ['namespace' => 'App\Controllers\Admin'], function ($routes) {
        $routes->get('/',              'AscSchedule::index');
        $routes->get('class',          'AscSchedule::byClass');
        $routes->get('teacher',        'AscSchedule::byTeacher');
        $routes->get('export/excel',              'AscSchedule::exportExcel');
        $routes->get('export/pdf',                'AscSchedule::exportPdf');
        $routes->get('export/class/excel',        'AscSchedule::exportClassExcel');
        $routes->get('export/class/pdf',          'AscSchedule::exportClassPdf');
        $routes->get('export/class/pdf-all',      'AscSchedule::exportAllClassPdf');
        $routes->get('export/teacher/excel',      'AscSchedule::exportTeacherExcel');
        $routes->get('export/teacher/pdf',        'AscSchedule::exportTeacherPdf');
        $routes->get('export/teacher/pdf-all',    'AscSchedule::exportAllTeacherPdf');
        // ── Export tanpa waktu ──────────────────────────────────────────
        $routes->get('export/excel-notimes',              'AscSchedule::exportExcelNoTimes');
        $routes->get('export/pdf-notimes',                'AscSchedule::exportPdfNoTimes');
        $routes->get('export/class/excel-notimes',        'AscSchedule::exportClassExcelNoTimes');
        $routes->get('export/class/pdf-notimes',          'AscSchedule::exportClassPdfNoTimes');
        $routes->get('export/class/pdf-all-notimes',      'AscSchedule::exportAllClassPdfNoTimes');
        $routes->get('export/teacher/excel-notimes',      'AscSchedule::exportTeacherExcelNoTimes');
        $routes->get('export/teacher/pdf-notimes',        'AscSchedule::exportTeacherPdfNoTimes');
        $routes->get('export/teacher/pdf-all-notimes',    'AscSchedule::exportAllTeacherPdfNoTimes');
    });

    // ASC Sync
    $routes->group('asc-sync', ['namespace' => 'App\Controllers\Admin'], function ($routes) {
        $routes->get('/', 'AscSync::index');
        $routes->get('(:num)', 'AscSync::index/$1');
        $routes->post('teacher/sync', 'AscSync::syncTeacher');
        $routes->post('teacher/sync-bulk', 'AscSync::syncTeacherBulk');
        $routes->post('teacher/auto-match', 'AscSync::autoMatchTeacher');
        $routes->post('class/sync', 'AscSync::syncClass');
        $routes->post('class/sync-bulk', 'AscSync::syncClassBulk');
        $routes->post('class/auto-match', 'AscSync::autoMatchClass');
        $routes->post('subject/sync', 'AscSync::syncSubject');
        $routes->post('subject/sync-bulk', 'AscSync::syncSubjectBulk');
        $routes->post('subject/auto-match', 'AscSync::autoMatchSubject');
        $routes->post('reset/(:num)/(:any)', 'AscSync::reset/$1/$2');
    });

    // Academic Calendar
    $routes->get('/academic-calendar', 'Admin\AcademicCalendar::index');
    $routes->get('/academic-calendar/get-events', 'Admin\AcademicCalendar::getEvents');
    $routes->post('/academic-calendar/store', 'Admin\AcademicCalendar::store');
    $routes->post('/academic-calendar/update/(:num)', 'Admin\AcademicCalendar::update/$1');
    $routes->get('/dashboard/jurnal', 'Admin\DashboardJurnal::index');
    $routes->get('/academic-calendar/delete/(:num)', 'Admin\AcademicCalendar::delete/$1');
    $routes->get('/academic-calendar/import-holidays/(:num)', 'Admin\AcademicCalendar::importHolidays/$1');
    $routes->post('/academic-calendar/category/store', 'Admin\AcademicCalendar::storeCategory');
    $routes->post('/academic-calendar/category/update/(:num)', 'Admin\AcademicCalendar::updateCategory/$1');
    $routes->get('/academic-calendar/category/delete/(:num)', 'Admin\AcademicCalendar::deleteCategory/$1');
    $routes->get('/academic-calendar/settings', 'Admin\AcademicCalendar::settings');
    $routes->post('/academic-calendar/settings/save', 'Admin\AcademicCalendar::saveSettings');
    });
    
    // Attendance QR Scan & Process routes (accessible by superadmin, admin, and operator)
    $routes->group('', ['filter' => 'auth:superadmin,admin,operator'], function ($routes) {
        $routes->get( '/attendance/qr-scan',         'Admin\AttendanceQr::scanPage');
        $routes->post('/attendance/qr-process',      'Admin\AttendanceQr::processScan');
        $routes->get( '/attendance/qr-daily-status', 'Admin\AttendanceQr::getDailyStatus');
    });

    // Attendance QR Settings routes (accessible by superadmin, admin only)
    $routes->group('', ['filter' => 'auth:superadmin,admin'], function ($routes) {
        $routes->get( '/attendance/qr-settings',     'Admin\AttendanceQr::settingsPage');
        $routes->post('/attendance/qr-settings',     'Admin\AttendanceQr::saveSettings');
    });

// ── SHARED CALENDAR PREVIEW & PRINT ROUTES (ALL ROLES) ─────────────────────
$routes->group('', ['filter' => 'auth:superadmin,admin,guru,tata_usaha'], function ($routes) {
    $routes->get('/academic-calendar/print-report/(:num)', 'Admin\AcademicCalendar::printReport/$1');
    $routes->get('/academic-calendar/print-grid/(:num)/(:alpha)', 'Admin\AcademicCalendar::printGrid/$1/$2');
    $routes->get('/academic-calendar/preview-report/(:num)', 'Admin\AcademicCalendar::previewReport/$1');
    $routes->get('/academic-calendar/preview-grid/(:num)/(:alpha)', 'Admin\AcademicCalendar::previewGrid/$1/$2');
});

// ── POINT PELANGGARAN ROUTES (ADMIN & BK) ──────────────────────────────────
$routes->group('', ['filter' => 'auth:superadmin,admin,guru'], function ($routes) {
    $routes->get('/violation-settings', 'Admin\ViolationSettings::index');
    $routes->post('/violation-settings/category/store', 'Admin\ViolationSettings::storeCategory');
    $routes->post('/violation-settings/category/update/(:num)', 'Admin\ViolationSettings::updateCategory/$1');
    $routes->get('/violation-settings/category/delete/(:num)', 'Admin\ViolationSettings::deleteCategory/$1');
    $routes->post('/violation-settings/rule/store', 'Admin\ViolationSettings::storeRule');
    $routes->post('/violation-settings/rule/update/(:num)', 'Admin\ViolationSettings::updateRule/$1');
    $routes->get('/violation-settings/rule/delete/(:num)', 'Admin\ViolationSettings::deleteRule/$1');
    $routes->post('/violation-settings/sanction/store', 'Admin\ViolationSettings::storeSanction');
    $routes->post('/violation-settings/sanction/update/(:num)', 'Admin\ViolationSettings::updateSanction/$1');
    $routes->get('/violation-settings/sanction/delete/(:num)', 'Admin\ViolationSettings::deleteSanction/$1');

    $routes->get('/bk/violations', 'Guru\ViolationController::index');
    $routes->get('/bk/violations/classroom/(:num)', 'Guru\ViolationController::classroom/$1');
    $routes->post('/bk/violations/store', 'Guru\ViolationController::store');
    $routes->get('/bk/violations/delete/(:num)', 'Guru\ViolationController::delete/$1');
    
    // Homeroom Teacher (Wali Kelas) Violation View
    $routes->get('/guru/violations-kelas', 'Guru\ViolationController::homeroomIndex');
});

// ── TABUNGAN SISWA ROUTES (ADMIN & TU) ────────────────────────────
 $routes->group('', ['filter' => 'auth:superadmin,admin,tata_usaha,guru'], function ($routes) {
    $routes->get('/tabungan', 'Admin\Tabungan::index');
    $routes->get('/tabungan/history/(:num)', 'Admin\Tabungan::history/$1');
    $routes->post('/tabungan/store', 'Admin\Tabungan::store');
    $routes->post('/tabungan/delete/(:num)', 'Admin\Tabungan::delete/$1');
    $routes->get('/tabungan/report', 'Admin\Tabungan::report');
    $routes->get('/tabungan/print-slip/(:num)', 'Admin\Tabungan::printSlip/$1');
    $routes->get('/tabungan/print-report', 'Admin\Tabungan::printReport');
    $routes->post('/tabungan/send-wa-ortu', 'Admin\Tabungan::sendWaOrtu');
    $routes->post('/tabungan/send-report', 'Admin\Tabungan::sendReport');
    $routes->get('/tabungan/detail/(:num)', 'Admin\Tabungan::detail/$1');
    $routes->get('/tabungan/print-detail/(:num)', 'Admin\Tabungan::printDetail/$1');
});

// ── SISWA PORTAL ROUTES ──────────────────────────────────────────
$routes->group('siswa', ['filter' => 'auth:siswa'], function ($routes) {
    $routes->get('dashboard', 'Siswa\StudentPortal::dashboard');
    $routes->get('profile', 'Siswa\StudentPortal::profile');
    $routes->post('profile/update', 'Siswa\StudentPortal::updateProfile');
    $routes->get('schedule', 'Siswa\StudentPortal::schedule');
    $routes->get('grades', 'Siswa\StudentPortal::grades');
    $routes->get('attendance', 'Siswa\StudentPortal::attendance');
    $routes->get('tahfidz', 'Siswa\StudentPortal::tahfidz');
    $routes->get('violations', 'Siswa\StudentPortal::violations');
    $routes->get('change-password', 'Siswa\StudentPortal::changePassword');
    $routes->post('change-password', 'Siswa\StudentPortal::changePasswordProcess');

    // Bimbingan & Konseling / Pengaduan
    $routes->get('counseling', 'Siswa\Counseling::index');
    $routes->get('counseling/create', 'Siswa\Counseling::create');
    $routes->post('counseling/store', 'Siswa\Counseling::store');
    $routes->get('counseling/chat/(:num)', 'Siswa\Counseling::chat/$1');
    $routes->post('counseling/send-message/(:num)', 'Siswa\Counseling::sendMessage/$1');
    $routes->get('counseling/get-new-messages/(:num)/(:num)', 'Siswa\Counseling::getNewMessages/$1/$2');
});

// ── KAMAD & ADMIN SHARED MONITORING ROUTES ────────────────────────
$routes->group('', ['filter' => 'auth:superadmin,admin,kamad'], function ($routes) {
    $routes->get('/admin/kbm/hari-ini', 'Admin\KbmMonitor::hariIni');
    $routes->get('/admin/kbm/rekap', 'Admin\KbmMonitor::rekap');
    $routes->get('/admin/kbm/detail/(:num)', 'Admin\KbmMonitor::detailGuru/$1');
    $routes->get('/admin/kbm/jurnal-kelas', 'Admin\KbmMonitor::jurnalKelas');
    $routes->get('/admin/kbm/jurnal-kelas/export', 'Admin\KbmMonitor::exportJurnalKelas');

    $routes->get('/admin/counseling', 'Admin\Counseling::index');
    $routes->get('/admin/counseling/export-recap', 'Admin\Counseling::exportRecap');
    $routes->get('/admin/counseling/detail/(:num)', 'Admin\Counseling::detail/$1');

    $routes->get('/admin/tahfidz', 'Admin\TahfidzAdmin::index');
    $routes->get('/admin/tahfidz/dashboard', 'Admin\TahfidzAdmin::dashboard');
    $routes->get('/admin/tahfidz/export-recap', 'Admin\TahfidzAdmin::exportRecap');
    
    // Kamad Dashboard
    $routes->get('/kamad/dashboard', 'Kamad\Dashboard::index');
});
