<?php
/**
 * Database Connection Test
 * Place this file in: /Applications/XAMPP/xamppfiles/htdocs/HMSPOS/test_connection.php
 * Access at: http://localhost/HMSPOS/test_connection.php
 */

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Define base path
define('BASE_PATH', __DIR__);

echo "<!DOCTYPE html>
<html>
<head>
    <title>Ruhondo HMS - Database Connection Test</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
        .container { max-width: 800px; margin: 0 auto; background: white; padding: 20px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
        h1 { color: #333; border-bottom: 2px solid #007bff; padding-bottom: 10px; }
        .success { color: green; background: #e8f5e8; padding: 10px; border-radius: 3px; margin: 10px 0; border-left: 4px solid green; }
        .error { color: red; background: #ffe8e8; padding: 10px; border-radius: 3px; margin: 10px 0; border-left: 4px solid red; }
        .warning { color: orange; background: #fff3e0; padding: 10px; border-radius: 3px; margin: 10px 0; border-left: 4px solid orange; }
        .info { background: #e3f2fd; padding: 10px; border-radius: 3px; margin: 10px 0; border-left: 4px solid blue; }
        pre { background: #f4f4f4; padding: 10px; border-radius: 3px; overflow-x: auto; }
        .step { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
    </style>
</head>
<body>
    <div class='container'>
        <h1>🏨 Ruhondo Beach Resort HMS - Database Connection Test</h1>";

// Step 1: Load configuration
echo "<div class='step'>";
echo "<h2>Step 1: Loading Configuration</h2>";

$config_file = __DIR__ . '/config/config.php';
if (file_exists($config_file)) {
    require_once $config_file;
    echo "<div class='success'>✓ config.php loaded successfully</div>";
    
    echo "<h3>Configuration Constants:</h3>";
    echo "<ul>";
    echo "<li><strong>BASE_URL:</strong> " . (defined('BASE_URL') ? BASE_URL : 'Not defined') . "</li>";
    echo "<li><strong>BASE_PATH:</strong> " . (defined('BASE_PATH') ? BASE_PATH : 'Not defined') . "</li>";
    echo "<li><strong>DB_HOST:</strong> " . (defined('DB_HOST') ? DB_HOST : 'Not defined') . "</li>";
    echo "<li><strong>DB_NAME:</strong> " . (defined('DB_NAME') ? DB_NAME : 'Not defined') . "</li>";
    echo "<li><strong>DB_USER:</strong> " . (defined('DB_USER') ? DB_USER : 'Not defined') . "</li>";
    echo "<li><strong>DB_PASS:</strong> " . (defined('DB_PASS') ? (empty(DB_PASS) ? '[empty]' : '[set]') : 'Not defined') . "</li>";
    echo "</ul>";
} else {
    echo "<div class='error'>✗ config.php not found at: $config_file</div>";
    exit;
}
echo "</div>";

// Step 2: Load database functions
echo "<div class='step'>";
echo "<h2>Step 2: Loading Database Functions</h2>";

$database_file = __DIR__ . '/config/database.php';
if (file_exists($database_file)) {
    require_once $database_file;
    echo "<div class='success'>✓ database.php loaded successfully</div>";
    
    // Check for required functions
    $required_functions = ['get_db_connection', 'db_query', 'db_fetch_all'];
    foreach ($required_functions as $func) {
        if (function_exists($func)) {
            echo "<div class='success'>✓ Function $func() exists</div>";
        } else {
            echo "<div class='error'>✗ Function $func() does not exist</div>";
        }
    }
} else {
    echo "<div class='error'>✗ database.php not found at: $database_file</div>";
    exit;
}
echo "</div>";

// Step 3: Test database connection
echo "<div class='step'>";
echo "<h2>Step 3: Testing Database Connection</h2>";

try {
    if (function_exists('get_db_connection')) {
        $pdo = get_db_connection();
        echo "<div class='success'>✓ Database connection established successfully!</div>";
        
        // Get database info
        $db_name = $pdo->query("SELECT DATABASE() as db")->fetch()['db'];
        echo "<p><strong>Connected to database:</strong> " . $db_name . "</p>";
        
        // Get MySQL version
        $version = $pdo->query("SELECT VERSION() as version")->fetch()['version'];
        echo "<p><strong>MySQL Version:</strong> " . $version . "</p>";
        
        // Test a simple query
        $result = $pdo->query("SHOW TABLES")->fetchAll();
        echo "<p><strong>Tables in database:</strong> " . count($result) . "</p>";
        
        if (count($result) > 0) {
            echo "<ul>";
            $count = 0;
            foreach ($result as $table) {
                $table_name = current($table);
                echo "<li>" . $table_name . "</li>";
                $count++;
                if ($count >= 10) {
                    echo "<li>... and " . (count($result) - 10) . " more</li>";
                    break;
                }
            }
            echo "</ul>";
        }
    } else {
        echo "<div class='error'>✗ get_db_connection() function not found</div>";
    }
} catch (PDOException $e) {
    echo "<div class='error'>✗ Database connection failed: " . $e->getMessage() . "</div>";
    
    // Show common issues
    echo "<h3>Common Issues:</h3>";
    echo "<ul>";
    if (strpos($e->getMessage(), 'Access denied') !== false) {
        echo "<li>Check your database username and password in config.php</li>";
    }
    if (strpos($e->getMessage(), 'Unknown database') !== false) {
        echo "<li>Database '" . DB_NAME . "' does not exist. Create it first.</li>";
    }
    if (strpos($e->getMessage(), 'Connection refused') !== false) {
        echo "<li>MySQL server is not running or host is incorrect</li>";
    }
    echo "</ul>";
}
echo "</div>";

// Step 4: Test log_message function
echo "<div class='step'>";
echo "<h2>Step 4: Testing Logging</h2>";

if (function_exists('log_message')) {
    try {
        log_message("Database connection test completed", "INFO");
        echo "<div class='success'>✓ log_message() works</div>";
        
        // Check log file
        if (defined('LOG_APP') && file_exists(LOG_APP)) {
            echo "<p><strong>Log file:</strong> " . LOG_APP . "</p>";
            echo "<p><strong>Log file size:</strong> " . filesize(LOG_APP) . " bytes</p>";
            echo "<p><strong>Last 5 log entries:</strong></p>";
            echo "<pre>";
            $lines = file(LOG_APP);
            $last_lines = array_slice($lines, -5);
            echo htmlspecialchars(implode('', $last_lines));
            echo "</pre>";
        }
    } catch (Exception $e) {
        echo "<div class='error'>✗ log_message() failed: " . $e->getMessage() . "</div>";
    }
} else {
    echo "<div class='warning'>⚠ log_message() function not available</div>";
}
echo "</div>";

// Step 5: Test a simple db_query
echo "<div class='step'>";
echo "<h2>Step 5: Testing db_query Function</h2>";

if (function_exists('db_query')) {
    try {
        $stmt = db_query("SELECT 1 as test");
        $result = $stmt->fetch();
        echo "<div class='success'>✓ db_query() works: " . $result['test'] . "</div>";
    } catch (Exception $e) {
        echo "<div class='error'>✗ db_query() failed: " . $e->getMessage() . "</div>";
    }
} else {
    echo "<div class='warning'>⚠ db_query() function not available</div>";
}
echo "</div>";

// Step 6: Next steps
echo "<div class='step'>";
echo "<h2>✅ Next Steps</h2>";

if (function_exists('get_db_connection') && isset($pdo) && $pdo) {
    echo "<div class='success'>Database connection is working! You can now:</div>";
    echo "<ul>";
    echo "<li><a href='public/dashboard.php' target='_blank'>Go to Dashboard →</a></li>";
    echo "<li><a href='public/index.php' target='_blank'>Go to Homepage →</a></li>";
    echo "</ul>";
} else {
    echo "<div class='warning'>Please fix the database connection issues above first.</div>";
}
echo "</div>";

echo "</div></body></html>";