<?php

function emailGetEventDefinitions()
{
    return [
        'user_welcome' => [
            'title' => 'Welcome Email',
            'subject' => 'Welcome to {{app_name}}',
            'body' => '<!doctype html><html><body style="margin:0;padding:0;background:#f4f7fb;font-family:Tahoma,Arial,sans-serif;"><table width="100%" cellpadding="0" cellspacing="0" style="padding:24px;"><tr><td align="center"><table width="640" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:14px;overflow:hidden;box-shadow:0 8px 30px rgba(16,24,40,.08);"><tr><td style="background:linear-gradient(135deg,#2563eb,#1d4ed8);padding:22px;color:#fff;"><h1 style="margin:0;font-size:22px;">Welcome {{full_name}}</h1><p style="margin:10px 0 0;opacity:.95;">Your account has been successfully created.</p></td></tr><tr><td style="padding:24px;color:#1f2937;line-height:1.9;"><p style="margin:0 0 14px;">Hi {{full_name}},</p><p style="margin:0 0 14px;">Thank you for joining {{app_name}}.</p><p style="margin:0 0 14px;">Your username: <strong>{{username}}</strong></p><p style="margin:0;color:#6b7280;">Registration date: {{date}}</p></td></tr></table></td></tr></table></body></html>'
        ],
        'order_created' => [
            'title' => 'Order Created Email',
            'subject' => 'Your order has been placed - #{{order_id}}',
            'body' => '<!doctype html><html><body style="margin:0;padding:0;background:#f8fafc;font-family:Tahoma,Arial,sans-serif;"><table width="100%" cellpadding="0" cellspacing="0" style="padding:24px;"><tr><td align="center"><table width="640" cellpadding="0" cellspacing="0" style="background:#fff;border-radius:14px;overflow:hidden;border:1px solid #e5e7eb;"><tr><td style="padding:22px;background:#0f766e;color:#fff;"><h2 style="margin:0;font-size:21px;">Order received</h2></td></tr><tr><td style="padding:24px;color:#111827;line-height:1.9;"><p style="margin:0 0 14px;">Hi {{full_name}}, your order was successfully created.</p><p style="margin:0 0 8px;">Order ID: <strong>#{{order_id}}</strong></p><p style="margin:0 0 8px;">Product: <strong>{{product_name}}</strong></p><p style="margin:0 0 8px;">Quantity: <strong>{{quantity}}</strong></p><p style="margin:0 0 12px;">Total: <strong>{{total_coins}} coins</strong></p><p style="margin:0;color:#6b7280;">Date: {{date}}</p></td></tr></table></td></tr></table></body></html>'
        ],
        'order_cancelled' => [
            'title' => 'Order Cancelled Email',
            'subject' => 'Your order has been cancelled - #{{order_id}}',
            'body' => '<!doctype html><html><body style="margin:0;padding:0;background:#fff7ed;font-family:Tahoma,Arial,sans-serif;"><table width="100%" cellpadding="0" cellspacing="0" style="padding:24px;"><tr><td align="center"><table width="640" cellpadding="0" cellspacing="0" style="background:#fff;border-radius:14px;overflow:hidden;border:1px solid #fed7aa;"><tr><td style="padding:22px;background:#ea580c;color:#fff;"><h2 style="margin:0;font-size:21px;">Order cancelled</h2></td></tr><tr><td style="padding:24px;color:#111827;line-height:1.9;"><p style="margin:0 0 14px;">Hi {{full_name}}, your order has been cancelled.</p><p style="margin:0 0 8px;">Order ID: <strong>#{{order_id}}</strong></p><p style="margin:0 0 8px;">Product: <strong>{{product_name}}</strong></p><p style="margin:0 0 12px;">Refunded amount: <strong>{{total_coins}} coins</strong></p><p style="margin:0;color:#6b7280;">Please contact support if you have any questions.</p></td></tr></table></td></tr></table></body></html>'
        ],
        'purchase_success' => [
            'title' => 'Purchase Success Email',
            'subject' => 'Your purchase was successful',
            'body' => '<!doctype html><html><body style="margin:0;padding:0;background:#ecfeff;font-family:Tahoma,Arial,sans-serif;"><table width="100%" cellpadding="0" cellspacing="0" style="padding:24px;"><tr><td align="center"><table width="640" cellpadding="0" cellspacing="0" style="background:#fff;border-radius:14px;overflow:hidden;border:1px solid #a5f3fc;"><tr><td style="padding:22px;background:#0891b2;color:#fff;"><h2 style="margin:0;font-size:21px;">Purchase successful</h2></td></tr><tr><td style="padding:24px;color:#111827;line-height:1.9;"><p style="margin:0 0 14px;">Hi {{full_name}}, your purchase was successful.</p><p style="margin:0 0 8px;">Item: <strong>{{item_name}}</strong></p><p style="margin:0 0 8px;">Quantity: <strong>{{quantity}}</strong></p><p style="margin:0 0 8px;">Details: <strong>{{amount_text}}</strong></p><p style="margin:0;color:#6b7280;">Date: {{date}}</p></td></tr></table></td></tr></table></body></html>'
        ],
        'coin_purchase_pending_reminder' => [
            'title' => 'Pending coin purchase reminder (5+ min)',
            'subject' => 'Your coin purchase is still pending — {{package_name}}',
            'body' => '<!doctype html><html><body style="margin:0;padding:0;background:#f8fafc;font-family:Tahoma,Arial,sans-serif;"><table width="100%" cellpadding="0" cellspacing="0" style="padding:24px;"><tr><td align="center"><table width="640" cellpadding="0" cellspacing="0" style="background:#fff;border-radius:14px;overflow:hidden;border:1px solid #e2e8f0;"><tr><td style="padding:22px;background:linear-gradient(135deg,#7c3aed,#5b21b6);color:#fff;"><h2 style="margin:0;font-size:21px;">Still thinking?</h2><p style="margin:10px 0 0;opacity:.95;">Your coin pack is waiting in {{app_name}}</p></td></tr><tr><td style="padding:24px;color:#111827;line-height:1.9;"><p style="margin:0 0 14px;">Hi {{full_name}},</p><p style="margin:0 0 14px;">We noticed your purchase <strong>#{{purchase_id}}</strong> for <strong>{{package_name}}</strong> (<strong>{{coins}} coins</strong> — {{price}} {{currency}}) has not been completed yet.</p><p style="margin:0 0 16px;">Open the app and finish checkout whenever you are ready.</p><div style="margin:20px 0;padding:16px;background:#fef3c7;border-radius:10px;border:1px solid #fcd34d;"><p style="margin:0 0 8px;font-weight:bold;color:#92400e;">Special offer</p><p style="margin:0;font-size:14px;color:#78350f;line-height:1.7;">{{offer_cta}}</p></div><p style="margin:0;font-size:13px;color:#64748b;">Username: {{username}} · {{date}}</p></td></tr></table></td></tr></table></body></html>'
        ]
    ];
}

