<?php

namespace App\Listeners;

use Config\Services;

class DecisionEmailListener
{
    public static function handle(array $payload): void
    {
        $studentId   = (int)($payload['student_id'] ?? 0);
        $studentName = (string)($payload['student_name'] ?? '');
        $classSection= (string)($payload['class_section_name'] ?? '');
        $semester    = (string)($payload['semester'] ?? '');
        $schoolYear  = (string)($payload['school_year'] ?? '');
        $decision     = (string)($payload['decision'] ?? '');
        $notes        = (string)($payload['notes'] ?? '');
        $scores       = is_array($payload['scores'] ?? null) ? $payload['scores'] : [];
        $allSemesters = is_array($payload['all_semesters'] ?? null) ? $payload['all_semesters'] : [];

        if ($studentId <= 0) {
            log_message('warning', 'DecisionEmail: missing student_id');
            return;
        }

        $db = \Config\Database::connect();
        $rows = $db->query(
            "SELECT u.firstname, u.lastname, u.email, fg.is_primary
               FROM family_students fs
               JOIN family_guardians fg ON fg.family_id = fs.family_id
               JOIN users u ON u.id = fg.user_id
              WHERE fs.student_id = ?
                AND fg.receive_emails = 1
                AND u.email IS NOT NULL AND u.email != ''
              ORDER BY fg.is_primary DESC, u.lastname, u.firstname",
            [$studentId]
        )->getResultArray();

        if (empty($rows)) {
            log_message('warning', 'DecisionEmail: no guardian emails for student_id=' . $studentId);
            return;
        }

        $emails = [];
        foreach ($rows as $row) {
            $em = trim((string)($row['email'] ?? ''));
            if ($em !== '') $emails[$em] = true;
        }
        $emails = array_keys($emails);

        $primary    = $rows[0] ?? [];
        $parentName = trim((string)($primary['firstname'] ?? '') . ' ' . (string)($primary['lastname'] ?? ''));

        $subject = (string)($payload['subject'] ?? '');
        if ($subject === '') {
            $subject = 'Academic Decision';
            if ($studentName !== '') $subject .= ' — ' . $studentName;
            if ($semester !== '' || $schoolYear !== '') {
                $subject .= ' (' . trim($semester . ' ' . $schoolYear) . ')';
            }
        }

        $emailData = [
            'title'              => $subject,
            'parent_name'        => $parentName !== '' ? $parentName : 'Parent/Guardian',
            'student_name'       => $studentName !== '' ? $studentName : 'your student',
            'class_section_name' => $classSection,
            'school_year'        => $schoolYear,
            'decision'           => $decision,
            'notes'              => $notes,
            'scores'             => $scores,
            'all_semesters'      => $allSemesters,
        ];

        $html = trim((string)($payload['html'] ?? ''));
        if ($html === '') {
            $html = view('emails/below_sixty_decision', $emailData, ['saveData' => true]);
        }

        $okAny = false;
        foreach ($emails as $to) {
            $ok = self::sendViaEmailService($to, $subject, $html);
            if (!$ok) {
                $ok = self::sendViaCiEmail($to, $subject, $html);
            }
            $okAny = $okAny || $ok;
        }

        if ($okAny) {
            log_message('info', 'DecisionEmail: sent for student_id=' . $studentId);
        } else {
            log_message('error', 'DecisionEmail: failed for student_id=' . $studentId);
        }
    }

    protected static function sendViaEmailService(string $to, string $subject, string $html): bool
    {
        try {
            $svc = function_exists('service') ? service('emailService') : null;
            if (!$svc && method_exists(Services::class, 'emailService')) {
                $svc = Services::emailService();
            }
            if (!$svc) return false;
            return (bool)$svc->send($to, $subject, $html, 'general');
        } catch (\Throwable $e) {
            log_message('debug', 'DecisionEmail sendViaEmailService failed: ' . $e->getMessage());
            return false;
        }
    }

    protected static function sendViaCiEmail(string $to, string $subject, string $html): bool
    {
        try {
            $email = Services::email();
            $cfg   = config('Email');
            $fromEmail = $cfg->fromEmail ?? $cfg->SMTPUser ?? 'no-reply@example.com';
            $fromName  = $cfg->fromName  ?? 'Al Rahma Sunday School';

            $email->setTo($to);
            $email->setFrom($fromEmail, $fromName);
            $email->setSubject($subject);
            $email->setMessage($html);
            $email->setMailType('html');
            $ok = $email->send();
            if (!$ok) {
                $dbg = method_exists($email, 'printDebugger') ? $email->printDebugger(['headers', 'subject']) : 'no debugger';
                log_message('debug', 'DecisionEmail CI send failed: ' . print_r($dbg, true));
            }
            return $ok;
        } catch (\Throwable $e) {
            log_message('debug', 'DecisionEmail sendViaCiEmail exception: ' . $e->getMessage());
            return false;
        }
    }
}
