<?php
/**
 * Test SMART API Connection
 * Comprehensive testing page for SMART integration
 */
session_start();
require_once 'layouts/dbconn.php';
require_once 'layouts/session.php';

// Check permission
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: index.php');
    exit();
}

$page_title = "Test SMART Connection";

// Fetch SMART settings
$settings_query = "SELECT setting_key, setting_value FROM system_settings WHERE category = 'smart'";
$settings_result = mysqli_query($conn, $settings_query);
$smart_settings = [];
while ($row = mysqli_fetch_assoc($settings_result)) {
    $smart_settings[$row['setting_key']] = $row['setting_value'];
}

// Determine environment
$env = $smart_settings['smart_environment'] ?? 'Not Set';
$api_url = $smart_settings['smart_api_url'] ?? '';
if (empty($api_url)) {
    // Auto-detect based on environment
    $api_url = $env === 'production' 
        ? 'https://data.smartapplicationsgroup.com/providerapi'
        : 'https://data.smartapplicationsgroup.com/providerapi-dev';
}
$enabled = ($smart_settings['smart_enabled'] ?? '0') === '1';

?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #2d7a2d 0%, #26a69a 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            transition: transform 0.2s;
            margin-bottom: 1.5rem;
            height: 100%;
        }
        
        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.15);
        }
        
        .config-item {
            margin-bottom: 1rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .config-item:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }
        
        .config-label {
            font-size: 0.75rem;
            color: #64748b;
            text-transform: uppercase;
            font-weight: 600;
            letter-spacing: 0.5px;
            margin-bottom: 0.25rem;
        }
        
        .config-value {
            font-size: 0.875rem;
            color: #1e293b;
            font-weight: 500;
        }
        
        .chart-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .chart-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1rem;
        }
        
        .test-step {
            padding: 1rem;
            margin-bottom: 0.5rem;
            border-radius: 8px;
            border-left: 4px solid #dee2e6;
            transition: all 0.3s;
        }

        .test-step.pending {
            background: #f8f9fa;
            border-left-color: #6c757d;
        }

        .test-step.running {
            background: #fff3cd;
            border-left-color: #ffc107;
            animation: pulse 1.5s infinite;
        }

        .test-step.success {
            background: #d1e7dd;
            border-left-color: #198754;
        }

        .test-step.failed {
            background: #f8d7da;
            border-left-color: #dc3545;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.8; }
        }

        .test-detail {
            font-size: 0.875rem;
            color: #6c757d;
            margin-top: 0.5rem;
        }
        
        .quick-action-btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.2s;
        }
        
        .quick-action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .endpoint-test-card {
            background: white;
            padding: 1rem;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
            margin-bottom: 0.75rem;
            transition: all 0.2s;
        }
        
        .endpoint-test-card:hover {
            border-color: #26a69a;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }
        
        .test-results-area {
            min-height: 300px;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">SMART API Testing</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item">System</li>
                                        <li class="breadcrumb-item active">SMART Testing</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h4><i class="ri-shield-check-line me-2"></i>SMART API Connection Test</h4>
                                <p class="mb-0">Comprehensive testing for SMART insurance integration</p>
                            </div>
                            <a href="system_settings.php" class="btn btn-light">
                                <i class="ri-settings-3-line me-1"></i> Settings
                            </a>
                        </div>
                    </div>

                    <!-- Configuration Status Cards -->
                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="config-item">
                                    <div class="config-label">Environment</div>
                                    <div class="config-value">
                                        <?php 
                                        $badge_class = $env === 'production' ? 'success' : 'warning';
                                        ?>
                                        <span class="badge bg-<?php echo $badge_class; ?> badge-lg">
                                            <?php echo strtoupper($env); ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="config-item">
                                    <div class="config-label">Integration Status</div>
                                    <div class="config-value">
                                        <span class="badge bg-<?php echo $enabled ? 'success' : 'secondary'; ?> badge-lg">
                                            <?php echo $enabled ? 'ENABLED' : 'DISABLED'; ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="config-item">
                                    <div class="config-label">API Endpoint</div>
                                    <div class="config-value small text-break">
                                        <?php echo htmlspecialchars($api_url); ?>
                                    </div>
                                </div>
                                <div class="config-item">
                                    <div class="config-label">Provider Key</div>
                                    <div class="config-value">
                                        <?php 
                                        $key = $smart_settings['smart_provider_key'] ?? '';
                                        echo $key ? '<code>' . substr($key, 0, 12) . '...</code>' : '<span class="text-muted">Not Set</span>';
                                        ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="config-item">
                                    <div class="config-label">Username</div>
                                    <div class="config-value">
                                        <?php 
                                        $username = $smart_settings['smart_username'] ?? '';
                                        echo $username ? htmlspecialchars($username) : '<span class="text-muted">Not Set</span>';
                                        ?>
                                    </div>
                                </div>
                                <div class="config-item">
                                    <div class="config-label">Password</div>
                                    <div class="config-value">
                                        <?php 
                                        $password = $smart_settings['smart_password'] ?? '';
                                        echo $password ? '<code>••••••••</code>' : '<span class="text-muted">Not Set</span>';
                                        ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="config-item">
                                    <div class="config-label">Client ID</div>
                                    <div class="config-value small">
                                        <?php 
                                        $client_id = $smart_settings['smart_client_id'] ?? '';
                                        echo $client_id ? '<code>' . substr($client_id, 0, 12) . '...</code>' : '<span class="text-muted">Not Set</span>';
                                        ?>
                                    </div>
                                </div>
                                <div class="config-item">
                                    <div class="config-label">Client Secret</div>
                                    <div class="config-value">
                                        <?php 
                                        $client_secret = $smart_settings['smart_client_secret'] ?? '';
                                        echo $client_secret ? '<code>••••••••</code>' : '<span class="text-muted">Not Set</span>';
                                        ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if (!$enabled): ?>
                    <div class="alert alert-warning border-0 mb-4">
                        <div class="d-flex align-items-center">
                            <i class="ri-alert-line fs-3 me-3"></i>
                            <div>
                                <strong>SMART Integration Disabled</strong>
                                <p class="mb-0">SMART integration is currently disabled. Enable it in System Settings to run tests.</p>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Quick Test Actions -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="chart-card">
                                <h5 class="mb-3">Quick Test Actions</h5>
                                <div class="d-flex flex-wrap gap-2">
                                    <button class="btn btn-success quick-action-btn" id="runAllTestsBtn">
                                        <i class="ri-play-circle-line"></i> Run All Tests
                                    </button>
                                    <button class="btn btn-primary quick-action-btn" id="testAuthBtn">
                                        <i class="ri-key-line"></i> Test Authentication
                                    </button>
                                    <button class="btn btn-info quick-action-btn" id="testLatencyBtn">
                                        <i class="ri-time-line"></i> Measure Latency
                                    </button>
                                    <button class="btn btn-outline-secondary quick-action-btn" id="clearHistoryBtn">
                                        <i class="ri-delete-bin-line"></i> Clear History
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Test Results -->
                        <div class="col-xl-8">
                            <div class="chart-card">
                                <h5 class="chart-title">
                                    <i class="ri-test-tube-line me-2"></i>Test Results
                                </h5>
                                <div id="testResults" class="test-results-area">
                                    <div class="text-center text-muted py-5">
                                        <i class="ri-flask-line" style="font-size: 3rem; opacity: 0.5;"></i>
                                        <p class="mt-3 mb-0">Click "Run All Tests" to begin comprehensive testing</p>
                                    </div>
                                </div>
                            </div>

                            <!-- Test History -->
                            <div class="chart-card">
                                <h5 class="chart-title">
                                    <i class="ri-history-line me-2"></i>Recent Test History
                                </h5>
                                <div class="table-responsive">
                                    <table class="table table-hover table-nowrap align-middle mb-0">
                                        <thead class="table-light">
                                            <tr>
                                                <th>Timestamp</th>
                                                <th>Test Type</th>
                                                <th>Status</th>
                                                <th>Response Time</th>
                                                <th>Details</th>
                                            </tr>
                                        </thead>
                                        <tbody id="testHistoryBody">
                                            <tr>
                                                <td colspan="5" class="text-center text-muted py-4">
                                                    No tests run yet
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <!-- Individual Endpoint Tests -->
                        <div class="col-xl-4">
                            <div class="chart-card">
                                <h5 class="chart-title">
                                    <i class="ri-compass-3-line me-2"></i>Endpoint Tests
                                </h5>
                                
                                <div class="endpoint-test-card">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <h6 class="mb-0"><i class="ri-user-follow-line me-1"></i> Member Lookup</h6>
                                    </div>
                                    <p class="text-muted small mb-2">Test member eligibility verification</p>
                                    <button class="btn btn-sm btn-outline-primary w-100" onclick="testMemberEndpoint()">
                                        <i class="ri-play-mini-line"></i> Test Endpoint
                                    </button>
                                    <div id="memberResults" class="mt-2"></div>
                                </div>

                                <div class="endpoint-test-card">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <h6 class="mb-0"><i class="ri-stethoscope-line me-1"></i> Visit/Session</h6>
                                    </div>
                                    <p class="text-muted small mb-2">Test visit session creation</p>
                                    <button class="btn btn-sm btn-outline-primary w-100" onclick="testVisitEndpoint()">
                                        <i class="ri-play-mini-line"></i> Test Endpoint
                                    </button>
                                    <div id="visitResults" class="mt-2"></div>
                                </div>

                                <div class="endpoint-test-card">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <h6 class="mb-0"><i class="ri-heart-pulse-line me-1"></i> Benefits Retrieval</h6>
                                    </div>
                                    <p class="text-muted small mb-2">Test member benefits lookup</p>
                                    <button class="btn btn-sm btn-outline-primary w-100" onclick="testBenefitsEndpoint()">
                                        <i class="ri-play-mini-line"></i> Test Endpoint
                                    </button>
                                    <div id="benefitsResults" class="mt-2"></div>
                                </div>

                                <div class="endpoint-test-card mb-0">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <h6 class="mb-0"><i class="ri-server-line me-1"></i> Server Connection</h6>
                                    </div>
                                    <p class="text-muted small mb-2">Test server reachability</p>
                                    <button class="btn btn-sm btn-outline-primary w-100" onclick="testNetwork()">
                                        <i class="ri-play-mini-line"></i> Test Connection
                                    </button>
                                    <div id="networkResults" class="mt-2"></div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>

        <?php include 'layouts/footer.php'; ?>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>

    <script>
    let testHistory = [];

    // Run all comprehensive tests
    $('#runAllTestsBtn').click(function() {
        const btn = $(this);
        btn.prop('disabled', true).html('<i class="ri-loader-4-line spinner-border spinner-border-sm me-1"></i> Running Tests...');
        
        $('#testResults').html(`
            <div class="test-step pending" id="step1">
                <div class="d-flex justify-content-between align-items-center">
                    <div><i class="ri-checkbox-blank-circle-line me-2"></i><strong>Step 1:</strong> Testing Server Connection</div>
                    <span class="badge bg-secondary">Pending</span>
                </div>
                <div class="test-detail" id="step1-detail"></div>
            </div>
            <div class="test-step pending" id="step2">
                <div class="d-flex justify-content-between align-items-center">
                    <div><i class="ri-checkbox-blank-circle-line me-2"></i><strong>Step 2:</strong> Testing Authentication</div>
                    <span class="badge bg-secondary">Pending</span>
                </div>
                <div class="test-detail" id="step2-detail"></div>
            </div>
            <div class="test-step pending" id="step3">
                <div class="d-flex justify-content-between align-items-center">
                    <div><i class="ri-checkbox-blank-circle-line me-2"></i><strong>Step 3:</strong> Testing Member Endpoint</div>
                    <span class="badge bg-secondary">Pending</span>
                </div>
                <div class="test-detail" id="step3-detail"></div>
            </div>
            <div class="test-step pending" id="step4">
                <div class="d-flex justify-content-between align-items-center">
                    <div><i class="ri-checkbox-blank-circle-line me-2"></i><strong>Step 4:</strong> Testing Visit Endpoint</div>
                    <span class="badge bg-secondary">Pending</span>
                </div>
                <div class="test-detail" id="step4-detail"></div>
            </div>
            <div class="test-step pending" id="step5">
                <div class="d-flex justify-content-between align-items-center">
                    <div><i class="ri-checkbox-blank-circle-line me-2"></i><strong>Step 5:</strong> Testing Benefits Endpoint</div>
                    <span class="badge bg-secondary">Pending</span>
                </div>
                <div class="test-detail" id="step5-detail"></div>
            </div>
        `);
        
        // Run tests sequentially
        runTestSequence()
            .finally(() => {
                btn.prop('disabled', false).html('<i class="ri-play-circle-line"></i> Run All Tests');
            });
    });

    async function runTestSequence() {
        // Test 1: Server Connection
        await runTest('step1', 'Server Connection', async () => {
            const response = await $.ajax({
                url: 'api/smart/test_connection.php',
                method: 'POST',
                dataType: 'json',
                data: { test_type: 'server' }
            });
            return response;
        });
        
        // Test 2: Authentication
        await runTest('step2', 'Authentication', async () => {
            const response = await $.ajax({
                url: 'api/smart/test_connection.php',
                method: 'POST',
                dataType: 'json',
                data: { test_type: 'auth' }
            });
            return response;
        });
        
        // Test 3: Member Endpoint
        await runTest('step3', 'Member Endpoint', async () => {
            const response = await $.ajax({
                url: 'api/smart/test_connection.php',
                method: 'POST',
                dataType: 'json',
                data: { test_type: 'member' }
            });
            return response;
        });
        
        // Test 4: Visit Endpoint
        await runTest('step4', 'Visit Endpoint', async () => {
            const response = await $.ajax({
                url: 'api/smart/test_connection.php',
                method: 'POST',
                dataType: 'json',
                data: { test_type: 'visit' }
            });
            return response;
        });
        
        // Test 5: Benefits Endpoint
        await runTest('step5', 'Benefits Endpoint', async () => {
            const response = await $.ajax({
                url: 'api/smart/test_connection.php',
                method: 'POST',
                dataType: 'json',
                data: { test_type: 'benefits' }
            });
            return response;
        });
    }

    async function runTest(stepId, testName, testFn) {
        const step = $(`#${stepId}`);
        const detail = $(`#${stepId}-detail`);
        const startTime = Date.now();
        
        // Mark as running
        step.removeClass('pending').addClass('running');
        step.find('.badge').removeClass('bg-secondary').addClass('bg-warning text-dark').text('Running...');
        step.find('i').first().removeClass('ri-checkbox-blank-circle-line').addClass('ri-loader-4-line spinner-border spinner-border-sm');
        
        try {
            const result = await testFn();
            const duration = Date.now() - startTime;
            
            if (result.success) {
                step.removeClass('running').addClass('success');
                step.find('.badge').removeClass('bg-warning text-dark').addClass('bg-success').text('Passed');
                step.find('i').first().removeClass('ri-loader-4-line spinner-border spinner-border-sm').addClass('ri-checkbox-circle-line');
                detail.html(`<i class="ri-check-line text-success me-1"></i> ${result.message} <span class="text-muted">(${duration}ms)</span>`);
                
                addToHistory(testName, 'Success', duration, result.message);
            } else {
                throw new Error(result.message);
            }
        } catch (error) {
            const duration = Date.now() - startTime;
            step.removeClass('running').addClass('failed');
            step.find('.badge').removeClass('bg-warning text-dark').addClass('bg-danger').text('Failed');
            step.find('i').first().removeClass('ri-loader-4-line spinner-border spinner-border-sm').addClass('ri-close-circle-line');
            detail.html(`<i class="ri-close-line text-danger me-1"></i> ${error.message} <span class="text-muted">(${duration}ms)</span>`);
            
            addToHistory(testName, 'Failed', duration, error.message);
        }
    }

    // Test Authentication Only
    $('#testAuthBtn').click(function() {
        const btn = $(this);
        btn.prop('disabled', true).html('<i class="ri-loader-4-line spinner-border spinner-border-sm me-1"></i> Testing...');
        
        $.ajax({
            url: 'api/smart/test_connection.php',
            method: 'POST',
            dataType: 'json',
            data: { test_type: 'auth' },
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Authentication Successful',
                        html: `<p class="mb-0">${response.message}</p>`,
                        confirmButtonColor: '#2d7a2d'
                    });
                    addToHistory('Authentication', 'Success', 0, response.message);
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Authentication Failed',
                        text: response.message
                    });
                    addToHistory('Authentication', 'Failed', 0, response.message);
                }
            },
            error: function(xhr) {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Failed to connect to test endpoint'
                });
            },
            complete: function() {
                btn.prop('disabled', false).html('<i class="ri-key-line"></i> Test Authentication');
            }
        });
    });

    // Test Latency
    $('#testLatencyBtn').click(function() {
        const btn = $(this);
        btn.prop('disabled', true).html('<i class="ri-loader-4-line spinner-border spinner-border-sm me-1"></i> Measuring...');
        
        const startTime = Date.now();
        
        $.ajax({
            url: 'api/smart/test_connection.php',
            method: 'POST',
            dataType: 'json',
            data: { test_type: 'latency' },
            success: function(response) {
                const duration = Date.now() - startTime;
                const quality = duration < 200 ? 'Excellent' : duration < 500 ? 'Good' : duration < 1000 ? 'Fair' : 'Poor';
                const alertClass = duration < 500 ? 'success' : duration < 1000 ? 'warning' : 'danger';
                
                Swal.fire({
                    icon: alertClass === 'success' ? 'success' : alertClass === 'warning' ? 'warning' : 'error',
                    title: 'Latency Test Result',
                    html: `
                        <div class="text-center">
                            <div class="display-4 mb-2">${duration}ms</div>
                            <p class="text-muted mb-0">Connection quality: <strong>${quality}</strong></p>
                        </div>
                    `,
                    confirmButtonColor: '#2d7a2d'
                });
                
                addToHistory('Latency Test', 'Success', duration, `${quality} (${duration}ms)`);
            },
            error: function() {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Failed to measure latency'
                });
            },
            complete: function() {
                btn.prop('disabled', false).html('<i class="ri-time-line"></i> Measure Latency');
            }
        });
    });

    // Individual endpoint tests
    function testNetwork() {
        $('#networkResults').html('<div class="spinner-border spinner-border-sm text-primary"></div>');
        
        $.ajax({
            url: 'api/smart/test_connection.php',
            method: 'POST',
            dataType: 'json',
            data: { test_type: 'server' },
            success: function(response) {
                const alertClass = response.success ? 'success' : 'danger';
                const icon = response.success ? 'check-line' : 'close-line';
                $('#networkResults').html(`
                    <div class="alert alert-${alertClass} border-0 mb-0 mt-2 py-2 px-3">
                        <small><i class="ri-${icon} me-1"></i> ${response.message}</small>
                    </div>
                `);
                addToHistory('Server Connection', response.success ? 'Success' : 'Failed', 0, response.message);
            },
            error: function() {
                $('#networkResults').html(`
                    <div class="alert alert-danger border-0 mb-0 mt-2 py-2 px-3">
<small><i class="ri-close-line me-1"></i> Connection failed</small>
</div>
`);
}
});
}
function testMemberEndpoint() {
    $('#memberResults').html('<div class="spinner-border spinner-border-sm text-primary"></div>');
    
    $.ajax({
        url: 'api/smart/test_connection.php',
        method: 'POST',
        dataType: 'json',
        data: { test_type: 'member' },
        success: function(response) {
            const alertClass = response.success ? 'success' : 'danger';
            const icon = response.success ? 'check-line' : 'close-line';
            $('#memberResults').html(`
                <div class="alert alert-${alertClass} border-0 mb-0 py-2 px-3">
                    <small><i class="ri-${icon} me-1"></i> ${response.message}</small>
                </div>
            `);
            addToHistory('Member Endpoint', response.success ? 'Success' : 'Failed', 0, response.message);
        }
    });
}