function emailEnsureDefaults(PDO $pdo)
{
    $smtpDefaults = [
        'email_smtp_host' => 'mail.memberx.app',
        'email_smtp_port' => '465',
        'email_smtp_secure' => 'ssl',
        'email_smtp_username' => 'no-reply@memberx.app',
        'email_smtp_password' => 'Sorena99.88@',
        'email_from_email' => 'no-reply@memberx.app',
        'email_from_name' => 'MemberX',
        'email_smtp_enabled' => '0'
    ];

    foreach ($smtpDefaults as $key => $value) {
        $stmt = $pdo->prepare("INSERT INTO app_settings (setting_key, setting_value, description) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE setting_key = setting_key");
        $stmt->execute([$key, $value, 'Email setting']);
    }

    foreach (emailGetEventDefinitions() as $eventKey => $def) {
        $enabledKey = "email_{$eventKey}_enabled";
        $subjectKey = "email_{$eventKey}_subject";
        $bodyKey = "email_{$eventKey}_body";

        $stmt = $pdo->prepare("INSERT INTO app_settings (setting_key, setting_value, description) VALUES (?, '0', ?) ON DUPLICATE KEY UPDATE setting_key = setting_key");
        $stmt->execute([$enabledKey, "Email event enabled: {$eventKey}"]);

        $stmt = $pdo->prepare("INSERT INTO app_settings (setting_key, setting_value, description) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE setting_key = setting_key");
        $stmt->execute([$subjectKey, $def['subject'], "Email event subject: {$eventKey}"]);

        $stmt = $pdo->prepare("INSERT INTO app_settings (setting_key, setting_value, description) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE setting_key = setting_key");
        $stmt->execute([$bodyKey, $def['body'], "Email event body: {$eventKey}"]);
    }
}

