<?php
/**
 * TEST_CONNECTION.php - Test if existing system functions work
 * Place in root directory and visit: http://yourdomain.com/TEST_CONNECTION.php
 */

// Step 1: Test config loading
echo "<h2>Step 1: Testing Config Load</h2>";
try {
    define('AIMS_ACCESS', true);
    require_once __DIR__ . '/config/config.php';
    echo "✅ Config loaded successfully<br>";
} catch (Exception $e) {
    die("❌ Config failed: " . $e->getMessage());
}

// Step 2: Test Database connection
echo "<h2>Step 2: Testing Database Connection</h2>";
try {
    $database = new Database();
    $db = $database->getConnection();
    if ($db) {
        echo "✅ Database connected successfully<br>";
    } else {
        echo "❌ Database connection returned null<br>";
    }
} catch (Exception $e) {
    die("❌ Database failed: " . $e->getMessage());
}

// Step 3: Test helper functions
echo "<h2>Step 3: Testing Helper Functions</h2>";
$functions = [
    'isLoggedIn',
    'hasAdminAccess', 
    'getUserId',
    'validatePhone',
    'hashPassword',
    'sanitize',
    'jsonError',
    'jsonSuccess',
    'logActivity'
];

foreach ($functions as $func) {
    if (function_exists($func)) {
        echo "✅ $func() exists<br>";
    } else {
        echo "❌ $func() NOT FOUND<br>";
    }
}

// Step 4: Test database tables
echo "<h2>Step 4: Testing Extension Tables</h2>";
$tables = [
    'extension_roles',
    'extension_assignments',
    'extension_officer_profiles',
    'regions',
    'districts',
    'subcounties',
    'parishes',
    'villages'
];

foreach ($tables as $table) {
    try {
        $stmt = $db->query("SELECT COUNT(*) as count FROM $table");
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        echo "✅ $table exists ({$row['count']} records)<br>";
    } catch (Exception $e) {
        echo "❌ $table missing or error: " . $e->getMessage() . "<br>";
    }
}

// Step 5: Test API endpoint
echo "<h2>Step 5: Testing API Response Format</h2>";
echo "<pre>";
echo "Expected jsonError format:\n";
echo json_encode(['success' => false, 'message' => 'Test error'], JSON_PRETTY_PRINT);
echo "\n\nExpected jsonSuccess format:\n";
echo json_encode(['success' => true, 'message' => 'Test success', 'data' => []], JSON_PRETTY_PRINT);
echo "</pre>";

echo "<h2>✅ All Tests Complete!</h2>";
echo "<p>If all tests pass, the system is ready. If any fail, check the error messages above.</p>";