<?php
/**
 * Email Integration Test Script
 * Tests all 22 email templates and integration functionality
 * 
 * Usage: Run this script from command line or browser to test email functionality
 * Make sure to update the test email address below before running
 */

// Include the unified configuration
include_once __DIR__ . '/unified_config.php';

// Test configuration
$TEST_EMAIL = 'test@example.com'; // Change this to your test email
$TEST_NAME = 'Test User';

echo "<h1>ZForex Email Integration Test</h1>\n";
echo "<p>Testing all email templates and integration functionality...</p>\n";

// Check if email automation is enabled
if (!EMAIL_AUTOMATION_ENABLED) {
    echo "<div style='color: red;'><strong>WARNING:</strong> EMAIL_AUTOMATION_ENABLED is set to false. Enable it in unified_config.php to test emails.</div>\n";
}

echo "<h2>Configuration Status</h2>\n";
echo "<ul>\n";
echo "<li>Email Automation: " . (EMAIL_AUTOMATION_ENABLED ? '✅ Enabled' : '❌ Disabled') . "</li>\n";
echo "<li>SMTP Host: " . SMTP_HOST . "</li>\n";
echo "<li>SMTP Port: " . SMTP_PORT . "</li>\n";
echo "<li>SMTP Username: " . SMTP_USERNAME . "</li>\n";
echo "<li>From Email: " . FROM_EMAIL . "</li>\n";
echo "<li>From Name: " . FROM_NAME . "</li>\n";
echo "</ul>\n";

// Get mail system instance
try {
    $mailSystem = getMailSystem();
    echo "<div style='color: green;'>✅ Mail system initialized successfully</div>\n";
} catch (Exception $e) {
    echo "<div style='color: red;'>❌ Failed to initialize mail system: " . $e->getMessage() . "</div>\n";
    exit;
}

echo "<h2>Testing Email Templates</h2>\n";

// Test all email templates
$tests = [
    // 1. Registration & Verification
    [
        'name' => 'Registration Verification',
        'method' => 'sendRegisterVerification',
        'params' => [$TEST_EMAIL, $TEST_NAME, 'ABC123', 'https://example.com/verify?token=ABC123']
    ],
    [
        'name' => 'Email Verification Success',
        'method' => 'sendEmailVerified',
        'params' => [$TEST_EMAIL, $TEST_NAME]
    ],
    
    // 2. Login & Security
    [
        'name' => 'Login Alert',
        'method' => 'sendLoginAlert',
        'params' => [$TEST_EMAIL, $TEST_NAME, date('Y-m-d H:i:s'), '192.168.1.1', 'Chrome on Windows']
    ],
    
    // 3. KYC Process
    [
        'name' => 'KYC Approved',
        'method' => 'sendKYCApproved',
        'params' => [$TEST_EMAIL, $TEST_NAME]
    ],
    [
        'name' => 'KYC Rejected',
        'method' => 'sendKYCRejected',
        'params' => [$TEST_EMAIL, $TEST_NAME, 'Document quality is poor']
    ],
    
    // 4. Account Management
    [
        'name' => 'Live Account Opened',
        'method' => 'sendLiveAccountOpened',
        'params' => [$TEST_EMAIL, $TEST_NAME, '12345', 'Standard', '1:100', 'USD', 'MainPass123', 'InvestPass456']
    ],
    
    // 5. Deposits
    [
        'name' => 'Deposit Request',
        'method' => 'sendDepositRequest',
        'params' => [$TEST_EMAIL, $TEST_NAME, 1000, 'USD', 'Bank Transfer', 'DEP-123', '24-48 hours']
    ],
    [
        'name' => 'Deposit Approved',
        'method' => 'sendDepositApproved',
        'params' => [$TEST_EMAIL, $TEST_NAME, 1000, 'USD', 5000, 'DEP-123']
    ],
    [
        'name' => 'Deposit Failed',
        'method' => 'sendDepositFailed',
        'params' => [$TEST_EMAIL, $TEST_NAME, 1000, 'USD', 'Invalid payment method']
    ],
    
    // 6. Withdrawals
    [
        'name' => 'Withdrawal Request',
        'method' => 'sendWithdrawalRequest',
        'params' => [$TEST_EMAIL, $TEST_NAME, 500, 'USD', 'Bank Transfer', 'WD-456', '2-5 business days']
    ],
    [
        'name' => 'Withdrawal Approved',
        'method' => 'sendWithdrawalApproved',
        'params' => [$TEST_EMAIL, $TEST_NAME, 500, 'USD', 4500, 'WD-456']
    ],
    [
        'name' => 'Withdrawal Rejected',
        'method' => 'sendWithdrawalRejected',
        'params' => [$TEST_EMAIL, $TEST_NAME, 500, 'USD', 'Insufficient funds']
    ],
    
    // 7. Trading
    [
        'name' => 'Trade Opened',
        'method' => 'sendTradeOpened',
        'params' => [$TEST_EMAIL, $TEST_NAME, 'EURUSD', 'BUY', 1.0, 1.1000, 1.0950, 1.1050, '12345']
    ],
    [
        'name' => 'Trade Closed',
        'method' => 'sendTradeClosed',
        'params' => [$TEST_EMAIL, $TEST_NAME, 'EURUSD', 'BUY', 1.0, 1.1000, 1.1025, 25.00, '12345']
    ],
    [
        'name' => 'Margin Call',
        'method' => 'sendMarginCall',
        'params' => [$TEST_EMAIL, $TEST_NAME, 150.00, 100.00, 50.00]
    ],
    [
        'name' => 'Stop Out',
        'method' => 'sendStopOut',
        'params' => [$TEST_EMAIL, $TEST_NAME, 25.00, 50.00]
    ],
    
    // 8. Referrals
    [
        'name' => 'Referral Registration',
        'method' => 'sendReferralRegistration',
        'params' => [$TEST_EMAIL, $TEST_NAME, 'John Doe', 'john@example.com', 'REF123']
    ],
    [
        'name' => 'Referral Commission',
        'method' => 'sendReferralCommission',
        'params' => [$TEST_EMAIL, $TEST_NAME, 50.00, 'USD', 'John Doe', 'Trade Commission']
    ],
    
    // 9. Password & Security
    [
        'name' => 'Password Reset',
        'method' => 'sendPasswordReset',
        'params' => [$TEST_EMAIL, $TEST_NAME, 'RESET123', '1 hour']
    ],
    [
        'name' => 'Password Changed',
        'method' => 'sendPasswordChanged',
        'params' => [$TEST_EMAIL, $TEST_NAME, '192.168.1.1']
    ],
    
    // 10. Profile & Notifications
    [
        'name' => 'Profile Updated',
        'method' => 'sendProfileUpdated',
        'params' => [$TEST_EMAIL, $TEST_NAME, 'Phone number, Address']
    ],
    [
        'name' => 'Daily Trade Summary',
        'method' => 'sendDailyTradeSummary',
        'params' => [$TEST_EMAIL, $TEST_NAME, 5, 3, 2, 150.00, 'USD', 60.0]
    ],
    [
        'name' => 'Promotional Offer',
        'method' => 'sendPromotionalOffer',
        'params' => [$TEST_EMAIL, $TEST_NAME, '50% Deposit Bonus', 'Get 50% bonus on your next deposit!', 'BONUS50', '2024-12-31']
    ]
];