function emailGetSettings(PDO $pdo, array $keys)
{
    if (empty($keys)) {
        return [];
    }
    $placeholders = implode(',', array_fill(0, count($keys), '?'));
    $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM app_settings WHERE setting_key IN ($placeholders)");
    $stmt->execute($keys);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $result = [];
    foreach ($rows as $row) {
        $result[$row['setting_key']] = $row['setting_value'];
    }
    return $result;
}

function emailRenderTemplate($template, array $vars)
{
    $search = [];
    $replace = [];
    foreach ($vars as $key => $value) {
        $search[] = '{{' . $key . '}}';
        $replace[] = (string)$value;
    }
    return str_replace($search, $replace, $template);
}

function emailSmtpRead($socket, $expectedCode = null)
{
    $response = '';
    while (($line = fgets($socket, 515)) !== false) {
        $response .= $line;
        if (preg_match('/^\d{3}\s/', $line)) {
            break;
        }
    }
    if ($expectedCode !== null && strpos($response, (string)$expectedCode) !== 0) {
        throw new Exception('SMTP response mismatch: ' . trim($response));
    }
    return $response;
}

function emailSmtpWrite($socket, $command, $expectedCode)
{
    fwrite($socket, $command . "\r\n");
    return emailSmtpRead($socket, $expectedCode);
}

function emailSendRawSMTP(array $smtp, $toEmail, $subject, $htmlBody)
{
    $host = $smtp['host'];
    $port = (int)$smtp['port'];
    $secure = strtolower($smtp['secure']);
    $username = $smtp['username'];
    $password = $smtp['password'];
    $fromEmail = $smtp['from_email'];
    $fromName = $smtp['from_name'];
    $timeout = 20;

    $remote = ($secure === 'ssl' ? 'ssl://' : '') . $host . ':' . $port;
    $context = stream_context_create([
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true,
            'SNI_enabled' => true,
            'peer_name' => $host
        ]
    ]);
    $socket = stream_socket_client($remote, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $context);
    if (!$socket) {
        throw new Exception("SMTP connect failed: {$errstr} ({$errno})");
    }

    stream_set_timeout($socket, $timeout);
    emailSmtpRead($socket, 220);
    emailSmtpWrite($socket, 'EHLO memberx.app', 250);

    if ($secure === 'tls') {
        emailSmtpWrite($socket, 'STARTTLS', 220);
        $cryptoMethod = STREAM_CRYPTO_METHOD_TLS_CLIENT;
        if (defined('STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT')) {
            $cryptoMethod = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
                | STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
                | STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
            if (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT')) {
                $cryptoMethod = $cryptoMethod | STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT;
            }
        }
        if (!stream_socket_enable_crypto($socket, true, $cryptoMethod)) {
            throw new Exception('Could not enable TLS encryption');
        }
        emailSmtpWrite($socket, 'EHLO memberx.app', 250);
    }

    emailSmtpWrite($socket, 'AUTH LOGIN', 334);
    emailSmtpWrite($socket, base64_encode($username), 334);
    emailSmtpWrite($socket, base64_encode($password), 235);

    emailSmtpWrite($socket, 'MAIL FROM: <' . $fromEmail . '>', 250);
    emailSmtpWrite($socket, 'RCPT TO: <' . $toEmail . '>', 250);
    emailSmtpWrite($socket, 'DATA', 354);

    $encodedSubject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
    $headers = [];
    $headers[] = 'MIME-Version: 1.0';
    $headers[] = 'Content-Type: text/html; charset=UTF-8';
    $headers[] = 'Content-Transfer-Encoding: 8bit';
    $encodedFromName = '=?UTF-8?B?' . base64_encode($fromName) . '?=';
    $headers[] = 'From: ' . $encodedFromName . ' <' . $fromEmail . '>';
    $headers[] = 'To: <' . $toEmail . '>';
    $headers[] = 'Subject: ' . $encodedSubject;

    $message = implode("\r\n", $headers) . "\r\n\r\n" . $htmlBody . "\r\n.";
    fwrite($socket, $message . "\r\n");
    $dataResp = emailSmtpRead($socket, 250);

    emailSmtpWrite($socket, 'QUIT', 221);
    fclose($socket);
    return $dataResp;
}

