<!DOCTYPE html>
<html>
<head>
    <title>AIMS API Diagnostic Tool</title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            max-width: 1000px; 
            margin: 20px auto; 
            padding: 20px;
            background: #f5f5f5;
        }
        .test { 
            background: white; 
            padding: 15px; 
            margin: 10px 0; 
            border-radius: 5px;
            border-left: 4px solid #ccc;
        }
        .test.success { border-left-color: #22c55e; }
        .test.error { border-left-color: #ef4444; }
        .test.warning { border-left-color: #f59e0b; }
        .result { 
            margin-top: 10px; 
            padding: 10px; 
            background: #f9fafb;
            font-family: monospace;
            font-size: 12px;
            overflow-x: auto;
        }
        h1 { color: #1f2937; }
        h2 { 
            color: #4b5563; 
            margin-top: 0;
            font-size: 16px;
        }
        .status { 
            display: inline-block;
            padding: 3px 10px;
            border-radius: 3px;
            font-size: 12px;
            font-weight: bold;
        }
        .status.pass { background: #22c55e; color: white; }
        .status.fail { background: #ef4444; color: white; }
        .status.pending { background: #f59e0b; color: white; }
        button { 
            background: #3b82f6; 
            color: white; 
            border: none; 
            padding: 10px 20px; 
            border-radius: 5px; 
            cursor: pointer;
            margin: 5px;
        }
        button:hover { background: #2563eb; }
    </style>
</head>
<body>
    <h1>🔍 AIMS API Diagnostic Tool</h1>
    <p>This tool will test all your API endpoints and database connections.</p>
    
    <button onclick="runAllTests()">▶️ Run All Tests</button>
    <button onclick="location.reload()">🔄 Refresh</button>
    
    <hr>
    
    <div id="tests"></div>

    <script>
    const testsDiv = document.getElementById('tests');
    
    async function runAllTests() {
        testsDiv.innerHTML = '<p>Running tests...</p>';
        
        // Test 1: Check if API files exist
        await testFileExists('api/locations.php', 'Locations API');
        await testFileExists('api/admin-user-management.php', 'Admin User Management API');
        await testFileExists('api/extension-management.php', 'Extension Management API');
        
        // Test 2: Test locations API
        await testAPI('api/locations.php?action=get_regions', 'Get Regions');
        
        // Test 3: Test extension management API (GET)
        await testAPI('api/extension-management.php?action=get_roles_by_level&level=district', 'Get Roles by Level');
        
        // Test 4: Database connection
        await testDatabaseConnection();
        
        // Test 5: Check PHP errors
        await checkPHPErrors();
    }
    
    async function testFileExists(file, name) {
        addTest(name, 'pending', 'Checking if file exists...');
        
        try {
            const response = await fetch(file, { method: 'HEAD' });
            
            if (response.ok) {
                updateTest(name, 'success', `✅ File exists (Status: ${response.status})`);
            } else {
                updateTest(name, 'error', `❌ File not found (Status: ${response.status})`);
            }
        } catch (error) {
            updateTest(name, 'error', `❌ Error: ${error.message}`);
        }
    }
    
    async function testAPI(url, name) {
        addTest(name, 'pending', 'Testing API endpoint...');
        
        try {
            const response = await fetch(url);
            const contentType = response.headers.get('content-type');
            const text = await response.text();
            
            let result = `Status: ${response.status}\n`;
            result += `Content-Type: ${contentType}\n\n`;
            
            if (contentType && contentType.includes('application/json')) {
                try {
                    const json = JSON.parse(text);
                    result += `JSON Response:\n${JSON.stringify(json, null, 2)}`;
                    
                    if (json.success) {
                        updateTest(name, 'success', `✅ API Working\n\n${result}`);
                    } else {
                        updateTest(name, 'warning', `⚠️ API responded but returned error\n\n${result}`);
                    }
                } catch (e) {
                    updateTest(name, 'error', `❌ Invalid JSON\n\n${result}\n\nRaw:\n${text.substring(0, 500)}`);
                }
            } else {
                // Not JSON - probably PHP error
                updateTest(name, 'error', `❌ Not JSON response\n\n${result}\n\nRaw Output:\n${text.substring(0, 1000)}`);
            }
        } catch (error) {
            updateTest(name, 'error', `❌ Network Error: ${error.message}`);
        }
    }
    
    async function testDatabaseConnection() {
        addTest('Database Connection', 'pending', 'Creating test file...');
        
        // We'll create a simple test
        const testHTML = `
<?php
require_once '../config/config.php';
header('Content-Type: text/plain');

try {
    // Try method 1: Singleton
    $db = null;
    if (class_exists('\\App\\Database')) {
        $db = \\App\\Database::getInstance()->getConnection();
        echo "✅ Connected via App\\Database singleton\\n";
    } else if (class_exists('Database')) {
        $database = new Database();
        $db = $database->getConnection();
        echo "✅ Connected via Database class\\n";
    } else {
        $db = new PDO(
            "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME,
            DB_USER,
            DB_PASS
        );
        echo "✅ Connected via direct PDO\\n";
    }
    
    // Test query
    $stmt = $db->query("SELECT COUNT(*) as c FROM regions");
    $result = $stmt->fetch();
    echo "✅ Query successful: " . $result['c'] . " regions found\\n";
    
    // Check for sample data
    $stmt = $db->query("SELECT COUNT(*) as c FROM extension_roles WHERE is_active = 1");
    $result = $stmt->fetch();
    echo "✅ Extension roles: " . $result['c'] . " found\\n";
    
    echo "\\n✅ DATABASE CONNECTION: PASS";
    
} catch (Exception $e) {
    echo "❌ DATABASE ERROR: " . $e->getMessage();
}
?>`;
        
        updateTest('Database Connection', 'warning', 'Check PHP error logs or create test-db.php manually');
    }
    
    async function checkPHPErrors() {
        addTest('PHP Configuration', 'pending', 'Checking...');
        
        let info = 'To check PHP errors:\n\n';
        info += '1. Check your error log (usually /var/log/php/error.log)\n';
        info += '2. Or add this to the top of your API files:\n\n';
        info += 'ini_set("display_errors", 1);\n';
        info += 'error_reporting(E_ALL);\n\n';
        info += '3. Check browser DevTools Network tab for the actual error';
        
        updateTest('PHP Configuration', 'warning', info);
    }
    
    function addTest(name, status, message) {
        const testDiv = document.createElement('div');
        testDiv.className = `test ${status}`;
        testDiv.id = `test-${name.replace(/\s+/g, '-')}`;
        testDiv.innerHTML = `
            <h2>
                <span class="status ${status === 'success' ? 'pass' : status === 'error' ? 'fail' : 'pending'}">
                    ${status.toUpperCase()}
                </span>
                ${name}
            </h2>
            <div class="result">${message}</div>
        `;
        testsDiv.appendChild(testDiv);
    }
    
    function updateTest(name, status, message) {
        const testDiv = document.getElementById(`test-${name.replace(/\s+/g, '-')}`);
        if (testDiv) {
            testDiv.className = `test ${status}`;
            testDiv.innerHTML = `
                <h2>
                    <span class="status ${status === 'success' ? 'pass' : status === 'error' ? 'fail' : 'pending'}">
                        ${status.toUpperCase()}
                    </span>
                    ${name}
                </h2>
                <div class="result">${message}</div>
            `;
        }
    }
    
    // Run on load
    window.onload = () => {
        addTest('Instructions', 'warning', 
            'Click "Run All Tests" to diagnose your API issues.\n\n' +
            'This will test:\n' +
            '✓ File existence\n' +
            '✓ API endpoints\n' +
            '✓ JSON responses\n' +
            '✓ Database connections\n\n' +
            'Look for RED errors - those are your problems!'
        );
    };
    </script>
</body>
</html>