<?php

namespace App\Listeners;

use Config\Services;

class BelowSixtyEmailListener
{
    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'] ?? '');
        $scores = is_array($payload['scores'] ?? null) ? $payload['scores'] : [];
        $comment = (string)($payload['comment'] ?? '');

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

        // Fetch guardian emails
        $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', 'Below60Email: 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 = 'Student Performance Alert';
            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,
            'semester'           => $semester,
            'school_year'        => $schoolYear,
            'scores'             => $scores,
            'comment'            => $comment,
            'sent_at'            => utc_now(),
        ];

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

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

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

    protected static function sendViaEmailService(string $to, string $subject, string $html, string $category): 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, $category);
        } catch (\Throwable $e) {
            log_message('debug', 'Below60Email 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', 'Below60Email CI send failed: ' . print_r($dbg, true));
            }
            return $ok;
        } catch (\Throwable $e) {
            log_message('debug', 'Below60Email sendViaCiEmail exception: ' . $e->getMessage());
            return false;
        }
    }
}