function testVisitEndpoint() {
    $('#visitResults').html('<div class="spinner-border spinner-border-sm text-primary"></div>');
    
    $.ajax({
        url: 'api/smart/test_connection.php',
        method: 'POST',
        dataType: 'json',
        data: { test_type: 'visit' },
        success: function(response) {
            const alertClass = response.success ? 'success' : 'danger';
            const icon = response.success ? 'check-line' : 'close-line';
            $('#visitResults').html(`
                <div class="alert alert-${alertClass} border-0 mb-0 py-2 px-3">
                    <small><i class="ri-${icon} me-1"></i> ${response.message}</small>
                </div>
            `);
            addToHistory('Visit Endpoint', response.success ? 'Success' : 'Failed', 0, response.message);
        }
    });
}

function testBenefitsEndpoint() {
    $('#benefitsResults').html('<div class="spinner-border spinner-border-sm text-primary"></div>');
    
    $.ajax({
        url: 'api/smart/test_connection.php',
        method: 'POST',
        dataType: 'json',
        data: { test_type: 'benefits' },
        success: function(response) {
            const alertClass = response.success ? 'success' : 'danger';
            const icon = response.success ? 'check-line' : 'close-line';
            $('#benefitsResults').html(`
                <div class="alert alert-${alertClass} border-0 mb-0 py-2 px-3">
                    <small><i class="ri-${icon} me-1"></i> ${response.message}</small>
                </div>
            `);
            addToHistory('Benefits Endpoint', response.success ? 'Success' : 'Failed', 0, response.message);
        }
    });
}

