<?php

namespace App\Commands;

use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;

class SendDailyJournalReminder extends BaseCommand
{
    protected $group       = 'Cron';
    protected $name        = 'app:send-daily-journal-reminder';
    protected $description = 'Kirim laporan/tagihan guru yang belum mengisi jurnal harian ke grup WhatsApp otomatis';
    protected $options     = [
        '-f, --force' => 'Abaikan pengecekan hari libur/Minggu dan kirim laporan secara paksa',
    ];

    public function run(array $params)
    {
        $db = \Config\Database::connect();
        
        $todayDate   = date('Y-m-d');
        $todayDayNum = (int)date('N'); // 1 = Senin, ..., 7 = Minggu

        log_message('info', "SendDailyJournalReminder: Command started. Date: {$todayDate}, Day: {$todayDayNum}");

        $force = CLI::getOption('force') !== null;
        if (!$force) {
            if (array_key_exists('force', $params) || array_key_exists('f', $params) || in_array('--force', $params) || in_array('-f', $params)) {
                $force = true;
            }
        }

        // 1. Cek Hari Libur jika tidak dipaksa (--force)
        if (!$force) {
            if ($todayDayNum === 7) { // Hari Minggu
                CLI::write("Hari ini Hari Minggu. Pengiriman dibatalkan.", 'yellow');
                return;
            }

            // Cek apakah hari Sabtu diatur libur
            $sabtuLiburRow = $db->table('calendar_settings')->where('key', 'sabtu_libur')->get()->getRowArray();
            $sabtuLibur = $sabtuLiburRow && (int)$sabtuLiburRow['value'] === 1;
            if ($todayDayNum === 6 && $sabtuLibur) {
                CLI::write("Hari ini Hari Sabtu dan diatur libur. Pengiriman dibatalkan.", 'yellow');
                return;
            }

            // Cek libur kalender akademik
            $holiday = $db->table('calendar_events ce')
                ->join('calendar_categories cc', 'cc.id = ce.category_id')
                ->where('cc.is_libur', 1)
                ->where('ce.deleted_at', null)
                ->where('ce.start_date <=', $todayDate)
                ->where('ce.end_date >=', $todayDate)
                ->countAllResults();

            if ($holiday > 0) {
                CLI::write("Hari ini adalah hari libur kalender akademik. Pengiriman dibatalkan.", 'yellow');
                log_message('info', "SendDailyJournalReminder: Canceled, today is academic holiday.");
                return;
            }
        }

        // 2. Inisialisasi WhatsappService
        $waService = new \App\Services\WhatsappService();
        if (!$waService->isConfigured()) {
            CLI::error("Whatsapp Gateway belum terkonfigurasi dengan benar di Pengaturan!");
            log_message('error', "SendDailyJournalReminder: WhatsApp Gateway belum terkonfigurasi.");
            return;
        }

        if (!$waService->isFeatureEnabled('journal')) {
            CLI::write("Fitur laporan jurnal harian via WhatsApp dinonaktifkan di Pengaturan.", 'light_blue');
            log_message('info', "SendDailyJournalReminder: Fitur laporan jurnal WhatsApp dinonaktifkan.");
            return;
        }

        $groupId = $waService->getGroupIdJournal();
        if (empty($groupId)) {
            CLI::error("ID Grup WhatsApp tujuan jurnal belum diisi di Pengaturan!");
            log_message('error', "SendDailyJournalReminder: ID Grup WhatsApp Jurnal kosong.");
            return;
        }

        // 3. Ambil Periode Akademik Aktif
        $activePeriod = $db->table('academic_periods')->where('is_active', 1)->get()->getRowArray();
        $periodId = $activePeriod ? $activePeriod['id'] : null;
        if (!$periodId) {
            CLI::error("Tidak ada periode akademik aktif. Pengiriman dibatalkan.");
            log_message('error', "SendDailyJournalReminder: Periode akademik aktif tidak ditemukan.");
            return;
        }

        // 4. Cari guru yang belum mengisi jurnal mengajar hari ini
        $guruBelum = [];
        $sourceRow = $db->table('settings')->where('setting_key', 'schedule_source')->get()->getRowArray();
        $scheduleSource = $sourceRow['setting_value'] ?? 'local';

        if ($scheduleSource === 'asc') {
            $activeImport = $db->table('asc_imports')->where('is_active', 1)->get()->getRowArray();
            if ($activeImport) {
                $guruBelumSql = "SELECT DISTINCT t.name, c.name AS classroom_name
                    FROM asc_schedules asch
                    JOIN asc_teachers at ON at.asc_id = asch.teacher_asc_id AND at.import_id = asch.import_id
                    JOIN teachers t ON t.id = at.teacher_id
                    JOIN asc_classes ac ON ac.asc_id = asch.class_asc_id AND ac.import_id = asch.import_id
                    JOIN classrooms c ON c.id = ac.classroom_id
                    WHERE t.deleted_at IS NULL
                      AND t.is_active = 1
                      AND asch.import_id = ?
                      AND asch.day_number = ?
                      AND NOT EXISTS (
                          SELECT 1 FROM teaching_journals tj
                          WHERE tj.teacher_id = t.id
                            AND tj.classroom_id = c.id
                            AND tj.meeting_date = ?
                            AND tj.deleted_at IS NULL
                            AND tj.academic_period_id = ?
                      )
                    ORDER BY t.name, c.name";
                $guruBelum = $db->query($guruBelumSql, [$activeImport['id'], $todayDayNum, $todayDate, $periodId])->getResultArray();
            }
        } else {
            $publishedSchedule = $db->table('schedules')
                ->where('academic_period_id', $periodId)
                ->where('status', 'published')
                ->where('type', $scheduleSource)
                ->get()->getRowArray();
            if ($publishedSchedule) {
                $guruBelumSql = "SELECT DISTINCT t.name, c.name AS classroom_name
                    FROM schedule_entries se
                    JOIN teachers t ON t.id = se.teacher_id
                    JOIN classrooms c ON c.id = se.classroom_id
                    WHERE t.deleted_at IS NULL
                      AND t.is_active = 1
                      AND se.schedule_id = ?
                      AND se.day = ?
                      AND NOT EXISTS (
                          SELECT 1 FROM teaching_journals tj
                          WHERE tj.teacher_id = t.id
                            AND tj.classroom_id = c.id
                            AND tj.meeting_date = ?
                            AND tj.deleted_at IS NULL
                            AND tj.academic_period_id = ?
                      )
                    ORDER BY t.name, c.name";
                $guruBelum = $db->query($guruBelumSql, [$publishedSchedule['id'], $todayDayNum, $todayDate, $periodId])->getResultArray();
            }
        }

        // Persiapan Tanggal format Indonesia
        $daysMap = [
            1 => 'Senin', 2 => 'Selasa', 3 => 'Rabu', 4 => 'Kamis', 5 => 'Jumat', 6 => 'Sabtu', 7 => 'Minggu'
        ];
        $monthsMap = [
            1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April', 5 => 'Mei', 6 => 'Juni',
            7 => 'Juli', 8 => 'Agustus', 9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
        ];
        $dayName = $daysMap[$todayDayNum] ?? '';
        $dateFormatted = date('d') . ' ' . ($monthsMap[(int)date('m')] ?? '') . ' ' . date('Y');
        $todayStringIndo = "$dayName, $dateFormatted";

        helper('url');
        $baseUrl = rtrim(base_url(), '/');

        // Susun header pesan
        $msg  = "📝 *INFORMASI JURNAL MENGAJAR HARI INI*\n";
        $msg .= "MIS DARUSSALAM ADIJAYA\n";
        $msg .= "Hari: *{$todayStringIndo}*\n";
        $msg .= "──────────────\n\n";

        if (empty($guruBelum)) {
            $msg .= "Alhamdulillah, Luar biasa! Semua guru yang mengajar hari ini telah melengkapi jurnal mengajar. ✅\n\n";
        } else {
            $msg .= "Bapak/Ibu guru berikut belum mengisi jurnal mengajar hari ini:\n\n";
            
            // Group kelas per guru agar pesan tidak terlalu berulang
            $guruMap = [];
            foreach ($guruBelum as $gb) {
                $guruMap[$gb['name']][] = $gb['classroom_name'];
            }

            foreach ($guruMap as $teacherName => $classes) {
                $msg .= "• *{$teacherName}* — belum mengisi kelas: *" . implode(', ', $classes) . "*\n";
            }
            
            $msg .= "\nMohon untuk segera dilengkapi melalui aplikasi SIMAK.\n\n";
        }

        $msg .= "──────────────\n";
        $msg .= "_Pesan dikirim otomatis dari aplikasi SIMAK - {$baseUrl}_";

        CLI::write("Mengirim tagihan jurnal ke grup: $groupId ...");
        
        // Kirim via WhatsappService ke Group ID (isGroup = true)
        $result = $waService->send($groupId, $msg, true);

        if ($result['success']) {
            CLI::write("Laporan tagihan jurnal berhasil dikirim ke grup!", 'green');
            log_message('info', "SendDailyJournalReminder: Laporan berhasil dikirim ke grup {$groupId}.");
        } else {
            CLI::error("Gagal mengirim laporan. Error: " . $result['message']);
            log_message('error', "SendDailyJournalReminder: Gagal mengirim ke grup {$groupId}. Error: " . $result['message']);
        }
    }
}
