<?php
/**
 * COMPREHENSIVE DASHBOARD DEBUGGER
 * Run this to identify why dashboard is blank
 */

// Turn on maximum error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

// Start output buffering
ob_start();

// Function to check if a file can be included
function safe_include($file) {
    echo "<tr>";
    echo "<td>" . htmlspecialchars($file) . "</td>";
    
    if (file_exists($file)) {
        echo "<td style='color:green'>✓ Exists</td>";
        
        // Check readable
        if (is_readable($file)) {
            echo "<td style='color:green'>✓ Readable</td>";
            
            // Try to include
            ob_start();
            try {
                include_once $file;
                $output = ob_get_clean();
                echo "<td style='color:green'>✓ Included</td>";
                echo "<td>" . (strlen($output) > 0 ? "Output: " . htmlspecialchars(substr($output, 0, 100)) : "No output") . "</td>";
            } catch (Exception $e) {
                ob_end_clean();
                echo "<td style='color:red'>✗ Error: " . htmlspecialchars($e->getMessage()) . "</td>";
                echo "<td>-</td>";
            } catch (Error $e) {
                ob_end_clean();
                echo "<td style='color:red'>✗ Error: " . htmlspecialchars($e->getMessage()) . "</td>";
                echo "<td>-</td>";
            }
        } else {
            echo "<td style='color:red'>✗ Not readable</td>";
            echo "<td>-</td><td>-</td>";
        }
    } else {
        echo "<td style='color:red'>✗ Not found</td>";
        echo "<td>-</td><td>-</td><td>-</td>";
    }
    echo "</tr>";
}

// Function to check if a function exists and can be called
function check_function($name) {
    echo "<tr>";
    echo "<td>" . htmlspecialchars($name) . "()</td>";
    
    if (function_exists($name)) {
        echo "<td style='color:green'>✓ Exists</td>";
        
        // Try to call if it's a simple function
        try {
            if ($name === 'is_logged_in') {
                $result = is_logged_in() ? 'true' : 'false';
                echo "<td style='color:green'>✓ Called (returns $result)</td>";
            } elseif ($name === 'current_user') {
                $user = current_user();
                echo "<td style='color:green'>✓ Called" . ($user ? " (user found)" : " (no user)") . "</td>";
            } elseif ($name === 'get_db_connection') {
                $pdo = get_db_connection();
                echo "<td style='color:green'>✓ Called (connected)</td>";
            } elseif ($name === 'db_fetch_one' || $name === 'db_fetch_all') {
                echo "<td style='color:orange'>⚠ Can't test safely</td>";
            } else {
                echo "<td style='color:green'>✓ Available</td>";
            }
        } catch (Exception $e) {
            echo "<td style='color:red'>✗ Error: " . htmlspecialchars($e->getMessage()) . "</td>";
        } catch (Error $e) {
            echo "<td style='color:red'>✗ Error: " . htmlspecialchars($e->getMessage()) . "</td>";
        }
    } else {
        echo "<td style='color:red'>✗ Not found</td>";
    }
    echo "</tr>";
}

