<?php
require_once '../config/database.php';
require_once '../config/currency.php';
require_once '../config/payment_security.php';
require_once '../includes/payments.php';
require_once '../includes/notifications.php';

requireLogin();

// Check if user is admin
$currentUser = getCurrentUser();
if ($currentUser['role'] !== 'admin') {
    header('Location: dashboard.php');
    exit;
}

$success = '';
$error = '';
$testResults = [];

$db = getDB();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $testType = $_POST['test_type'] ?? '';

    switch ($testType) {
        case 'security_validation':
            $testResults = testSecurityValidation();
            break;

        case 'currency_conversion':
            $testResults = testCurrencyConversion();
            break;

        case 'payment_flow':
            $testResults = testPaymentFlow();
            break;

        case 'error_handling':
            $testResults = testErrorHandling();
            break;

        case 'gateway_compatibility':
            $testResults = testGatewayCompatibility();
            break;

        case 'run_all_tests':
            $testResults = array_merge(
                testSecurityValidation(),
                testCurrencyConversion(),
                testPaymentFlow(),
                testErrorHandling(),
                testGatewayCompatibility()
            );
            break;
    }
}

function testSecurityValidation() {
    $results = [];

    // Test input sanitization
    try {
        $sanitized = PaymentSecurity::sanitizeInput([
            'amount' => '100.50',
            'currency' => 'USD',
            'discount_code' => 'TEST123'
        ], PAYMENT_VALIDATION_RULES);

        $results[] = ['test' => 'Input Sanitization', 'status' => 'pass', 'message' => 'Input validation successful'];
    } catch (Exception $e) {
        $results[] = ['test' => 'Input Sanitization', 'status' => 'fail', 'message' => $e->getMessage()];
    }

    // Test rate limiting (simulate)
    try {
        PaymentSecurity::checkRateLimit(1); // Should pass for admin
        $results[] = ['test' => 'Rate Limiting', 'status' => 'pass', 'message' => 'Rate limiting check passed'];
    } catch (Exception $e) {
        $results[] = ['test' => 'Rate Limiting', 'status' => 'fail', 'message' => $e->getMessage()];
    }

    // Test invalid input
    try {
        PaymentSecurity::sanitizeInput([
            'amount' => 'invalid_amount',
            'currency' => 'INVALID'
        ], PAYMENT_VALIDATION_RULES);

        $results[] = ['test' => 'Invalid Input Handling', 'status' => 'fail', 'message' => 'Should have thrown exception'];
    } catch (Exception $e) {
        $results[] = ['test' => 'Invalid Input Handling', 'status' => 'pass', 'message' => 'Correctly rejected invalid input'];
    }

    return $results;
}

function testCurrencyConversion() {
    $results = [];

    // Test valid conversion
    try {
        $converted = CurrencyHelper::convert(100, 'USD', 'EUR');
        if ($converted > 0) {
            $results[] = ['test' => 'Currency Conversion (USD to EUR)', 'status' => 'pass', 'message' => "100 USD = {$converted} EUR"];
        } else {
            $results[] = ['test' => 'Currency Conversion (USD to EUR)', 'status' => 'fail', 'message' => 'Conversion returned zero'];
        }
    } catch (Exception $e) {
        $results[] = ['test' => 'Currency Conversion (USD to EUR)', 'status' => 'fail', 'message' => $e->getMessage()];
    }

    // Test same currency conversion
    try {
        $converted = CurrencyHelper::convert(100, 'USD', 'USD');
        if ($converted == 100) {
            $results[] = ['test' => 'Same Currency Conversion', 'status' => 'pass', 'message' => 'Same currency conversion works'];
        } else {
            $results[] = ['test' => 'Same Currency Conversion', 'status' => 'fail', 'message' => 'Same currency conversion failed'];
        }
    } catch (Exception $e) {
        $results[] = ['test' => 'Same Currency Conversion', 'status' => 'fail', 'message' => $e->getMessage()];
    }

    // Test invalid currency
    try {
        CurrencyHelper::convert(100, 'INVALID', 'USD');
        $results[] = ['test' => 'Invalid Currency Handling', 'status' => 'fail', 'message' => 'Should have thrown exception'];
    } catch (Exception $e) {
        $results[] = ['test' => 'Invalid Currency Handling', 'status' => 'pass', 'message' => 'Correctly rejected invalid currency'];
    }

    // Test currency formatting
    try {
        $formatted = CurrencyHelper::format(1234.56, 'USD');
        if (strpos($formatted, '$') !== false) {
            $results[] = ['test' => 'Currency Formatting', 'status' => 'pass', 'message' => "Formatted: {$formatted}"];
        } else {
            $results[] = ['test' => 'Currency Formatting', 'status' => 'fail', 'message' => 'Formatting failed'];
        }
    } catch (Exception $e) {
        $results[] = ['test' => 'Currency Formatting', 'status' => 'fail', 'message' => $e->getMessage()];
    }

    return $results;
}

