<?php
header("Content-Type: text/html");
header("Access-Control-Allow-Origin: *");

// Include config to get mail system
require_once('config.php');

// Test email address
$TEST_EMAIL = 'sagarnandal95@gmail.com';
$TEST_NAME = 'Sagar Nandal';

echo "<h1>🚀 ZForex Mail System API Testing</h1>\n";
echo "<p>Testing mail integration with real email sending to: <strong>$TEST_EMAIL</strong></p>\n";
echo "<hr>\n";

$testResults = [];

// ==========================================
// TEST 1: Registration API Call
// ==========================================
echo "<h2>📧 Test 1: Registration API Call</h2>\n";

try {
    // Prepare registration data
    $registrationData = [
        'first_name' => 'Sagar',
        'last_name' => 'Nandal',
        'country' => 'India',
        'phone' => '+91-9876543210',
        'dob' => '1995-01-01',
        'email' => $TEST_EMAIL,
        'password' => 'TestPassword123!',
        'referral' => ''
    ];
    
    // Use cURL to call registration API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://localhost:8000/register.php');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($registrationData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    echo "<div style='background: #f0f8ff; padding: 10px; margin: 10px 0; border-left: 4px solid #007cba;'>\n";
    echo "<strong>Registration API Response (HTTP $httpCode):</strong><br>\n";
    echo "<pre>$response</pre>\n";
    echo "</div>\n";
    
    $testResults['registration'] = ['success' => $httpCode == 200, 'response' => $response];
    
} catch (Exception $e) {
    echo "<p style='color: red;'>❌ Registration test failed: " . $e->getMessage() . "</p>\n";
    $testResults['registration'] = ['success' => false, 'error' => $e->getMessage()];
}

// ==========================================
// TEST 2: Direct Mail Function Tests
// ==========================================
echo "<h2>📬 Test 2: Direct Mail Function Tests</h2>\n";

// Test Welcome Email
echo "<h3>Welcome Email Test</h3>\n";
try {
    if (function_exists('sendWelcomeEmail')) {
        $welcomeResult = sendWelcomeEmail($TEST_EMAIL, $TEST_NAME);
        echo "<div style='background: #fff3cd; padding: 10px; margin: 10px 0; border-left: 4px solid #ffc107;'>\n";
        echo "<strong>Welcome Email Result:</strong><br>\n";
        echo "<pre>" . print_r($welcomeResult, true) . "</pre>\n";
        echo "</div>\n";
        $testResults['welcome_email'] = $welcomeResult;
    } else {
        echo "<p style='color: red;'>❌ sendWelcomeEmail function not available</p>\n";
        $testResults['welcome_email'] = ['success' => false, 'error' => 'Function not available'];
    }
} catch (Exception $e) {
    echo "<p style='color: red;'>❌ Welcome email test failed: " . $e->getMessage() . "</p>\n";
    $testResults['welcome_email'] = ['success' => false, 'error' => $e->getMessage()];
}

// Test Password Reset Email
echo "<h3>Password Reset Email Test</h3>\n";
try {
    if (function_exists('sendPasswordResetEmail')) {
        $resetLink = "http://localhost:8000/reset-password?token=" . bin2hex(random_bytes(16));
        $resetResult = sendPasswordResetEmail($TEST_EMAIL, $TEST_NAME, $resetLink);
        echo "<div style='background: #f8d7da; padding: 10px; margin: 10px 0; border-left: 4px solid #dc3545;'>\n";
        echo "<strong>Password Reset Email Result:</strong><br>\n";
        echo "<pre>" . print_r($resetResult, true) . "</pre>\n";
        echo "</div>\n";
        $testResults['password_reset_email'] = $resetResult;
    } else {
        echo "<p style='color: red;'>❌ sendPasswordResetEmail function not available</p>\n";
        $testResults['password_reset_email'] = ['success' => false, 'error' => 'Function not available'];
    }
} catch (Exception $e) {
    echo "<p style='color: red;'>❌ Password reset email test failed: " . $e->getMessage() . "</p>\n";
    $testResults['password_reset_email'] = ['success' => false, 'error' => $e->getMessage()];
}

// ==========================================
// TEST 3: Mail System Direct Tests
// ==========================================
echo "<h2>🎯 Test 3: Mail System Direct Tests</h2>\n";

try {
    // Get mail system instance
    if (function_exists('getMailSystem')) {
        $mailSystem = getMailSystem();
        
        // Test KYC Approval Email
        echo "<h3>KYC Approval Email Test</h3>\n";
        $kycResult = $mailSystem->sendKYCApproved($TEST_EMAIL, $TEST_NAME);
        echo "<div style='background: #d4edda; padding: 10px; margin: 10px 0; border-left: 4px solid #28a745;'>\n";
        echo "<strong>KYC Approval Email Result:</strong><br>\n";
        echo "<pre>" . print_r($kycResult, true) . "</pre>\n";
        echo "</div>\n";
        $testResults['kyc_approval'] = $kycResult;
        
        // Test Deposit Confirmation Email
        echo "<h3>Deposit Confirmation Email Test</h3>\n";
        $depositResult = $mailSystem->sendDepositApproved($TEST_EMAIL, $TEST_NAME, 1000, 'USD', 'TXN123456');
        echo "<div style='background: #d1ecf1; padding: 10px; margin: 10px 0; border-left: 4px solid #17a2b8;'>\n";
        echo "<strong>Deposit Confirmation Email Result:</strong><br>\n";
        echo "<pre>" . print_r($depositResult, true) . "</pre>\n";
        echo "</div>\n";
        $testResults['deposit_confirmation'] = $depositResult;
        
    } else {
        echo "<p style='color: red;'>❌ getMailSystem function not available</p>\n";
        $testResults['mail_system'] = ['success' => false, 'error' => 'getMailSystem function not available'];
    }
} catch (Exception $e) {
    echo "<p style='color: red;'>❌ Mail system test failed: " . $e->getMessage() . "</p>\n";
    $testResults['mail_system'] = ['success' => false, 'error' => $e->getMessage()];
}

// ==========================================
// TEST SUMMARY
// ==========================================
echo "<hr>\n";
echo "<h2>📊 Test Summary</h2>\n";

$totalTests = count($testResults);
$successfulTests = 0;

foreach ($testResults as $result) {
    if (isset($result['success']) && $result['success']) {
        $successfulTests++;
    }
}

echo "<div style='background: #e7f3ff; padding: 15px; margin: 20px 0; border-radius: 5px;'>\n";
echo "<h3>🎯 Final Results</h3>\n";
echo "<p><strong>Total Tests:</strong> $totalTests</p>\n";
echo "<p><strong>Successful:</strong> $successfulTests</p>\n";
echo "<p><strong>Failed:</strong> " . ($totalTests - $successfulTests) . "</p>\n";
echo "<p><strong>Success Rate:</strong> " . round(($successfulTests / $totalTests) * 100, 2) . "%</p>\n";
echo "</div>\n";

echo "<div style='background: #fff3cd; padding: 15px; margin: 20px 0; border-radius: 5px;'>\n";
echo "<h3>📧 Email Delivery Instructions</h3>\n";
echo "<p>Please check the email inbox for <strong>$TEST_EMAIL</strong> to verify that emails were delivered successfully.</p>\n";
echo "</div>\n";

echo "<h3>🔍 Detailed Test Results:</h3>\n";
echo "<pre>" . print_r($testResults, true) . "</pre>\n";
?>