// Start HTML output
echo "<!DOCTYPE html>
<html>
<head>
    <title>Dashboard Debugger</title>
    <style>
        body { font-family: monospace; padding: 20px; background: #f5f5f5; }
        h1 { color: #333; }
        h2 { color: #666; margin-top: 30px; }
        table { border-collapse: collapse; width: 100%; margin-bottom: 20px; background: white; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        .success { color: green; }
        .error { color: red; }
        .warning { color: orange; }
        pre { background: #333; color: #fff; padding: 10px; border-radius: 5px; overflow: auto; }
        .section { background: white; padding: 15px; margin-bottom: 20px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
    </style>
</head>
<body>
    <h1>🔍 Dashboard Debugger</h1>";

// Step 1: Basic PHP Info
echo "<div class='section'>";
echo "<h2>Step 1: Basic PHP Information</h2>";
echo "<table>";
echo "<tr><th>Property</th><th>Value</th></tr>";
echo "<tr><td>PHP Version</td><td>" . phpversion() . "</td></tr>";
echo "<tr><td>Memory Limit</td><td>" . ini_get('memory_limit') . "</td></tr>";
echo "<tr><td>Max Execution Time</td><td>" . ini_get('max_execution_time') . "s</td></tr>";
echo "<tr><td>Display Errors</td><td>" . ini_get('display_errors') . "</td></tr>";
echo "<tr><td>Error Reporting</td><td>" . error_reporting() . "</td></tr>";
echo "<tr><td>Document Root</td><td>" . ($_SERVER['DOCUMENT_ROOT'] ?? 'Unknown') . "</td></tr>";
echo "<tr><td>Script Path</td><td>" . __DIR__ . "</td></tr>";
echo "<tr><td>Request URI</td><td>" . ($_SERVER['REQUEST_URI'] ?? 'Unknown') . "</td></tr>";
echo "</table>";
echo "</div>";

// Step 2: Define BASE_PATH
echo "<div class='section'>";
echo "<h2>Step 2: Base Path</h2>";
$base_path = dirname(__DIR__);
echo "<p><strong>BASE_PATH set to:</strong> " . $base_path . "</p>";
echo "<p><strong>Directory exists:</strong> " . (is_dir($base_path) ? '✅ Yes' : '❌ No') . "</p>";
echo "</div>";

// Step 3: Check all required files
echo "<div class='section'>";
echo "<h2>Step 3: Required Files</h2>";
echo "<table>";
echo "<tr><th>File</th><th>Exists</th><th>Readable</th><th>Include Status</th><th>Output</th></tr>";

$files_to_check = [
    $base_path . '/config/config.php',
    $base_path . '/config/database.php',
    $base_path . '/config/auth.php',
    $base_path . '/config/csrf.php',
    $base_path . '/config/notifications.php',
    $base_path . '/config/constants.php',
    $base_path . '/config/helpers.php',
    $base_path . '/views/partials/header.php',
    $base_path . '/views/partials/topbar.php',
    $base_path . '/views/partials/sidebar.php',
    $base_path . '/views/partials/footer.php',
    __DIR__ . '/dashboard.php'
];

foreach ($files_to_check as $file) {
    safe_include($file);
}

echo "</table>";
echo "</div>";

// Step 4: Check loaded files
echo "<div class='section'>";
echo "<h2>Step 4: Currently Loaded Files</h2>";
echo "<table>";
echo "<tr><th>#</th><th>File</th></tr>";
$included_files = get_included_files();
foreach ($included_files as $index => $file) {
    echo "<tr><td>" . ($index + 1) . "</td><td>" . htmlspecialchars($file) . "</td></tr>";
}
echo "</table>";
echo "</div>";

// Step 5: Check critical functions
echo "<div class='section'>";
echo "<h2>Step 5: Critical Functions</h2>";
echo "<table>";
echo "<tr><th>Function</th><th>Exists</th><th>Status</th></tr>";

$functions_to_check = [
    'is_logged_in',
    'current_user',
    'require_auth',
    'get_db_connection',
    'db_fetch_one',
    'db_fetch_all',
    'db_query',
    'csrf_meta_tags',
    'csrf_field',
    'base_url',
    'assets_url',
    'get_unread_notification_count',
    'get_user_notifications',
    'format_currency',
    'time_ago',
    'escape_html',
    'sanitize_input',
    'redirect'
];

foreach ($functions_to_check as $func) {
    check_function($func);
}

echo "</table>";
echo "</div>";

// Step 6: Session status
echo "<div class='section'>";
echo "<h2>Step 6: Session Status</h2>";
echo "<table>";
echo "<tr><th>Property</th><th>Value</th></tr>";
echo "<tr><td>Session Status</td><td>" . (session_status() === PHP_SESSION_ACTIVE ? '✅ Active' : '❌ Not active') . "</td></tr>";
echo "<tr><td>Session ID</td><td>" . (session_id() ?: 'None') . "</td></tr>";

// Try to start session if not active
if (session_status() === PHP_SESSION_NONE) {
    session_start();
    echo "<tr><td>Session Started</td><td>✅ Started now</td></tr>";
}

echo "<tr><td>Session Data</td><td><pre>" . print_r($_SESSION, true) . "</pre></td></tr>";
echo "</table>";
echo "</div>";

// Step 7: Authentication status
echo "<div class='section'>";
echo "<h2>Step 7: Authentication Status</h2>";

if (function_exists('is_logged_in')) {
    $logged_in = is_logged_in();
    echo "<p><strong>Logged in:</strong> " . ($logged_in ? '✅ Yes' : '❌ No') . "</p>";
    
    if ($logged_in && function_exists('current_user')) {
        $user = current_user();
        echo "<p><strong>User ID:</strong> " . ($user['user_id'] ?? 'Unknown') . "</p>";
        echo "<p><strong>Username:</strong> " . ($user['username'] ?? 'Unknown') . "</p>";
        echo "<p><strong>User Data:</strong></p>";
        echo "<pre>" . print_r($user, true) . "</pre>";
    }
} else {
    echo "<p class='error'>is_logged_in() function not found</p>";
}

echo "</div>";

// Step 8: Database connection
echo "<div class='section'>";
echo "<h2>Step 8: Database Connection</h2>";

if (function_exists('get_db_connection')) {
    try {
        $pdo = get_db_connection();
        echo "<p class='success'>✅ Database connected</p>";
        
        // Get database info
        $db_name = $pdo->query("SELECT DATABASE() as db")->fetch()['db'];
        echo "<p><strong>Database:</strong> " . $db_name . "</p>";
        
        // List tables
        $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
        echo "<p><strong>Tables (" . count($tables) . "):</strong></p>";
        echo "<ul>";
        foreach (array_slice($tables, 0, 10) as $table) {
            echo "<li>" . $table . "</li>";
        }
        if (count($tables) > 10) {
            echo "<li>... and " . (count($tables) - 10) . " more</li>";
        }
        echo "</ul>";
        
        // Check required tables
        $required_tables = ['users', 'reservations', 'rooms', 'guests', 'folio_charges', 'notifications'];
        echo "<p><strong>Required tables check:</strong></p>";
        echo "<ul>";
        foreach ($required_tables as $table) {
            if (in_array($table, $tables)) {
                echo "<li class='success'>✅ $table exists</li>";
            } else {
                echo "<li class='error'>❌ $table missing</li>";
            }
        }
        echo "</ul>";
        
    } catch (Exception $e) {
        echo "<p class='error'>❌ Database error: " . $e->getMessage() . "</p>";
    }
} else {
    echo "<p class='error'>❌ get_db_connection() function not found</p>";
}

echo "</div>";

// Step 9: Constants
echo "<div class='section'>";
echo "<h2>Step 9: Critical Constants</h2>";
echo "<table>";
echo "<tr><th>Constant</th><th>Defined</th><th>Value</th></tr>";

$constants_to_check = [
    'BASE_PATH',
    'BASE_URL',
    'APP_NAME',
    'APP_VERSION',
    'DB_HOST',
    'DB_NAME',
    'DB_USER',
    'DB_PASS',
    'DB_CHARSET',
    'CSRF_TOKEN_NAME',
    'SESSION_TIMEOUT'
];

foreach ($constants_to_check as $const) {
    if (defined($const)) {
        $value = constant($const);
        if ($const === 'DB_PASS' && !empty($value)) {
            $value = '[hidden]';
        }
        echo "<tr><td>$const</td><td style='color:green'>✅ Yes</td><td>" . htmlspecialchars($value) . "</td></tr>";
    } else {
        echo "<tr><td>$const</td><td style='color:red'>❌ No</td><td>-</td></tr>";
    }
}

echo "</table>";
echo "</div>";

// Step 10: Try to include dashboard directly
echo "<div class='section'>";
echo "<h2>Step 10: Direct Dashboard Inclusion Test</h2>";

$dashboard_file = __DIR__ . '/dashboard.php';
if (file_exists($dashboard_file)) {
    echo "<p>Attempting to include dashboard.php...</p>";
    ob_start();
    try {
        include $dashboard_file;
        $output = ob_get_clean();
        if (strlen($output) > 0) {
            echo "<p class='success'>✅ Dashboard included successfully with " . strlen($output) . " bytes of output</p>";
            echo "<p>First 500 characters of output:</p>";
            echo "<pre>" . htmlspecialchars(substr($output, 0, 500)) . "</pre>";
        } else {
            echo "<p class='error'>❌ Dashboard included but produced NO OUTPUT</p>";
        }
    } catch (Exception $e) {
        ob_end_clean();
        echo "<p class='error'>❌ Error including dashboard: " . $e->getMessage() . "</p>";
    } catch (Error $e) {
        ob_end_clean();
        echo "<p class='error'>❌ Error including dashboard: " . $e->getMessage() . "</p>";
    }
} else {
    echo "<p class='error'>❌ dashboard.php not found</p>";
}

echo "</div>";

// Step 11: PHP Error Log
echo "<div class='section'>";
echo "<h2>Step 11: Recent PHP Errors</h2>";

$error_log = ini_get('error_log');
if (file_exists($error_log)) {
    $lines = file($error_log);
    $last_lines = array_slice($lines, -20);
    echo "<pre>" . htmlspecialchars(implode('', $last_lines)) . "</pre>";
} else {
    echo "<p>Error log not found at: $error_log</p>";
    
    // Try XAMPP default location
    $xampp_log = '/Applications/XAMPP/xamppfiles/logs/php_error_log';
    if (file_exists($xampp_log)) {
        $lines = file($xampp_log);
        $last_lines = array_slice($lines, -20);
        echo "<pre>" . htmlspecialchars(implode('', $last_lines)) . "</pre>";
    }
}

echo "</div>";

// Step 12: Recommendations
echo "<div class='section'>";
echo "<h2>📋 Recommendations</h2>";
echo "<ul>";

// Check if user is logged in
if (!function_exists('is_logged_in') || !is_logged_in()) {
    echo "<li class='error'>❌ You are not logged in. Try logging in first at <a href='login.php'>login.php</a></li>";
}

// Check database connection
if (!function_exists('get_db_connection')) {
    echo "<li class='error'>❌ Database functions not available. Check database.php</li>";
}

// Check if header exists
if (!file_exists($base_path . '/views/partials/header.php')) {
    echo "<li class='error'>❌ Header file missing. Create it at: " . $base_path . '/views/partials/header.php' . "</li>";
}

// Check if dashboard has output
if (ob_get_level() > 0 && strlen(ob_get_contents()) == 0) {
    echo "<li class='warning'>⚠️ Dashboard is producing no output. Check for silent PHP errors.</li>";
}

echo "</ul>";
echo "</div>";

echo "<hr>";
echo "<p><a href='dashboard.php'>Try dashboard again</a> | <a href='login.php'>Go to login</a></p>";

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

// Flush output
ob_end_flush();
?>