<?php
/**
 * EMAIL SYSTEM TEST SCRIPT
 * 
 * This script tests all email templates and SMTP functionality
 * Run this AFTER configuring SMTP in the admin panel
 * 
 * Usage: http://localhost:8000/api/test_email_system.php?email=YOUR_EMAIL
 */

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/email_helper.php';

header('Content-Type: application/json');

// Get test email from query parameter
$testEmail = $_GET['email'] ?? '';

if (empty($testEmail)) {
    echo json_encode([
        'success' => false,
        'error' => 'Please provide email parameter: ?email=your@email.com'
    ]);
    exit;
}

if (!filter_var($testEmail, FILTER_VALIDATE_EMAIL)) {
    echo json_encode([
        'success' => false,
        'error' => 'Invalid email address format'
    ]);
    exit;
}

$conn = getDbConnection();
$results = [];

echo "<!DOCTYPE html>
<html>
<head>
    <title>Email System Test Results</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif;
            background: #1a1a2e;
            color: #fff;
            padding: 40px;
            line-height: 1.6;
        }
        .container {
            max-width: 900px;
            margin: 0 auto;
            background: #16213e;
            padding: 40px;
            border-radius: 16px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.3);
        }
        h1 {
            color: #E43D30;
            margin-bottom: 30px;
        }
        .test-section {
            background: #0f1624;
            padding: 20px;
            margin: 20px 0;
            border-radius: 8px;
            border-left: 4px solid #E43D30;
        }
        .success {
            color: #10b981;
            font-weight: bold;
        }
        .error {
            color: #ef4444;
            font-weight: bold;
        }
        .info {
            color: #60a5fa;
        }
        pre {
            background: #000;
            padding: 15px;
            border-radius: 8px;
            overflow-x: auto;
            font-size: 12px;
        }
        .template-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin: 20px 0;
        }
        .template-card {
            background: #0f1624;
            padding: 20px;
            border-radius: 8px;
            border: 1px solid #2d3748;
        }
        .template-card h3 {
            margin-top: 0;
            color: #E43D30;
        }
        .badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
            margin-left: 10px;
        }
        .badge-success {
            background: #10b981;
            color: white;
        }
        .badge-error {
            background: #ef4444;
            color: white;
        }
    </style>
</head>
<body>
    <div class='container'>
        <h1>📧 Email System Test Results</h1>
        <p class='info'>Testing email delivery to: <strong>{$testEmail}</strong></p>
        <p style='color: #999; font-size: 14px;'>Started at: " . date('Y-m-d H:i:s') . "</p>
        <hr style='border-color: #2d3748; margin: 30px 0;'>
";

// Test 1: Check SMTP Configuration
echo "<div class='test-section'>
        <h2>🔧 Test 1: SMTP Configuration</h2>";

$smtpConfig = getEmailConfig($conn, 'smtp_config');
if ($smtpConfig && $smtpConfig['enabled']) {
    echo "<p class='success'>✅ SMTP is enabled</p>";
    echo "<p>Host: {$smtpConfig['host']}</p>";
    echo "<p>Port: {$smtpConfig['port']}</p>";
    echo "<p>Encryption: " . strtoupper($smtpConfig['encryption']) . "</p>";
    echo "<p>From: {$smtpConfig['fromName']} &lt;{$smtpConfig['fromEmail']}&gt;</p>";
} else {
    echo "<p class='error'>❌ SMTP is not configured or disabled</p>";
    echo "<p>Please configure SMTP in the admin panel first.</p>";
    echo "</div></div></body></html>";
    exit;
}
echo "</div>";

// Test 2: Check Email Settings
echo "<div class='test-section'>
        <h2>⚙️ Test 2: Email Settings</h2>";

