<?php
/*
 * Test Voucher Generator
 * Test VoucherGenerator class functionality
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<!DOCTYPE html>
<html>
<head>
    <title>Test Voucher Generator</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 1000px; margin: 30px auto; padding: 20px; background: #f5f7fa; }
        .container { background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        h1 { color: #333; border-bottom: 3px solid #667eea; padding-bottom: 10px; }
        h2 { color: #667eea; margin-top: 30px; }
        .test-case { background: #f8f9fa; padding: 15px; margin: 15px 0; border-left: 4px solid #667eea; border-radius: 5px; }
        .success { background: #d4edda; color: #155724; padding: 10px; border-radius: 5px; margin: 5px 0; }
        .error { background: #f8d7da; color: #721c24; padding: 10px; border-radius: 5px; margin: 5px 0; }
        .info { background: #d1ecf1; color: #0c5460; padding: 10px; border-radius: 5px; margin: 5px 0; }
        .voucher-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 15px; margin: 15px 0; }
        .voucher-card { background: white; border: 2px solid #e0e0e0; border-radius: 8px; padding: 15px; text-align: center; }
        .voucher-username { font-weight: bold; font-size: 16px; color: #333; margin-bottom: 5px; }
        .voucher-password { font-family: monospace; background: #f0f0f0; padding: 8px; border-radius: 4px; font-size: 14px; }
        code { background: #f4f4f4; padding: 2px 6px; border-radius: 3px; font-family: monospace; }
        table { width: 100%; border-collapse: collapse; margin: 15px 0; }
        table th { background: #667eea; color: white; padding: 10px; text-align: left; }
        table td { padding: 10px; border-bottom: 1px solid #e0e0e0; }
        .stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; margin: 20px 0; }
        .stat-card { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 8px; text-align: center; }
        .stat-value { font-size: 32px; font-weight: bold; }
        .stat-label { font-size: 14px; opacity: 0.9; }
    </style>
</head>
<body>
<div class='container'>";

echo "<h1>🧪 Voucher Generator Test Suite</h1>";

// Include required files
try {
    include_once('./include/db_config.php');
    include_once('./lib/VoucherGenerator.class.php');
    
    echo "<div class='success'>✅ Files loaded successfully</div>";
} catch (Exception $e) {
    echo "<div class='error'>❌ Error loading files: " . $e->getMessage() . "</div>";
    exit;
}

// Initialize generator
try {
    $generator = new VoucherGenerator();
    echo "<div class='success'>✅ VoucherGenerator initialized</div>";
} catch (Exception $e) {
    echo "<div class='error'>❌ Error initializing generator: " . $e->getMessage() . "</div>";
    exit;
}

// Display current settings
echo "<h2>📋 Current Settings</h2>";
$settings = $generator->getSettings();

echo "<table>";
echo "<tr><th>Setting Key</th><th>Value</th></tr>";
foreach ($settings as $key => $value) {
    echo "<tr><td><code>$key</code></td><td><strong>$value</strong></td></tr>";
}
echo "</table>";

// Test Case 1: Generate Single Voucher
echo "<h2>🎫 Test Case 1: Generate Single Voucher</h2>";
echo "<div class='test-case'>";
echo "<strong>Test:</strong> Generate 1 voucher with current settings<br>";

try {
    $voucher = $generator->generateVoucher();
    echo "<div class='success'>✅ Voucher generated successfully</div>";
    echo "<div class='voucher-grid'>";
    echo "<div class='voucher-card'>";
    echo "<div class='voucher-username'>{$voucher['username']}</div>";
    echo "<div class='voucher-password'>{$voucher['password']}</div>";
    echo "</div>";
    echo "</div>";
} catch (Exception $e) {
    echo "<div class='error'>❌ Error: " . $e->getMessage() . "</div>";
}

echo "</div>";

// Test Case 2: Generate Multiple Vouchers
echo "<h2>🎫 Test Case 2: Generate Multiple Vouchers</h2>";
echo "<div class='test-case'>";
echo "<strong>Test:</strong> Generate 10 vouchers<br>";

try {
    $vouchers = $generator->generateMultipleVouchers(10);
    echo "<div class='success'>✅ Generated " . count($vouchers) . " vouchers</div>";
    
    echo "<div class='voucher-grid'>";
    foreach ($vouchers as $voucher) {
        echo "<div class='voucher-card'>";
        echo "<div class='voucher-username'>{$voucher['username']}</div>";
        echo "<div class='voucher-password'>{$voucher['password']}</div>";
        echo "</div>";
    }
    echo "</div>";
    
    // Check for duplicates
    $usernames = array_column($vouchers, 'username');
    $uniqueUsernames = array_unique($usernames);
    
    if (count($usernames) === count($uniqueUsernames)) {
        echo "<div class='success'>✅ No duplicate usernames found</div>";
    } else {
        echo "<div class='error'>⚠️ Found " . (count($usernames) - count($uniqueUsernames)) . " duplicate(s)</div>";
    }
    
} catch (Exception $e) {
    echo "<div class='error'>❌ Error: " . $e->getMessage() . "</div>";
}

echo "</div>";

// Test Case 3: Character Type Tests
echo "<h2>🔤 Test Case 3: Character Type Validation</h2>";

$testTypes = [
    ['type' => 'numeric', 'length' => 8, 'pattern' => '/^[0-9]+$/'],
    ['type' => 'alpha', 'length' => 8, 'pattern' => '/^[A-Z]+$/'],
    ['type' => 'alphanumeric', 'length' => 8, 'pattern' => '/^[A-Z0-9]+$/']
];

foreach ($testTypes as $test) {
    echo "<div class='test-case'>";
    echo "<strong>Test:</strong> Type = <code>{$test['type']}</code>, Length = {$test['length']}<br>";
    
    // Temporarily change settings (for testing only)
    $db = getDBConnection();
    $stmt = $db->prepare("UPDATE agent_settings SET setting_value = ? WHERE setting_key = 'voucher_username_type'");
    $stmt->execute([$test['type']]);
    $stmt = $db->prepare("UPDATE agent_settings SET setting_value = ? WHERE setting_key = 'voucher_username_length'");
    $stmt->execute([$test['length']]);
    
    // Reload generator
    $generator = new VoucherGenerator();
    $voucher = $generator->generateVoucher();
    
    // Validate
    $username = $voucher['username'];
    // Remove prefix for validation
    $prefix = $generator->getSetting('voucher_prefix_enabled') == '1' ? $generator->getSetting('voucher_prefix') : '';
    if (!empty($prefix) && strpos($username, $prefix) === 0) {
        $username = substr($username, strlen($prefix));
    }
    
    if (preg_match($test['pattern'], $username)) {
        echo "<div class='success'>✅ Valid: <code>$username</code> matches pattern</div>";
    } else {
        echo "<div class='error'>❌ Invalid: <code>$username</code> doesn't match pattern</div>";
    }
    
    echo "</div>";
}

// Test Case 4: Length Validation
echo "<h2>📏 Test Case 4: Length Validation</h2>";

$testLengths = [4, 6, 8, 10, 12, 15, 20];

foreach ($testLengths as $length) {
    echo "<div class='test-case'>";
    echo "<strong>Test:</strong> Length = $length<br>";
    
    $db = getDBConnection();
    $stmt = $db->prepare("UPDATE agent_settings SET setting_value = ? WHERE setting_key = 'voucher_username_length'");
    $stmt->execute([$length]);
    $stmt = $db->prepare("UPDATE agent_settings SET setting_value = '0' WHERE setting_key = 'voucher_prefix_enabled'");
    $stmt->execute();
    
    $generator = new VoucherGenerator();
    $voucher = $generator->generateVoucher();
    $actualLength = strlen($voucher['username']);
    
    if ($actualLength == $length) {
        echo "<div class='success'>✅ Correct length: <code>{$voucher['username']}</code> ($actualLength chars)</div>";
    } else {
        echo "<div class='error'>❌ Wrong length: Expected $length, got $actualLength</div>";
    }
    
    echo "</div>";
}

// Test Case 5: Prefix Test
echo "<h2>🏷️ Test Case 5: Prefix Validation</h2>";
echo "<div class='test-case'>";
echo "<strong>Test:</strong> Prefix enabled with 'TEST'<br>";

$db = getDBConnection();
$stmt = $db->prepare("UPDATE agent_settings SET setting_value = '1' WHERE setting_key = 'voucher_prefix_enabled'");
$stmt->execute();
$stmt = $db->prepare("UPDATE agent_settings SET setting_value = 'TEST' WHERE setting_key = 'voucher_prefix'");
$stmt->execute();

$generator = new VoucherGenerator();
$voucher = $generator->generateVoucher();

if (strpos($voucher['username'], 'TEST') === 0) {
    echo "<div class='success'>✅ Prefix working: <code>{$voucher['username']}</code></div>";
} else {
    echo "<div class='error'>❌ Prefix not found in: <code>{$voucher['username']}</code></div>";
}

echo "</div>";

// Test Case 6: Same Username/Password
echo "<h2>🔐 Test Case 6: Same Username/Password</h2>";
echo "<div class='test-case'>";
echo "<strong>Test:</strong> Username and password should be same<br>";

$db = getDBConnection();
$stmt = $db->prepare("UPDATE agent_settings SET setting_value = '1' WHERE setting_key = 'voucher_username_password_same'");
$stmt->execute();

$generator = new VoucherGenerator();
$voucher = $generator->generateVoucher();

if ($voucher['username'] === $voucher['password']) {
    echo "<div class='success'>✅ Username and password are same: <code>{$voucher['username']}</code></div>";
} else {
    echo "<div class='error'>❌ Username and password are different</div>";
    echo "<div class='info'>Username: {$voucher['username']}, Password: {$voucher['password']}</div>";
}

echo "</div>";

// Performance Test
echo "<h2>⚡ Performance Test</h2>";
echo "<div class='test-case'>";
echo "<strong>Test:</strong> Generate 100 vouchers and measure time<br>";

$startTime = microtime(true);
$vouchers = $generator->generateMultipleVouchers(100);
$endTime = microtime(true);
$duration = ($endTime - $startTime) * 1000; // Convert to milliseconds

echo "<div class='stats'>";
echo "<div class='stat-card'><div class='stat-value'>100</div><div class='stat-label'>Vouchers</div></div>";
echo "<div class='stat-card'><div class='stat-value'>" . number_format($duration, 2) . "ms</div><div class='stat-label'>Total Time</div></div>";
echo "<div class='stat-card'><div class='stat-value'>" . number_format($duration/100, 2) . "ms</div><div class='stat-label'>Per Voucher</div></div>";
echo "<div class='stat-card'><div class='stat-value'>" . number_format(100/($duration/1000), 0) . "</div><div class='stat-label'>Vouchers/sec</div></div>";
echo "</div>";

if ($duration < 1000) {
    echo "<div class='success'>✅ Excellent performance!</div>";
} else {
    echo "<div class='info'>⚠️ Performance could be improved</div>";
}

echo "</div>";

// Restore default settings
echo "<h2>🔄 Restoring Default Settings</h2>";
$db = getDBConnection();
$db->exec("UPDATE agent_settings SET setting_value = '0' WHERE setting_key = 'voucher_username_password_same'");
$db->exec("UPDATE agent_settings SET setting_value = 'alphanumeric' WHERE setting_key = 'voucher_username_type'");
$db->exec("UPDATE agent_settings SET setting_value = '8' WHERE setting_key = 'voucher_username_length'");
$db->exec("UPDATE agent_settings SET setting_value = '1' WHERE setting_key = 'voucher_prefix_enabled'");
$db->exec("UPDATE agent_settings SET setting_value = 'AG' WHERE setting_key = 'voucher_prefix'");
echo "<div class='success'>✅ Default settings restored</div>";

echo "<h2>✅ Test Suite Complete</h2>";
echo "<div class='success'>";
echo "<strong>All tests completed!</strong><br>";
echo "VoucherGenerator class is working correctly.";
echo "</div>";

echo "<div style='margin-top: 30px; text-align: center;'>";
echo "<a href='./admin.php' style='display: inline-block; padding: 10px 20px; background: #667eea; color: white; text-decoration: none; border-radius: 5px;'>Back to Admin</a>";
echo "</div>";

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