<?php
/**
 * Email sending via SMTP (PHPMailer)
 * Requires: config/app.php, config/smtp.php; Composer + phpmailer/phpmailer
 */

function getSmtpConfig() {
    static $config = null;
    if ($config === null) {
        if (!defined('BASE_PATH')) {
            require_once __DIR__ . '/../config/app.php';
        }
        $fileConfig = require __DIR__ . '/../config/smtp.php';
        if (!function_exists('getSettingsByPrefix')) {
            require_once __DIR__ . '/settings.php';
        }
        $db = getSettingsByPrefix('smtp_');
        if (!empty($db)) {
            $config = array_merge($fileConfig, [
                'enabled'    => !empty($db['enabled']),
                'host'       => $db['host'] ?? $fileConfig['host'],
                'port'       => $db['port'] ?? $fileConfig['port'],
                'encryption' => $db['encryption'] ?? $fileConfig['encryption'],
                'username'   => $db['username'] ?? $fileConfig['username'],
                'password'   => $db['password'] ?? $fileConfig['password'],
                'from_email' => $db['from_email'] ?? $fileConfig['from_email'],
                'from_name'  => $db['from_name'] ?? $fileConfig['from_name'],
            ]);
        } else {
            $config = $fileConfig;
        }
    }
    return $config;
}

/**
 * Wrap receipt/offering email body in a branded HTML layout (header, container, footer).
 * Uses table-based layout and inline styles for email client compatibility.
 *
 * @param string $contentHtml Main message HTML (e.g. paragraph with nl2br text)
 * @param string $churchName  Church/organization name for header and footer
 * @return string Full HTML document
 */
function wrapReceiptEmailHtml($contentHtml, $churchName) {
    $name = htmlspecialchars($churchName, ENT_QUOTES, 'UTF-8');
    return '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Receipt</title>
</head>
<body style="margin:0; padding:0; background-color:#f1f5f9; font-family: Arial, Helvetica, sans-serif; font-size: 16px; line-height: 1.5; color: #1e293b;">
    <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f1f5f9; padding: 24px 16px;">
        <tr>
            <td align="center">
                <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width: 560px; background-color:#ffffff; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.08); overflow: hidden;">
                    <tr>
                        <td style="background-color: #1e3a5f; color: #ffffff; padding: 24px 28px; text-align: center;">
                            <p style="margin:0; font-size: 18px; font-weight: bold; letter-spacing: 0.02em;">' . $name . '</p>
                            <p style="margin: 6px 0 0 0; font-size: 13px; color: #94a3b8;">Offering receipt</p>
                        </td>
                    </tr>
                    <tr>
                        <td style="padding: 28px 28px 24px; color: #334155;">
                            ' . $contentHtml . '
                        </td>
                    </tr>
                    <tr>
                        <td style="padding: 20px 28px 24px; border-top: 1px solid #e2e8f0; background-color: #f8fafc; font-size: 14px; color: #64748b; text-align: center;">
                            <p style="margin:0 0 4px 0;">Thank you for your generosity.</p>
                            <p style="margin: 12px 0 0 0; font-style: italic; color: #475569; line-height: 1.5;">&ldquo;And praise be to God Most High,<br>who delivered your enemies into your hand.&rdquo;<br>Then Abram gave him a tenth of everything.</p>
                            <p style="margin: 4px 0 0 0; font-size: 13px; font-style: normal; color: #64748b;">Gen. 14:20</p>
                            <p style="margin: 12px 0 0 0; font-weight: 600; color: #475569;">' . $name . '</p>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>
</html>';
}

/**
 * Send an email via SMTP.
 *
 * @param string $to      Recipient email
 * @param string $subject Subject line
 * @param string $bodyHtml HTML body (preferred)
 * @param string|null $bodyText Plain-text body (optional)
 * @return array ['sent' => bool, 'error' => string|null]
 */
function sendMail($to, $subject, $bodyHtml, $bodyText = null) {
    $cfg = getSmtpConfig();
    if (empty($cfg['enabled'])) {
        return ['sent' => false, 'error' => 'SMTP is not configured or disabled.'];
    }

    // Avoid Composer platform_check fatal on older PHP versions.
    // If your vendor/ dependencies require a newer PHP (e.g. >= 8.4), return a friendly error instead of a blank page.
    if (defined('PHP_VERSION_ID') && PHP_VERSION_ID < 80400) {
        return ['sent' => false, 'error' => 'Email sending is unavailable on this server PHP version. Upgrade PHP to 8.4+ or disable birthday email.'];
    }

    $autoload = __DIR__ . '/../vendor/autoload.php';
    if (!file_exists($autoload)) {
        return ['sent' => false, 'error' => 'Composer dependencies not installed. Run: composer install'];
    }
    require_once $autoload;

    $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = $cfg['host'];
        $mail->SMTPAuth   = true;
        $mail->Username   = $cfg['username'];
        $mail->Password   = $cfg['password'];
        $mail->Port = (int) $cfg['port'];
        $mail->Timeout    = 3; // 3 second timeout to prevent blocking
        if (!empty($cfg['encryption'])) {
            $mail->SMTPSecure = $cfg['encryption'];
        } else {
            $mail->SMTPSecure = false;
            $mail->SMTPAutoTLS = false;
        }
        $mail->CharSet = 'UTF-8';

        $mail->setFrom($cfg['from_email'], $cfg['from_name'] ?? '');
        $mail->addAddress($to);
        $mail->Subject = $subject;
        $mail->isHTML(true);
        $mail->Body    = $bodyHtml;
        if ($bodyText !== null && $bodyText !== '') {
            $mail->AltBody = $bodyText;
        }

        $mail->send();
        return ['sent' => true, 'error' => null];
    } catch (\PHPMailer\PHPMailer\Exception $e) {
        return ['sent' => false, 'error' => $e->getMessage()];
    }
}
