<?php
header('Content-Type: application/json');

echo "Testing Database Connection...\n\n";

// Test 1: Check if database.php exists
$configPath = __DIR__ . '/../config/database.php';
echo "Config path: $configPath\n";

if (file_exists($configPath)) {
    echo "✅ Database config file exists\n";
} else {
    echo "❌ Database config file not found\n";
    exit;
}

// Test 2: Try to include database.php
try {
    require_once $configPath;
    echo "✅ Database config loaded successfully\n";
} catch (Exception $e) {
    echo "❌ Error loading database config: " . $e->getMessage() . "\n";
    exit;
}

// Test 3: Check if getDBConnection function exists
if (function_exists('getDBConnection')) {
    echo "✅ getDBConnection function exists\n";
} else {
    echo "❌ getDBConnection function not found\n";
    exit;
}

// Test 4: Try to connect to database
try {
    $pdo = getDBConnection();
    echo "✅ Database connection successful\n";
    
    // Test 5: Check if users table exists
    $stmt = $pdo->query("SHOW TABLES LIKE 'users'");
    if ($stmt->rowCount() > 0) {
        echo "✅ Users table exists\n";
        
        // Test 6: Check table structure
        $stmt = $pdo->query("DESCRIBE users");
        $columns = $stmt->fetchAll();
        echo "Users table columns:\n";
        foreach ($columns as $column) {
            echo "  - {$column['Field']} ({$column['Type']})\n";
        }
        
        // Test 7: Check if test user exists
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM users");
        $stmt->execute();
        $result = $stmt->fetch();
        echo "Total users in database: {$result['count']}\n";
        
    } else {
        echo "❌ Users table does not exist\n";
    }
    
} catch (Exception $e) {
    echo "❌ Database connection failed: " . $e->getMessage() . "\n";
}
?> 