<?php
declare(strict_types=1);
if (!defined('STORE_ROOT')) { http_response_code(403); exit; }

/**
 * Email Bridge — centralized email delivery via service node
 * SECURITY FIX: SSL verification now enabled (was disabled previously)
 */
class EmailBridge {
    public const TYPE_VERIFY = 'verify';
    public const TYPE_ORDER_CONFIRM = 'order_confirmation';
    public const TYPE_ORDER_SHIPPED = 'order_shipped';
    public const TYPE_PASSWORD_RESET = 'password_reset';
    public const TYPE_SUPPORT_REPLY = 'support_reply';

    private static ?string $cachedKey = null;

    public static function send(string $type, array $data): array {
        $hmacKey = self::loadKey();
        if (!$hmacKey) return ['ok' => false, 'error' => 'Bridge key not found'];

        // Build email with proper to/subject/html_body so the engine sends our rendered HTML
        $email = $data['email'] ?? '';
        $name = $data['name'] ?? '';
        $url = $data['url'] ?? '';

        switch ($type) {
            case self::TYPE_VERIFY:
                $subject = 'Verify your email address';
                $htmlBody = self::renderVerifyEmail($name, $url);
                break;
            case self::TYPE_PASSWORD_RESET:
                $subject = 'Reset your password';
                $htmlBody = self::renderSimpleEmail($name, 'Password Reset', 'Click the link below to reset your password:', $url, 'Reset Password');
                break;
            case self::TYPE_ORDER_CONFIRM:
                $subject = 'Order Confirmation';
                $htmlBody = self::renderSimpleEmail($name, 'Order Confirmed', 'Your order has been confirmed. Thank you for your purchase.', '', '');
                break;
            default:
                $subject = $data['subject'] ?? 'Notification';
                $htmlBody = self::renderSimpleEmail($name, $subject, $data['message'] ?? '', $url, '');
                break;
        }

        $payload = json_encode([
            'to' => $email,
            'subject' => $subject,
            'html_body' => $htmlBody,
            'from' => 'noreply@cleanearth.cc',
            'type' => $type,
            'node_id' => defined('NODE_ID') ? NODE_ID : '558201',
        ]);

        $ts = (string)time();
        $nonce = bin2hex(random_bytes(16));
        $sig = hash_hmac('sha256', $ts . '.' . $nonce . '.' . $payload, $hmacKey);

        $ch = curl_init(self::getEmailNodeUrl() . '/api/mail.php');
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'X-Bridge-Sig: ' . $sig,
                'X-Bridge-Ts: ' . $ts,
                'X-Bridge-Nonce: ' . $nonce,
                'X-Bridge-Node: ' . (defined('NODE_ID') ? NODE_ID : '558201'),
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_CONNECTTIMEOUT => 5,
            // SECURITY FIX: SSL verification enabled (was false)
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_CAINFO => '/etc/ssl/certs/ca-bundle.crt',
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlErr = curl_error($ch);
        curl_close($ch);

        if ($response === false || $httpCode !== 200) {
            $errBody = $response ?: $curlErr;
            error_log("[EMAIL_BRIDGE] Failed: HTTP {$httpCode} — {$errBody}");
            return ['ok' => false, 'error' => "HTTP {$httpCode} - {$errBody}"];
        }

        $decoded = json_decode($response, true);
        return $decoded ?: ['ok' => false, 'error' => 'Invalid response'];
    }

