<?php
// ============================================
// DigiMobiz - Debug & Diagnostics Tool
// ============================================

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

echo "<!DOCTYPE html><html lang='en'><head><meta charset='UTF-8'>";
echo "<title>DigiMobiz - Debug Test</title>";
echo "<link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>";
echo "</head><body class='bg-light'><div class='container py-4'>";

echo "<h2 class='mb-4'>DigiMobiz - System Diagnostics</h2>";

$base = __DIR__;
$errors = [];
$warnings = [];

// 1. PHP Version
echo "<div class='card mb-3'><div class='card-header'><strong>1. PHP Version</strong></div><div class='card-body'>";
echo "PHP Version: " . phpversion();
if (version_compare(phpversion(), '7.0', '<')) {
    echo " <span class='text-danger'>Minimum PHP 7.0 required!</span>";
    $errors[] = "PHP version too old: " . phpversion();
} else {
    echo " <span class='text-success'>(OK)</span>";
}
echo "</div></div>";

// 2. Required Extensions
echo "<div class='card mb-3'><div class='card-header'><strong>2. Required PHP Extensions</strong></div><div class='card-body'>";
$required_exts = ['pdo', 'pdo_mysql', 'session', 'json', 'mbstring', 'gd'];
foreach ($required_exts as $ext) {
    $ok = extension_loaded($ext);
    echo "$ext: " . ($ok ? "<span class='text-success'>Loaded</span>" : "<span class='text-danger'>Missing!</span>") . "<br>";
    if (!$ok) $errors[] = "Extension missing: $ext";
}
echo "</div></div>";

// 3. Database Connection
echo "<div class='card mb-3'><div class='card-header'><strong>3. Database Connection</strong></div><div class='card-body'>";
try {
    $pdo = new PDO("mysql:host=localhost;dbname=digimobiz;charset=utf8mb4", "root", "", [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
    echo "<span class='text-success'>Connected to 'digimobiz' on localhost</span><br>";

    // Check tables
    $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
    echo "Tables found: " . count($tables) . " (" . implode(", ", $tables) . ")<br>";

    // Check users table
    if (in_array('users', $tables)) {
        $count = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
        echo "Users in table: $count<br>";
        $users = $pdo->query("SELECT id, name, email, role_id FROM users LIMIT 5")->fetchAll();
        foreach ($users as $u) {
            echo "- ID:{$u['id']} Name:{$u['name']} Email:{$u['email']} Role:{$u['role_id']}<br>";
        }
    } else {
        echo "<span class='text-warning'>'users' table not found - run install.php first</span><br>";
        $warnings[] = "users table does not exist";
    }

    // Check permissions table
    if (in_array('permissions', $tables)) {
        $pcount = $pdo->query("SELECT COUNT(*) FROM permissions")->fetchColumn();
        echo "Permissions: $pcount<br>";
        $perms = $pdo->query("SELECT permission_key, module_name FROM permissions LIMIT 10")->fetchAll();
        foreach ($perms as $p) {
            echo "- {$p['permission_key']} ({$p['module_name']})<br>";
        }
    }

    // Check roles table
    if (in_array('roles', $tables)) {
        $rcount = $pdo->query("SELECT COUNT(*) FROM roles")->fetchColumn();
        echo "Roles: $rcount<br>";
        $roles = $pdo->query("SELECT id, role_name FROM roles")->fetchAll();
        foreach ($roles as $r) {
            echo "- ID:{$r['id']} {$r['role_name']}<br>";
        }
    }

} catch (PDOException $e) {
    echo "<span class='text-danger'>Connection failed: " . htmlspecialchars($e->getMessage()) . "</span><br>";
    $errors[] = "Database error: " . $e->getMessage();
}
echo "</div></div>";

// 4. Session Test
echo "<div class='card mb-3'><div class='card-header'><strong>4. Session Test</strong></div><div class='card-body'>";
if (session_status() === PHP_SESSION_NONE) session_start();
echo "Session ID: " . session_id() . "<br>";
echo "Session status: " . (session_status() === PHP_SESSION_ACTIVE ? "<span class='text-success'>Active</span>" : "<span class='text-danger'>Inactive</span>");
echo "</div></div>";

// 5. Required Files Check
echo "<div class='card mb-3'><div class='card-header'><strong>5. Required Files</strong></div><div class='card-body'>";
$files_to_check = [
    'config/database.php',
    'config/auth.php',
    'config/permissions.php',
    'includes/header.php',
    'includes/sidebar.php',
    'includes/footer.php',
    'includes/functions.php',
    'includes/alerts.php',
    'database/schema.sql',
    'database/seed.sql',
    'auth/login.php',
    'auth/logout.php',
    'admin/dashboard.php',
    'admin/users.php',
    'admin/roles.php',
    'admin/permissions.php',
    'assets/css/style.css',
    'assets/js/main.js',
    'assets/js/app.js',
    'assets/uploads/',
    '.htaccess',
    'install.php',
    'index.php',
];
foreach ($files_to_check as $file) {
    $path = $base . '/' . $file;
    $exists = file_exists($path);
    echo ($exists ? "<span class='text-success'>OK</span>" : "<span class='text-danger'>MISSING</span>") . " - $file<br>";
    if (!$exists) $errors[] = "Missing file: $file";
}
echo "</div></div>";

// 6. .htaccess check
echo "<div class='card mb-3'><div class='card-header'><strong>6. .htaccess Check</strong></div><div class='card-body'>";
$htaccess = $base . '/.htaccess';
if (file_exists($htaccess)) {
    $content = file_get_contents($htaccess);
    if (strpos($content, '<Directory') !== false) {
        echo "<span class='text-danger'>.htaccess contains &lt;Directory&gt; directive - remove it! This causes 500 error.</span>";
        $errors[] = ".htaccess has <Directory> directive";
    } else {
        echo "<span class='text-success'>.htaccess looks clean (no &lt;Directory&gt; directives)</span>";
    }
} else {
    echo "<span class='text-warning'>.htaccess not found</span>";
}
echo "</div></div>";

// Summary
echo "<div class='card mb-3'><div class='card-header'><strong>Summary</strong></div><div class='card-body'>";
if (empty($errors)) {
    echo "<div class='alert alert-success mb-0'>All checks passed! System should be operational.</div>";
} else {
    echo "<div class='alert alert-danger'>" . count($errors) . " error(s) found:</div><ul>";
    foreach ($errors as $e) {
        echo "<li class='text-danger'>" . htmlspecialchars($e) . "</li>";
    }
    echo "</ul>";
    if ($warnings) {
        echo "<div class='alert alert-warning'>" . count($warnings) . " warning(s):</div><ul>";
        foreach ($warnings as $w) {
            echo "<li>" . htmlspecialchars($w) . "</li>";
        }
        echo "</ul>";
    }
}
echo "</div></div>";

echo "<p><a href='install.php' class='btn btn-primary'>Run Installer</a> ";
echo "<a href='auth/login.php' class='btn btn-success'>Go to Login</a></p>";

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