$successCount = 0;
$failureCount = 0;

foreach ($tests as $test) {
    echo "<h3>Testing: {$test['name']}</h3>\n";
    
    try {
        $result = call_user_func_array([$mailSystem, $test['method']], $test['params']);
        
        if ($result['success']) {
            echo "<div style='color: green;'>✅ {$test['name']}: SUCCESS</div>\n";
            $successCount++;
        } else {
            echo "<div style='color: red;'>❌ {$test['name']}: FAILED - {$result['message']}</div>\n";
            $failureCount++;
        }
    } catch (Exception $e) {
        echo "<div style='color: red;'>❌ {$test['name']}: ERROR - {$e->getMessage()}</div>\n";
        $failureCount++;
    }
    
    // Small delay to prevent overwhelming the mail server
    usleep(100000); // 0.1 second delay
}

echo "<h2>Test Summary</h2>\n";
echo "<div style='padding: 10px; border: 1px solid #ccc; background: #f9f9f9;'>\n";
echo "<strong>Total Tests:</strong> " . count($tests) . "<br>\n";
echo "<strong style='color: green;'>Successful:</strong> $successCount<br>\n";
echo "<strong style='color: red;'>Failed:</strong> $failureCount<br>\n";

if ($failureCount === 0) {
    echo "<div style='color: green; font-weight: bold; margin-top: 10px;'>🎉 All email templates are working correctly!</div>\n";
} else {
    echo "<div style='color: orange; font-weight: bold; margin-top: 10px;'>⚠️ Some email templates failed. Check SMTP configuration and error logs.</div>\n";
}
echo "</div>\n";

echo "<h2>Integration Files Updated</h2>\n";
echo "<p>The following files have been updated with email integration:</p>\n";
echo "<ul>\n";
echo "<li>✅ register.php - Registration verification emails</li>\n";
echo "<li>✅ login.php - Login alert emails</li>\n";
echo "<li>✅ liveaccount.php - Live account opening emails</li>\n";
echo "<li>✅ admin_kycapproval.php - KYC approval/rejection emails</li>\n";
echo "<li>✅ admin_withdrawal.php - Withdrawal approval/rejection emails</li>\n";
echo "<li>✅ admin_deposit.php - Deposit approval/rejection emails</li>\n";
echo "<li>✅ deposit.php - Deposit request emails</li>\n";
echo "<li>✅ admin_changepassword.php - Admin password change emails</li>\n";
echo "<li>✅ changeliveaccpass.php - Live account password change emails</li>\n";
echo "</ul>\n";

echo "<h2>Next Steps</h2>\n";
echo "<ol>\n";
echo "<li>Update SMTP credentials in unified_config.php with real email server details</li>\n";
echo "<li>Test with actual email addresses</li>\n";
echo "<li>Monitor email delivery and logs</li>\n";
echo "<li>Customize email templates as needed</li>\n";
echo "<li>Set up email automation triggers in production</li>\n";
echo "</ol>\n";

echo "<p><em>Test completed at: " . date('Y-m-d H:i:s') . "</em></p>\n";
?>