    private static function renderVerifyEmail(string $name, string $url): string {
        $safeName = htmlspecialchars($name ?: 'there');
        $safeUrl = htmlspecialchars($url);
        return <<<HTML
<!DOCTYPE html><html><head><meta charset="UTF-8"></head>
<body style="margin:0;padding:0;font-family:Arial,Helvetica,sans-serif;background:#f4f4f7;">
<table width="100%" cellpadding="0" cellspacing="0" style="padding:40px 0;"><tr><td align="center">
<table width="560" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:8px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.08);">
<tr><td style="background:#1a1a2e;padding:30px 40px;text-align:center;">
<h1 style="margin:0;color:#ffffff;font-size:22px;">CleanPharma</h1></td></tr>
<tr><td style="padding:40px;">
<h2 style="margin:0 0 16px;color:#1a1a2e;font-size:20px;">Verify Your Email</h2>
<p style="color:#4a5568;font-size:15px;line-height:1.6;">Hi {$safeName},</p>
<p style="color:#4a5568;font-size:15px;line-height:1.6;">Thanks for creating your account. Please click the button below to verify your email address.</p>
<p style="text-align:center;margin:32px 0;">
<a href="{$safeUrl}" style="display:inline-block;padding:14px 36px;background:#10b981;color:#ffffff;text-decoration:none;border-radius:6px;font-weight:bold;font-size:15px;">Verify Email</a></p>
<p style="color:#718096;font-size:13px;line-height:1.6;">Or copy and paste this link:<br>
<span style="color:#3182ce;word-break:break-all;">{$safeUrl}</span></p>
<hr style="border:none;border-top:1px solid #e2e8f0;margin:32px 0;">
<p style="color:#a0aec0;font-size:12px;">If you did not create an account, you can safely ignore this email.</p>
</td></tr></table></td></tr></table></body></html>
HTML;
    }

    private static function renderSimpleEmail(string $name, string $title, string $message, string $url, string $btnText): string {
        $safeName = htmlspecialchars($name ?: 'there');
        $safeTitle = htmlspecialchars($title);
        $safeMsg = htmlspecialchars($message);
        $btn = '';
        if ($url && $btnText) {
            $safeUrl = htmlspecialchars($url);
            $safeBtnText = htmlspecialchars($btnText);
            $btn = "<p style=\"text-align:center;margin:32px 0;\"><a href=\"{$safeUrl}\" style=\"display:inline-block;padding:14px 36px;background:#10b981;color:#ffffff;text-decoration:none;border-radius:6px;font-weight:bold;\">{$safeBtnText}</a></p>";
        }
        return <<<HTML
<!DOCTYPE html><html><head><meta charset="UTF-8"></head>
<body style="margin:0;padding:0;font-family:Arial,Helvetica,sans-serif;background:#f4f4f7;">
<table width="100%" cellpadding="0" cellspacing="0" style="padding:40px 0;"><tr><td align="center">
<table width="560" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:8px;overflow:hidden;">
<tr><td style="background:#1a1a2e;padding:30px 40px;text-align:center;">
<h1 style="margin:0;color:#ffffff;font-size:22px;">CleanPharma</h1></td></tr>
<tr><td style="padding:40px;">
<h2 style="margin:0 0 16px;color:#1a1a2e;">{$safeTitle}</h2>
<p style="color:#4a5568;font-size:15px;">Hi {$safeName},</p>
<p style="color:#4a5568;font-size:15px;line-height:1.6;">{$safeMsg}</p>
{$btn}
</td></tr></table></td></tr></table></body></html>
HTML;
    }

    public static function verifyUrl(string $token, string $storeDomain = ''): string {
        $base = $storeDomain ?: ($_SERVER['HTTP_HOST'] ?? 'noname');
        $proto = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        return $proto . '://' . $base . '/verify/' . urlencode($token);
    }

    private static function loadKey(): ?string {
        if (self::$cachedKey !== null) return self::$cachedKey;
        $path = PRIVATE_DIR . '/bridge_hmac.key';
        if (!file_exists($path)) {
            // Fallback: try credential store
            try {
                if (class_exists('CredentialStore')) {
                    self::$cachedKey = CredentialStore::get('bridge_hmac') ?: null;
                    return self::$cachedKey;
                }
            } catch (\Throwable $e) {}
            return null;
        }
        self::$cachedKey = trim(file_get_contents($path));
        return self::$cachedKey ?: null;
    }

    private static function getEmailNodeUrl(): string {
        try {
            $envLines = file(PRIVATE_DIR . '/.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            foreach ($envLines as $line) {
                $parts = explode('=', $line, 2);
                if (count($parts) === 2 && trim($parts[0]) === 'email_node_url') {
                    $url = trim($parts[1]);
                    if (filter_var($url, FILTER_VALIDATE_URL)) return $url;
                }
            }
        } catch (\Throwable $e) {}
        return 'http://10.88.0.2:8443';
    }
}