$emailSettings = getEmailConfig($conn, 'email_settings');
if ($emailSettings) {
    echo "<p class='success'>✅ Email settings configured</p>";
    echo "<ul>";
    echo "<li>Verification Required: " . ($emailSettings['verificationRequired'] ? 'Yes' : 'No') . "</li>";
    echo "<li>Verification Expiry: {$emailSettings['verificationExpiry']} hours</li>";
    echo "<li>Send Welcome Email: " . ($emailSettings['sendWelcomeEmail'] ? 'Yes' : 'No') . "</li>";
    echo "<li>Send Deposit Notifications: " . ($emailSettings['sendDepositNotifications'] ? 'Yes' : 'No') . "</li>";
    echo "<li>Send Withdrawal Notifications: " . ($emailSettings['sendWithdrawalNotifications'] ? 'Yes' : 'No') . "</li>";
    echo "<li>Send KYC Notifications: " . ($emailSettings['sendKycNotifications'] ? 'Yes' : 'No') . "</li>";
    echo "<li>Send Ticket Notifications: " . ($emailSettings['sendTicketNotifications'] ? 'Yes' : 'No') . "</li>";
    echo "</ul>";
} else {
    echo "<p class='error'>❌ Email settings not found</p>";
}
echo "</div>";

// Test 3: Check All Templates
echo "<div class='test-section'>
        <h2>📝 Test 3: Email Templates</h2>";

$templates = [
    'verification',
    'welcome',
    'depositRequest',
    'depositApproved',
    'withdrawalRequest',
    'withdrawalApproved',
    'kycApproved',
    'kycRejected',
    'ticketReply'
];

$templateResults = [];
foreach ($templates as $template) {
    $config = getEmailConfig($conn, "template_{$template}");
    $templateResults[$template] = $config ? 'configured' : 'missing';
}

echo "<div class='template-grid'>";
foreach ($templateResults as $template => $status) {
    $icon = $status === 'configured' ? '✅' : '❌';
    $badge = $status === 'configured' ? 
        "<span class='badge badge-success'>Configured</span>" : 
        "<span class='badge badge-error'>Missing</span>";
    
    echo "<div class='template-card'>
            <h3>{$icon} " . ucfirst($template) . "</h3>
            {$badge}
          </div>";
}
echo "</div>";

$configuredCount = count(array_filter($templateResults, fn($s) => $s === 'configured'));
echo "<p><strong>Result:</strong> {$configuredCount} / " . count($templates) . " templates configured</p>";

echo "</div>";

// Test 4: Send Test Emails
echo "<div class='test-section'>
        <h2>📤 Test 4: Sending Test Emails</h2>
        <p class='info'>Sending test emails to {$testEmail}...</p>";

$testResults = [];

// Test 4.1: Verification Email
echo "<h3>📧 Verification Email</h3>";
try {
    $result = sendEmail($conn, $testEmail, 'verification', [
        'user_name' => 'Test User',
        'verification_link' => 'http://localhost:5173/verify-email?token=test123',
        'expiry_hours' => 24
    ]);
    if ($result) {
        echo "<p class='success'>✅ Verification email sent successfully</p>";
        $testResults['verification'] = true;
    } else {
        echo "<p class='error'>❌ Failed to send verification email</p>";
        $testResults['verification'] = false;
    }
} catch (Exception $e) {
    echo "<p class='error'>❌ Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    $testResults['verification'] = false;
}

// Test 4.2: Welcome Email
echo "<h3>📧 Welcome Email</h3>";
try {
    $result = sendEmail($conn, $testEmail, 'welcome', [
        'user_name' => 'Test User',
        'login_link' => 'http://localhost:5173/login',
        'support_email' => 'support@vizventure.com'
    ]);
    if ($result) {
        echo "<p class='success'>✅ Welcome email sent successfully</p>";
        $testResults['welcome'] = true;
    } else {
        echo "<p class='error'>❌ Failed to send welcome email</p>";
        $testResults['welcome'] = false;
    }
} catch (Exception $e) {
    echo "<p class='error'>❌ Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    $testResults['welcome'] = false;
}

// Test 4.3: Deposit Request Email
echo "<h3>📧 Deposit Request Email</h3>";
try {
    $result = sendEmail($conn, $testEmail, 'depositRequest', [
        'user_name' => 'Test User',
        'amount' => '$1,000.00',
        'method' => 'Bank Transfer',
        'date' => date('Y-m-d H:i:s')
    ]);
    if ($result) {
        echo "<p class='success'>✅ Deposit request email sent successfully</p>";
        $testResults['depositRequest'] = true;
    } else {
        echo "<p class='error'>❌ Failed to send deposit request email</p>";
        $testResults['depositRequest'] = false;
    }
} catch (Exception $e) {
    echo "<p class='error'>❌ Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    $testResults['depositRequest'] = false;
}