function testPaymentFlow() {
    $results = [];

    // Test gateway initialization
    try {
        $gateway = getPaymentGateway('paynow', 'sandbox');
        $results[] = ['test' => 'Gateway Initialization', 'status' => 'pass', 'message' => 'Paynow gateway initialized successfully'];
    } catch (Exception $e) {
        $results[] = ['test' => 'Gateway Initialization', 'status' => 'fail', 'message' => $e->getMessage()];
    }

    // Test transaction creation (without actual payment)
    try {
        $db = getDB();
        $referenceNumber = 'TEST_' . time() . '_' . rand(1000, 9999);

        $stmt = $db->prepare("
            INSERT INTO payment_transactions
            (transaction_id, reference_number, gateway_name, gateway_type, user_id, item_type, item_id,
             amount, currency, final_amount, status, created_at)
            VALUES (?, ?, 'paynow', 'sandbox', 1, 'course', 1, 100.00, 'USD', 100.00, 'pending', NOW())
        ");

        $stmt->execute([uniqid('test_', true), $referenceNumber]);

        $results[] = ['test' => 'Transaction Creation', 'status' => 'pass', 'message' => 'Test transaction created successfully'];

        // Clean up test transaction
        $db->prepare("DELETE FROM payment_transactions WHERE reference_number = ?")->execute([$referenceNumber]);

    } catch (Exception $e) {
        $results[] = ['test' => 'Transaction Creation', 'status' => 'fail', 'message' => $e->getMessage()];
    }

    return $results;
}

function testErrorHandling() {
    $results = [];

    // Test invalid gateway
    try {
        getPaymentGateway('invalid_gateway');
        $results[] = ['test' => 'Invalid Gateway Handling', 'status' => 'fail', 'message' => 'Should have thrown exception'];
    } catch (Exception $e) {
        $results[] = ['test' => 'Invalid Gateway Handling', 'status' => 'pass', 'message' => 'Correctly handled invalid gateway'];
    }

    // Test discount code validation
    try {
        $gateway = new PaymentGateway('paynow', 'sandbox');
        $reflection = new ReflectionClass($gateway);
        $method = $reflection->getMethod('validateDiscountCode');
        $method->setAccessible(true);

        $result = $method->invoke($gateway, 'INVALID_CODE', 100);
        if ($result === false) {
            $results[] = ['test' => 'Invalid Discount Code', 'status' => 'pass', 'message' => 'Correctly rejected invalid discount code'];
        } else {
            $results[] = ['test' => 'Invalid Discount Code', 'status' => 'fail', 'message' => 'Should have rejected invalid code'];
        }
    } catch (Exception $e) {
        $results[] = ['test' => 'Invalid Discount Code', 'status' => 'fail', 'message' => $e->getMessage()];
    }

    return $results;
}

function testGatewayCompatibility() {
    $results = [];

    // Test currency support
    $currencies = ['USD', 'ZAR', 'EUR', 'GBP'];

    foreach ($currencies as $currency) {
        $paypalSupport = CurrencyHelper::isSupportedByGateway($currency, 'paypal');
        $paynowSupport = CurrencyHelper::isSupportedByGateway($currency, 'paynow');

        $results[] = [
            'test' => "Currency Support: {$currency}",
            'status' => 'info',
            'message' => "PayPal: " . ($paypalSupport ? 'Yes' : 'No') . ", Paynow: " . ($paynowSupport ? 'Yes' : 'No')
        ];
    }

    // Test gateway settings retrieval
    try {
        $gateways = $db->query("SELECT gateway_name, gateway_type, is_active FROM payment_gateway_settings")->fetchAll();
        $results[] = [
            'test' => 'Gateway Settings',
            'status' => 'pass',
            'message' => 'Found ' . count($gateways) . ' gateway configurations'
        ];
    } catch (Exception $e) {
        $results[] = [
            'test' => 'Gateway Settings',
            'status' => 'fail',
            'message' => $e->getMessage()
        ];
    }

    return $results;
}

$page_title = 'Payment System Tests';
include 'includes/admin_header.php';
?>

<div class="test-section">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2>Payment System Tests</h2>
            <p class="text-muted">Test payment flows, security measures, and error handling</p>
        </div>
        <form method="POST" class="d-inline">
            <input type="hidden" name="test_type" value="run_all_tests">
            <button type="submit" class="btn btn-success">
                <i class="fas fa-play me-2"></i>Run All Tests
            </button>
        </form>
    </div>

    <?php if ($error): ?>
        <div class="alert alert-error">
            <?php echo htmlspecialchars($error); ?>
        </div>
    <?php endif; ?>

    <?php if ($success): ?>
        <div class="alert alert-success">
            <?php echo htmlspecialchars($success); ?>
        </div>
    <?php endif; ?>

    <!-- Test Categories -->
    <div class="row mb-4">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Test Categories</h5>
                </div>
                <div class="card-body">
                    <div class="test-buttons">
                        <form method="POST" class="d-inline me-2 mb-2">
                            <input type="hidden" name="test_type" value="security_validation">
                            <button type="submit" class="btn btn-outline-primary">
                                <i class="fas fa-shield-alt me-2"></i>Security Validation
                            </button>
                        </form>

                        <form method="POST" class="d-inline me-2 mb-2">
                            <input type="hidden" name="test_type" value="currency_conversion">
                            <button type="submit" class="btn btn-outline-primary">
                                <i class="fas fa-exchange-alt me-2"></i>Currency Conversion
                            </button>
                        </form>

                        <form method="POST" class="d-inline me-2 mb-2">
                            <input type="hidden" name="test_type" value="payment_flow">
                            <button type="submit" class="btn btn-outline-primary">
                                <i class="fas fa-credit-card me-2"></i>Payment Flow
                            </button>
                        </form>

                        <form method="POST" class="d-inline me-2 mb-2">
                            <input type="hidden" name="test_type" value="error_handling">
                            <button type="submit" class="btn btn-outline-primary">
                                <i class="fas fa-exclamation-triangle me-2"></i>Error Handling
                            </button>
                        </form>

                        <form method="POST" class="d-inline me-2 mb-2">
                            <input type="hidden" name="test_type" value="gateway_compatibility">
                            <button type="submit" class="btn btn-outline-primary">
                                <i class="fas fa-plug me-2"></i>Gateway Compatibility
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Test Results -->
    <?php if (!empty($testResults)): ?>
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">Test Results</h5>
            </div>
            <div class="card-body">
                <div class="test-results">
                    <?php
                    $passed = 0;
                    $failed = 0;
                    $info = 0;

                    foreach ($testResults as $result):
                        if ($result['status'] === 'pass') $passed++;
                        elseif ($result['status'] === 'fail') $failed++;
                        else $info++;
                    ?>
                        <div class="test-result <?php echo $result['status']; ?>">
                            <div class="test-header">
                                <span class="test-name"><?php echo htmlspecialchars($result['test']); ?></span>
                                <span class="test-status <?php echo $result['status']; ?>">
                                    <i class="fas fa-<?php
                                        echo $result['status'] === 'pass' ? 'check-circle' :
                                             ($result['status'] === 'fail' ? 'times-circle' : 'info-circle');
                                    ?>"></i>
                                    <?php echo ucfirst($result['status']); ?>
                                </span>
                            </div>
                            <div class="test-message"><?php echo htmlspecialchars($result['message']); ?></div>
                        </div>
                    <?php endforeach; ?>
                </div>

                <!-- Summary -->
                <div class="test-summary mt-4">
                    <h6>Test Summary</h6>
                    <div class="summary-stats">
                        <span class="stat passed">
                            <i class="fas fa-check-circle"></i>
                            <?php echo $passed; ?> Passed
                        </span>
                        <span class="stat failed">
                            <i class="fas fa-times-circle"></i>
                            <?php echo $failed; ?> Failed
                        </span>
                        <span class="stat info">
                            <i class="fas fa-info-circle"></i>
                            <?php echo $info; ?> Info
                        </span>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <!-- System Information -->
    <div class="row mt-4">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">System Information</h5>
                </div>
                <div class="card-body">
                    <div class="system-info">
                        <div class="info-item">
                            <strong>PHP Version:</strong> <?php echo phpversion(); ?>
                        </div>
                        <div class="info-item">
                            <strong>Database:</strong> MySQL (PDO)
                        </div>
                        <div class="info-item">
                            <strong>HTTPS:</strong> <?php echo isset($_SERVER['HTTPS']) ? 'Enabled' : 'Disabled'; ?>
                        </div>
                        <div class="info-item">
                            <strong>Payment Gateways:</strong>
                            <?php
                            $gateways = $db->query("SELECT COUNT(*) FROM payment_gateway_settings WHERE is_active = 1")->fetchColumn();
                            echo $gateways . ' active';
                            ?>
                        </div>
                        <div class="info-item">
                            <strong>Currencies:</strong> <?php echo count(SUPPORTED_CURRENCIES); ?> supported
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Quick Actions</h5>
                </div>
                <div class="card-body">
                    <div class="quick-actions">
                        <a href="payment_gateways.php" class="btn btn-outline-primary btn-sm mb-2">
                            <i class="fas fa-credit-card me-2"></i>Configure Gateways
                        </a>
                        <a href="currency_settings.php" class="btn btn-outline-primary btn-sm mb-2">
                            <i class="fas fa-money-bill-wave me-2"></i>Currency Settings
                        </a>
                        <a href="pci_compliance.php" class="btn btn-outline-primary btn-sm mb-2">
                            <i class="fas fa-shield-alt me-2"></i>PCI Compliance
                        </a>
                        <a href="payment_analytics.php" class="btn btn-outline-primary btn-sm mb-2">
                            <i class="fas fa-chart-bar me-2"></i>View Analytics
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.test-section {
    max-width: 1400px;
}

.test-buttons .btn {
    margin-bottom: 0.5rem;
}

.test-results {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.test-result {
    border: 1px solid #e5e7eb;
    border-radius: 0.5rem;
    padding: 1rem;
}

.test-result.pass {
    border-color: #10b981;
    background-color: #f0fdf4;
}

.test-result.fail {
    border-color: #ef4444;
    background-color: #fef2f2;
}

.test-result.info {
    border-color: #3b82f6;
    background-color: #eff6ff;
}

.test-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0.5rem;
}

.test-name {
    font-weight: 600;
    color: #1f2937;
}

.test-status {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-weight: 600;
    padding: 0.25rem 0.5rem;
    border-radius: 0.25rem;
    font-size: 0.875rem;
}

.test-status.pass {
    background-color: #dcfce7;
    color: #166534;
}

.test-status.fail {
    background-color: #fee2e2;
    color: #dc2626;
}

.test-status.info {
    background-color: #dbeafe;
    color: #1e40af;
}

.test-message {
    color: #6b7280;
    font-size: 0.875rem;
}

.test-summary {
    border-top: 1px solid #e5e7eb;
    padding-top: 1rem;
}

.test-summary h6 {
    color: #1f2937;
    margin-bottom: 1rem;
}

.summary-stats {
    display: flex;
    gap: 1rem;
}

.stat {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 1rem;
    border-radius: 0.375rem;
    font-weight: 600;
    font-size: 0.875rem;
}

.stat.passed {
    background-color: #dcfce7;
    color: #166534;
}

.stat.failed {
    background-color: #fee2e2;
    color: #dc2626;
}

.stat.info {
    background-color: #dbeafe;
    color: #1e40af;
}

.card {
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    border: none;
    border-radius: 0.75rem;
}

.card-header {
    background-color: #f8f9fa;
    border-bottom: 1px solid #e9ecef;
    padding: 1rem 1.5rem;
    border-radius: 0.75rem 0.75rem 0 0 !important;
}

.card-header h5 {
    color: #1f2937;
    margin: 0;
}

.card-body {
    padding: 1.5rem;
}

.system-info {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
}

.info-item {
    display: flex;
    justify-content: space-between;
    padding: 0.5rem 0;
    border-bottom: 1px solid #f3f4f6;
}

.info-item:last-child {
    border-bottom: none;
}

.quick-actions {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.btn {
    padding: 0.5rem 1rem;
    border: 1px solid #d1d5db;
    border-radius: 0.375rem;
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
    transition: all 0.2s;
}

.btn-outline-primary {
    color: #2563eb;
    border-color: #2563eb;
}

.btn-outline-primary:hover {
    background-color: #2563eb;
    color: white;
}

.btn-success {
    background-color: #10b981;
    color: white;
    border-color: #10b981;
}

.btn-success:hover {
    background-color: #059669;
}

.alert {
    padding: 1rem;
    border-radius: 0.5rem;
    margin-bottom: 1rem;
}

.alert-error {
    background-color: #fef2f2;
    border: 1px solid #fecaca;
    color: #dc2626;
}

.alert-success {
    background-color: #f0fdf4;
    border: 1px solid #bbf7d0;
    color: #16a34a;
}

@media (max-width: 768px) {
    .test-buttons {
        display: flex;
        flex-direction: column;
    }

    .test-buttons .btn {
        width: 100%;
    }

    .summary-stats {
        flex-direction: column;
    }

    .row {
        flex-direction: column;
    }

    .col-md-6 {
        margin-bottom: 1rem;
    }
}
</style>

<?php include 'includes/admin_footer.php'; ?>