<?php
// /edenrms/includes/email_helper.php
declare(strict_types=1);

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

function rms_email_require_phpmailer(): void
{
    $composer = __DIR__ . '/../vendor/autoload.php';

    if (is_file($composer)) {
        require_once $composer;
        return;
    }

    $base = __DIR__ . '/../vendor/PHPMailer/src/';

    require_once $base . 'Exception.php';
    require_once $base . 'PHPMailer.php';
    require_once $base . 'SMTP.php';
}

function rms_send_email(string $to, string $subject, string $html, string $toName = ''): array
{
    rms_email_require_phpmailer();

    $mail = new PHPMailer(true);

    try {
        /*
         * CHANGE THESE SMTP SETTINGS
         * Use your hosting/cPanel email SMTP details.
         */
        $smtpHost = 'mail.edencampus.lk';
$smtpPort = 465;
        $smtpUser = 'nabrees@edencampus.lk';
        $smtpPass = '9Yv[5k-PFr=lLIL2';
        $fromEmail = 'nabrees@edencampus.lk';
        $fromName = 'Eden Campus RMS';

        $mail->isSMTP();
        $mail->Host       = $smtpHost;
        $mail->SMTPAuth   = true;
        $mail->Username   = $smtpUser;
        $mail->Password   = $smtpPass;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port       = $smtpPort;

        $mail->CharSet = 'UTF-8';
        $mail->setFrom($fromEmail, $fromName);
        $mail->addAddress($to, $toName);

        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $html;
        $mail->AltBody = strip_tags(str_replace(['<br>', '<br/>', '<br />'], "\n", $html));

        $mail->send();

        return [
            'ok' => true,
            'message' => 'Email sent successfully'
        ];
    } catch (Throwable $e) {
        error_log('RMS Email Error: ' . $e->getMessage());

        return [
            'ok' => false,
            'message' => $e->getMessage()
        ];
    }
}
if (!function_exists('rms_email_table_exists')) {
    function rms_email_table_exists(mysqli $db, string $table): bool
    {
        $table = $db->real_escape_string($table);
        $rs = $db->query("SHOW TABLES LIKE '{$table}'");
        return $rs && $rs->num_rows > 0;
    }
}

if (!function_exists('rms_render_email_template')) {
    function rms_render_email_template(string $text, array $data): string
    {
        foreach ($data as $key => $value) {
            $text = str_replace('{{' . $key . '}}', (string)$value, $text);
        }

        return $text;
    }
}

if (!function_exists('rms_log_email')) {
    function rms_log_email(
        mysqli $db,
        string $templateKey,
        ?int $studentId,
        ?int $paymentId,
        string $emailTo,
        string $subject,
        string $status,
        string $errorMessage = ''
    ): void {
        if (!rms_email_table_exists($db, 'rms_email_logs')) {
            return;
        }

        $sentAt = $status === 'sent' ? date('Y-m-d H:i:s') : null;

        $st = $db->prepare("
            INSERT INTO rms_email_logs
            (template_key, student_id, payment_id, email_to, subject, status, error_message, sent_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");

        if (!$st) return;

        $st->bind_param(
            'siisssss',
            $templateKey,
            $studentId,
            $paymentId,
            $emailTo,
            $subject,
            $status,
            $errorMessage,
            $sentAt
        );

        $st->execute();
        $st->close();
    }
}

if (!function_exists('rms_send_template_email')) {
    function rms_send_template_email(
        mysqli $db,
        string $templateKey,
        string $emailTo,
        array $data = [],
        ?int $studentId = null,
        ?int $paymentId = null,
        string $toName = ''
    ): array {
        if (!rms_email_table_exists($db, 'rms_email_templates')) {
            return [
                'ok' => false,
                'skipped' => true,
                'message' => 'Email templates table not found.'
            ];
        }

        if (!filter_var($emailTo, FILTER_VALIDATE_EMAIL)) {
            rms_log_email($db, $templateKey, $studentId, $paymentId, $emailTo, '', 'skipped', 'Invalid email address');

            return [
                'ok' => false,
                'skipped' => true,
                'message' => 'Invalid email address.'
            ];
        }

        $st = $db->prepare("
            SELECT template_key, subject, body_html, is_enabled
            FROM rms_email_templates
            WHERE template_key = ?
            LIMIT 1
        ");

        if (!$st) {
            return [
                'ok' => false,
                'message' => $db->error
            ];
        }

        $st->bind_param('s', $templateKey);
        $st->execute();
        $tpl = $st->get_result()->fetch_assoc();
        $st->close();

        if (!$tpl) {
            return [
                'ok' => false,
                'skipped' => true,
                'message' => 'Template not found.'
            ];
        }

        $subject = rms_render_email_template((string)$tpl['subject'], $data);
        $html    = rms_render_email_template((string)$tpl['body_html'], $data);

        if ((int)$tpl['is_enabled'] !== 1) {
            rms_log_email($db, $templateKey, $studentId, $paymentId, $emailTo, $subject, 'skipped', 'Template disabled');

            return [
                'ok' => true,
                'skipped' => true,
                'message' => 'Template disabled. Email skipped.'
            ];
        }

        $result = rms_send_email($emailTo, $subject, $html, $toName);

        if (!empty($result['ok'])) {
            rms_log_email($db, $templateKey, $studentId, $paymentId, $emailTo, $subject, 'sent');
        } else {
            rms_log_email($db, $templateKey, $studentId, $paymentId, $emailTo, $subject, 'failed', (string)($result['message'] ?? 'Email failed'));
        }

        return $result;
    }
}