<?php

namespace App\Listeners;

use Config\Services;

class AttendanceConsequenceListener
{
    public static function followUp(array $payload): void
    {
        self::handle('follow_up', $payload, 'Attendance Follow Up', 'emails/follow_up', 'info');
    }

    public static function finalWarning(array $payload): void
    {
        self::handle('final_warning', $payload, 'Final Warning: Attendance Issue', 'emails/final_warning', 'warning');
    }

    public static function dismissal(array $payload): void
    {
        self::handle('dismissal', $payload, 'Notice of Dismissal', 'emails/dismissal', 'error');
    }

    /* ------------------------------------------------------------------ */

    protected static function handle(string $type, array $payload, string $defaultSubject, string $viewName, string $logLevel): void
    {
        // Gather context
        $studentName = trim(($payload['student']['firstname'] ?? '') . ' ' . ($payload['student']['lastname'] ?? ''));
        $parentEmail = $payload['parent']['email'] ?? '';
        $parentName  = $payload['parent']['name']  ?? '';
        $teacherName = trim(($payload['teacher']['firstname'] ?? '') . ' ' . ($payload['teacher']['lastname'] ?? ''));
        $className   = $payload['class']['class_section_name'] ?? '';
        $semester    = $payload['semester']    ?? '';
        $schoolYear  = $payload['school_year'] ?? '';
        $dateYmd     = $payload['date']        ?? '';
        $dateFmt     = $dateYmd ? date('m-d-Y', strtotime($dateYmd)) : '';
        $sentAt      = $payload['now'] ?? utc_now();

        if (!$parentEmail) {
            log_message('warning', "Attendance {$type}: missing parent email for studentId " . ($payload['student_id'] ?? ''));
            return;
        }

        // Subject (allow override)
        $subject = $payload['subject'] ?? self::buildSubject($defaultSubject, $studentName, $dateFmt);

        // DATA for the template (which already extends layout/email_layout)
        $emailData = [
            'title'              => $subject,
            'student_name'       => $studentName,
            'parent_name'        => $parentName,
            'teacher_name'       => $teacherName,
            'class_section_name' => $className,
            'semester'           => $semester,
            'school_year'        => $schoolYear,
            'date_fmt'           => $dateFmt,
            'sent_at'            => $sentAt,
        ];

        // Render the template DIRECTLY (no extra wrapper; template extends layout/email_layout itself)
        $html = view($viewName, $emailData, ['saveData' => true]);

        // Try EmailService first (mirrors your enrollment handler style)
        $ok = self::sendViaEmailService($parentEmail, $subject, $html, 'attendance');

        // Fallback to CI Email if custom service not available / failed
        if (!$ok) {
            $ok = self::sendViaCiEmail($parentEmail, $subject, $html);
        }

        // In-app notification similar to enrollment flow
        $summary = self::buildInAppSummary($type, $studentName, $dateFmt);
        self::notifyUser(
            $payload['parent']['user_id'] ?? null,
            $subject,
            $summary,
            ['in_app'],
            'attendance'
        );

        // Optional: mark tracking as notified if you passed tracking_id in payload
        if (!empty($payload['tracking_id'])) {
            try {
                $tracking = model(\App\Models\AttendanceTrackingModel::class);
                $tracking->markAsNotified((int) $payload['tracking_id']);
            } catch (\Throwable $e) {
                log_message('debug', 'Attendance listener: could not update notif_counter: ' . $e->getMessage());
            }
        }

        // Log final result
        $sid = $payload['student_id'] ?? '';
        if ($ok) {
            log_message($logLevel, "Attendance {$type} email sent to {$parentEmail} (studentId: {$sid})");
        } else {
            log_message('error',   "Attendance {$type} email FAILED to {$parentEmail} (studentId: {$sid})");
        }
    }

    /* --------------------------- helpers ----------------------------- */

    protected static function buildSubject(string $base, string $studentName, string $dateFmt): string
    {
        $name = $studentName ? " — {$studentName}" : '';
        $date = $dateFmt ? " ({$dateFmt})" : '';
        return $base . $name . $date;
    }

    protected static function buildInAppSummary(string $type, string $studentName, string $dateFmt): string
    {
        $who  = $studentName ?: 'a student';
        $when = $dateFmt ? " on {$dateFmt}" : '';
        return match ($type) {
            'dismissal'     => "Dismissal notice sent for {$who}{$when}.",
            'final_warning' => "Final warning sent for {$who}{$when}.",
            default         => "Follow-up notice sent for {$who}{$when}.",
        };
    }

    /**
     * App-level EmailService (like handleEnrollmentStatusChanged). Returns true/false.
     * Expects Config\Services::emailService() or service('emailService') to be defined.
     */
    protected static function sendViaEmailService(string $to, string $subject, string $html, string $category): bool
    {
        try {
            // Prefer a custom service if available
            $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', 'sendViaEmailService failed: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * CI Email fallback
     */
    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) {
                // Push more details to the log to diagnose transport/layout issues
                $dbg = method_exists($email, 'printDebugger') ? $email->printDebugger(['headers','subject']) : 'no debugger';
                log_message('debug', 'CI Email send failed: ' . print_r($dbg, true));
            }
            return $ok;
        } catch (\Throwable $e) {
            log_message('debug', 'sendViaCiEmail exception: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * In-app notifier (mirrors your enrollment handler)
     */
    protected static function notifyUser($userId, string $title, string $message, array $channels, string $topic): void
    {
        if (empty($userId)) return;
        try {
            $notifier = function_exists('service') ? service('notifier') : null;
            if (!$notifier && method_exists(Services::class, 'notifier')) {
                $notifier = Services::notifier();
            }
            if ($notifier && method_exists($notifier, 'notifyUser')) {
                $notifier->notifyUser($userId, $title, $message, $channels, $topic);
            }
        } catch (\Throwable $e) {
            log_message('debug', 'notifyUser failed: ' . $e->getMessage());
        }
    }
}