function emailLog(PDO $pdo, $eventKey, $recipient, $subject, $status, $errorMessage = null, $responseRaw = null, $triggeredBy = null, array $context = [])
{
    $stmt = $pdo->prepare("
        INSERT INTO email_logs (event_key, recipient_email, subject, status, error_message, response_raw, triggered_by, context_json)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $eventKey,
        $recipient,
        $subject,
        $status,
        $errorMessage,
        $responseRaw,
        $triggeredBy,
        !empty($context) ? json_encode($context, JSON_UNESCAPED_UNICODE) : null
    ]);
}

function sendSystemEmail(PDO $pdo, $eventKey, $toEmail, array $vars = [], array $options = [])
{
    emailEnsureDefaults($pdo);
    $events = emailGetEventDefinitions();
    if (!isset($events[$eventKey])) {
        return false;
    }

    $settingKeys = [
        'email_smtp_host', 'email_smtp_port', 'email_smtp_secure', 'email_smtp_username', 'email_smtp_password',
        'email_from_email', 'email_from_name', 'email_smtp_enabled',
        "email_{$eventKey}_enabled", "email_{$eventKey}_subject", "email_{$eventKey}_body", 'app_name'
    ];
    $settings = emailGetSettings($pdo, $settingKeys);
    $force = !empty($options['force']);
    $triggeredBy = $options['triggered_by'] ?? null;
    $context = $options['context'] ?? [];

    $vars['app_name'] = $vars['app_name'] ?? ($settings['app_name'] ?? 'MemberX');
    $vars['date'] = $vars['date'] ?? date('Y/m/d H:i');

    $subjectTpl = $settings["email_{$eventKey}_subject"] ?? $events[$eventKey]['subject'];
    $bodyTpl = $settings["email_{$eventKey}_body"] ?? $events[$eventKey]['body'];
    $subject = emailRenderTemplate($subjectTpl, $vars);
    $body = emailRenderTemplate($bodyTpl, $vars);

    if (!$force) {
        if (($settings['email_smtp_enabled'] ?? '0') !== '1' || ($settings["email_{$eventKey}_enabled"] ?? '0') !== '1') {
            emailLog($pdo, $eventKey, $toEmail, $subject, 'skipped', 'Disabled by settings', null, $triggeredBy, $context);
            return false;
        }
    }

    $smtp = [
        'host' => $settings['email_smtp_host'] ?? 'mail.memberx.app',
        'port' => $settings['email_smtp_port'] ?? '465',
        'secure' => $settings['email_smtp_secure'] ?? 'ssl',
        'username' => $settings['email_smtp_username'] ?? 'no-reply@memberx.app',
        'password' => $settings['email_smtp_password'] ?? '',
        'from_email' => $settings['email_from_email'] ?? 'no-reply@memberx.app',
        'from_name' => $settings['email_from_name'] ?? 'MemberX'
    ];

    try {
        $rawResponse = emailSendRawSMTP($smtp, $toEmail, $subject, $body);
        emailLog($pdo, $eventKey, $toEmail, $subject, 'sent', null, $rawResponse, $triggeredBy, $context);
        return true;
    } catch (Exception $e) {
        emailLog($pdo, $eventKey, $toEmail, $subject, 'failed', $e->getMessage(), null, $triggeredBy, $context);
        error_log('Email send failed: ' . $e->getMessage());
        return false;
    }
}

?>
