<?php
/**
 * ============================================================================
 * test-connection.php - Connection & API Diagnostic Tool
 * ============================================================================
 * Place this in your admin folder and access it to diagnose issues
 */

define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html>
<head>
    <title>AIMS Connection Diagnostics</title>
    <style>
        body { font-family: monospace; padding: 20px; background: #f5f5f5; }
        .test { margin: 10px 0; padding: 10px; background: white; border-left: 4px solid #ccc; }
        .pass { border-color: #22c55e; }
        .fail { border-color: #ef4444; }
        .warn { border-color: #f59e0b; }
        h2 { color: #333; }
        pre { background: #f9f9f9; padding: 10px; overflow-x: auto; }
        .status { font-weight: bold; }
    </style>
</head>
<body>

<h1>🔧 AIMS Connection Diagnostics</h1>
<p>Running comprehensive tests...</p>

<?php

// Test 1: Database Connection
echo '<div class="test">';
echo '<h2>Test 1: Database Connection</h2>';
try {
    // Try multiple connection methods
    $db = null;
    $method = 'unknown';
    
    // Method 1: App\Database
    if (class_exists('\App\Database')) {
        try {
            $db = \App\Database::getInstance()->getConnection();
            $method = 'App\Database::getInstance()';
        } catch (Exception $e) {
            echo '<p class="warn">⚠️ App\Database failed: ' . $e->getMessage() . '</p>';
        }
    }
    
    // Method 2: Database class
    if (!$db && class_exists('Database')) {
        try {
            $database = new Database();
            $db = $database->getConnection();
            $method = 'new Database()';
        } catch (Exception $e) {
            echo '<p class="warn">⚠️ Database class failed: ' . $e->getMessage() . '</p>';
        }
    }
    
    // Method 3: Direct PDO
    if (!$db) {
        try {
            $db = new PDO(
                "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET,
                DB_USER,
                DB_PASS,
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
            );
            $method = 'Direct PDO';
        } catch (PDOException $e) {
            echo '<p class="fail">❌ Direct PDO failed: ' . $e->getMessage() . '</p>';
        }
    }
    
    if ($db) {
        echo '<p class="status pass">✅ Connected via: ' . $method . '</p>';
        
        // Test query
        $stmt = $db->query("SELECT COUNT(*) as c FROM users");
        $result = $stmt->fetch();
        echo '<p class="pass">✅ Query successful. Found ' . $result['c'] . ' users.</p>';
    } else {
        echo '<p class="status fail">❌ All connection methods failed!</p>';
    }
} catch (Exception $e) {
    echo '<p class="fail">❌ Database error: ' . $e->getMessage() . '</p>';
}
echo '</div>';

// Test 2: Config Constants
echo '<div class="test">';
echo '<h2>Test 2: Configuration Constants</h2>';
$constants = ['APP_URL', 'DB_HOST', 'DB_NAME', 'DB_USER', 'DB_CHARSET'];
foreach ($constants as $const) {
    if (defined($const)) {
        $value = constant($const);
        // Hide password
        if ($const === 'DB_PASS') $value = '***hidden***';
        echo '<p class="pass">✅ ' . $const . ' = ' . $value . '</p>';
    } else {
        echo '<p class="fail">❌ ' . $const . ' not defined!</p>';
    }
}
echo '</div>';

// Test 3: Helper Functions
echo '<div class="test">';
echo '<h2>Test 3: Helper Functions</h2>';
$functions = ['isLoggedIn', 'hasAdminAccess', 'jsonError', 'jsonSuccess', 'sanitize', 'validatePhone', 'hashPassword'];
foreach ($functions as $func) {
    if (function_exists($func)) {
        echo '<p class="pass">✅ ' . $func . '() exists</p>';
    } else {
        echo '<p class="fail">❌ ' . $func . '() missing!</p>';
    }
}
echo '</div>';

// Test 4: Location Data
echo '<div class="test">';
echo '<h2>Test 4: Location Hierarchy Data</h2>';
if ($db) {
    try {
        $tables = ['regions', 'districts', 'subcounties', 'parishes', 'villages'];
        foreach ($tables as $table) {
            $stmt = $db->query("SELECT COUNT(*) as c FROM $table");
            $result = $stmt->fetch();
            $count = $result['c'];
            if ($count > 0) {
                echo '<p class="pass">✅ ' . $table . ': ' . $count . ' records</p>';
            } else {
                echo '<p class="warn">⚠️ ' . $table . ': EMPTY (run schema_verification.sql)</p>';
            }
        }
    } catch (Exception $e) {
        echo '<p class="fail">❌ Error checking tables: ' . $e->getMessage() . '</p>';
    }
}
echo '</div>';

// Test 5: Extension Roles
echo '<div class="test">';
echo '<h2>Test 5: Extension Roles</h2>';
if ($db) {
    try {
        $stmt = $db->query("SELECT COUNT(*) as c FROM extension_roles WHERE is_active = 1");
        $result = $stmt->fetch();
        $count = $result['c'];
        if ($count > 0) {
            echo '<p class="pass">✅ Found ' . $count . ' active extension roles</p>';
            
            // Show roles
            $stmt = $db->query("SELECT role_name, role_level FROM extension_roles WHERE is_active = 1 ORDER BY role_level");
            while ($role = $stmt->fetch()) {
                echo '<p style="margin-left: 20px;">→ ' . $role['role_name'] . ' (' . $role['role_level'] . ')</p>';
            }
        } else {
            echo '<p class="fail">❌ No active extension roles (run schema_verification.sql)</p>';
        }
    } catch (Exception $e) {
        echo '<p class="fail">❌ Error: ' . $e->getMessage() . '</p>';
    }
}
echo '</div>';

// Test 6: API Files
echo '<div class="test">';
echo '<h2>Test 6: API Files Existence</h2>';
$apiFiles = [
    'admin-user-management.php',
    'extension-management.php',
    'locations.php'
];
foreach ($apiFiles as $file) {
    $path = __DIR__ . '/../api/' . $file;
    if (file_exists($path)) {
        echo '<p class="pass">✅ /api/' . $file . ' exists (' . filesize($path) . ' bytes)</p>';
    } else {
        echo '<p class="fail">❌ /api/' . $file . ' MISSING!</p>';
    }
}
echo '</div>';

// Test 7: Direct API Test
echo '<div class="test">';
echo '<h2>Test 7: API Endpoint Test</h2>';
echo '<p>Testing locations API...</p>';

try {
    // Simulate API call
    $_GET['action'] = 'get_regions';
    ob_start();
    include __DIR__ . '/../api/locations.php';
    $output = ob_get_clean();
    
    $response = json_decode($output, true);
    if ($response && isset($response['success'])) {
        if ($response['success']) {
            echo '<p class="pass">✅ Locations API works! Found ' . count($response['data']) . ' regions</p>';
        } else {
            echo '<p class="warn">⚠️ API responded but with error: ' . ($response['message'] ?? 'unknown') . '</p>';
        }
    } else {
        echo '<p class="fail">❌ Invalid API response: ' . substr($output, 0, 200) . '</p>';
    }
} catch (Exception $e) {
    echo '<p class="fail">❌ API test failed: ' . $e->getMessage() . '</p>';
}
echo '</div>';

// Test 8: jQuery & JavaScript
echo '<div class="test">';
echo '<h2>Test 8: JavaScript Test</h2>';
echo '<p>Click the button to test AJAX:</p>';
echo '<button onclick="testAjax()" style="padding: 10px 20px; cursor: pointer;">Test AJAX Connection</button>';
echo '<div id="ajaxResult" style="margin-top: 10px;"></div>';
echo '</div>';

// Test 9: Session & Auth
echo '<div class="test">';
echo '<h2>Test 9: Session & Authentication</h2>';
if (session_status() === PHP_SESSION_ACTIVE) {
    echo '<p class="pass">✅ Session active</p>';
    echo '<p>Session ID: ' . session_id() . '</p>';
    
    if (isLoggedIn()) {
        echo '<p class="pass">✅ User is logged in</p>';
        if (hasAdminAccess()) {
            echo '<p class="pass">✅ User has admin access</p>';
        } else {
            echo '<p class="fail">❌ User DOES NOT have admin access</p>';
        }
    } else {
        echo '<p class="warn">⚠️ User is NOT logged in (this is normal if you\'re testing while logged out)</p>';
    }
} else {
    echo '<p class="fail">❌ Session not active!</p>';
}
echo '</div>';

?>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
const APP_URL = '<?php echo APP_URL; ?>';

function testAjax() {
    const resultDiv = document.getElementById('ajaxResult');
    resultDiv.innerHTML = '<p>Testing...</p>';
    
    jQuery.ajax({
        url: APP_URL + '/api/locations.php',
        method: 'GET',
        data: { action: 'get_regions' },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                resultDiv.innerHTML = '<p class="pass">✅ AJAX SUCCESS! Found ' + response.data.length + ' regions</p>';
            } else {
                resultDiv.innerHTML = '<p class="fail">❌ API Error: ' + response.message + '</p>';
            }
        },
        error: function(xhr, status, error) {
            resultDiv.innerHTML = '<p class="fail">❌ AJAX ERROR: ' + status + ' - ' + error + '</p>' +
                                '<p>Status Code: ' + xhr.status + '</p>' +
                                '<pre>' + xhr.responseText.substring(0, 500) + '</pre>';
        }
    });
}
</script>

<div style="margin-top: 30px; padding: 20px; background: #fff3cd; border-left: 4px solid #f59e0b;">
    <h2>📋 Next Steps Based on Results:</h2>
    <ol>
        <li><strong>If Database Connection Failed:</strong> Check config.php and database credentials</li>
        <li><strong>If Location Tables Empty:</strong> Run schema_verification.sql in phpMyAdmin</li>
        <li><strong>If Extension Roles Empty:</strong> Run schema_verification.sql in phpMyAdmin</li>
        <li><strong>If API Files Missing:</strong> Copy the new API files to /api/ folder</li>
        <li><strong>If AJAX Test Failed:</strong> Check browser console (F12) for JavaScript errors</li>
        <li><strong>If Not Logged In:</strong> Login first, then run this test again</li>
    </ol>
</div>

<div style="margin-top: 20px; padding: 20px; background: #e0f2fe; border-left: 4px solid #0ea5e9;">
    <h2>🔍 Check Your Error Logs:</h2>
    <p><strong>PHP Error Log:</strong></p>
    <pre><?php
    $errorLog = ini_get('error_log');
    if ($errorLog && file_exists($errorLog)) {
        echo "Location: $errorLog\n";
        echo "Last 10 lines:\n";
        echo shell_exec("tail -n 10 " . escapeshellarg($errorLog));
    } else {
        echo "Error log not found. Check: /var/log/php/error.log or your server's error log location";
    }
    ?></pre>
    
    <p><strong>Browser Console:</strong> Press F12 and check Console tab for JavaScript errors</p>
</div>

</body>
</html>