function addToHistory(testType, status, responseTime, details) {
    const now = new Date();
    const timestamp = now.toLocaleString();
    
    testHistory.unshift({
        timestamp,
        testType,
        status,
        responseTime,
        details
    });
    
    // Keep only last 20 tests
    if (testHistory.length > 20) {
        testHistory.pop();
    }
    
    updateHistoryTable();
}

function updateHistoryTable() {
    const tbody = $('#testHistoryBody');
    
    if (testHistory.length === 0) {
        tbody.html('<tr><td colspan="5" class="text-center text-muted py-4">No tests run yet</td></tr>');
        return;
    }
    
    let html = '';
    testHistory.forEach(test => {
        const statusBadge = test.status === 'Success' 
            ? '<span class="badge bg-success-subtle text-success">Success</span>'
            : '<span class="badge bg-danger-subtle text-danger">Failed</span>';
        
        html += `
            <tr>
                <td class="small">${test.timestamp}</td>
                <td>${test.testType}</td>
                <td>${statusBadge}</td>
                <td>${test.responseTime > 0 ? test.responseTime + 'ms' : '-'}</td>
                <td class="small text-muted">${test.details}</td>
            </tr>
        `;
    });
    
    tbody.html(html);
}

// Clear history
$('#clearHistoryBtn').click(function() {
    Swal.fire({
        title: 'Clear Test History?',
        text: 'This will remove all test history records',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc3545',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Yes, clear it'
    }).then((result) => {
        if (result.isConfirmed) {
            testHistory = [];
            updateHistoryTable();
            Swal.fire({
                icon: 'success',
                title: 'Cleared',
                text: 'Test history has been cleared',
                timer: 1500,
                showConfirmButton: false
            });
        }
    });
});
</script>
</body>
</html>