<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once __DIR__ . "/PHPMailer/src/Exception.php";
require_once __DIR__ . "/PHPMailer/src/PHPMailer.php";
require_once __DIR__ . "/PHPMailer/src/SMTP.php";

function sendAppEmail($to, $subject, $message)
{
    if (empty($to) || !filter_var($to, FILTER_VALIDATE_EMAIL)) {
        return ['success' => false, 'error' => 'Invalid email'];
    }

    $mail = new PHPMailer(true);

    // Capture PHPMailer debug output
    $debugLog = '';
    $mail->SMTPDebug = 2; // Verbose
    $mail->Debugoutput = function($str, $level) use (&$debugLog) {
        $debugLog .= date('Y-m-d H:i:s') . " | SMTP[$level] | $str\n";
    };

    try {
        // ------------------------------
        // SMTP Configuration
        // ------------------------------
        if (SMTP_ENABLED) {
            $mail->isSMTP();
            $mail->Host       = SMTP_HOST;
            $mail->SMTPAuth   = true;
            $mail->Username   = SMTP_USERNAME;
            $mail->Password   = SMTP_PASSWORD;
            $mail->SMTPSecure = SMTP_SECURE;
            $mail->Port       = SMTP_PORT;
        }

        // ------------------------------
        // UTF-8 Encoding Fix
        // ------------------------------
        $mail->CharSet  = 'UTF-8';
        $mail->Encoding = 'base64';

        // ------------------------------
        // Sender & Recipient
        // ------------------------------
        $mail->setFrom(EMAIL_FROM_EMAIL, EMAIL_FROM_NAME);
        $mail->addAddress($to);

        // ------------------------------
        // Email Content
        // ------------------------------
        $mail->isHTML(true); // allows HTML formatting
        $mail->Subject = $subject;
        $mail->Body    = nl2br($message);

        $mail->send();

        return [
            'success' => true,
            'debug'   => $debugLog
        ];

    } catch (Exception $e) {
        return [
            'success' => false,
            'error'   => $mail->ErrorInfo,
            'debug'   => $debugLog
        ];
    }
}