// Test 4.4: Deposit Approved Email
echo "<h3>📧 Deposit Approved Email</h3>";
try {
    $result = sendEmail($conn, $testEmail, 'depositApproved', [
        'user_name' => 'Test User',
        'amount' => '$1,000.00',
        'method' => 'Bank Transfer',
        'balance' => '$5,000.00'
    ]);
    if ($result) {
        echo "<p class='success'>✅ Deposit approved email sent successfully</p>";
        $testResults['depositApproved'] = true;
    } else {
        echo "<p class='error'>❌ Failed to send deposit approved email</p>";
        $testResults['depositApproved'] = false;
    }
} catch (Exception $e) {
    echo "<p class='error'>❌ Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    $testResults['depositApproved'] = false;
}

// Test 4.5: KYC Approved Email
echo "<h3>📧 KYC Approved Email</h3>";
try {
    $result = sendEmail($conn, $testEmail, 'kycApproved', [
        'user_name' => 'Test User',
        'verification_level' => 'Level 2 - Full Verification'
    ]);
    if ($result) {
        echo "<p class='success'>✅ KYC approved email sent successfully</p>";
        $testResults['kycApproved'] = true;
    } else {
        echo "<p class='error'>❌ Failed to send KYC approved email</p>";
        $testResults['kycApproved'] = false;
    }
} catch (Exception $e) {
    echo "<p class='error'>❌ Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    $testResults['kycApproved'] = false;
}

// Test 4.6: Ticket Reply Email
echo "<h3>📧 Ticket Reply Email</h3>";
try {
    $result = sendEmail($conn, $testEmail, 'ticketReply', [
        'user_name' => 'Test User',
        'ticket_id' => '12345',
        'reply' => 'Thank you for contacting support. We have reviewed your request and will process it within 24 hours.',
        'ticket_link' => 'http://localhost:5173/dashboard/tickets/12345'
    ]);
    if ($result) {
        echo "<p class='success'>✅ Ticket reply email sent successfully</p>";
        $testResults['ticketReply'] = true;
    } else {
        echo "<p class='error'>❌ Failed to send ticket reply email</p>";
        $testResults['ticketReply'] = false;
    }
} catch (Exception $e) {
    echo "<p class='error'>❌ Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    $testResults['ticketReply'] = false;
}

echo "</div>";

// Final Summary
$successCount = count(array_filter($testResults, fn($r) => $r === true));
$totalTests = count($testResults);

echo "<div class='test-section'>
        <h2>📊 Test Summary</h2>";

if ($successCount === $totalTests) {
    echo "<p class='success' style='font-size: 20px;'>🎉 All tests passed! ({$successCount}/{$totalTests})</p>";
    echo "<p>All email templates are working correctly. Check your inbox at <strong>{$testEmail}</strong></p>";
    echo "<p style='color: #999;'>Note: Emails might take a few minutes to arrive. Check spam folder if needed.</p>";
} else {
    echo "<p class='error' style='font-size: 20px;'>⚠️ Some tests failed ({$successCount}/{$totalTests} passed)</p>";
    echo "<p>Please check the error messages above and verify your SMTP configuration.</p>";
}

echo "<h3>Detailed Results:</h3>";
echo "<ul>";
foreach ($testResults as $template => $result) {
    $status = $result ? "<span class='success'>✅ Passed</span>" : "<span class='error'>❌ Failed</span>";
    echo "<li><strong>" . ucfirst($template) . ":</strong> {$status}</li>";
}
echo "</ul>";

echo "</div>";

echo "<div style='margin-top: 40px; padding: 20px; background: #0f1624; border-radius: 8px;'>
        <h3>🔍 What to Check Next:</h3>
        <ol>
            <li>Check your email inbox: <strong>{$testEmail}</strong></li>
            <li>Look in spam/junk folder if emails don't appear in inbox</li>
            <li>Verify each email has the correct content and formatting</li>
            <li>Test variable substitution worked correctly</li>
            <li>Confirm all images and buttons display properly</li>
            <li>Click links in emails to verify they work</li>
        </ol>
        <p style='color: #999; font-size: 14px; margin-top: 20px;'>
            Completed at: " . date('Y-m-d H:i:s') . "
        </p>
      </div>";

echo "</div></body></html>";

$conn = null;
?>
