<?php
// debug.php - Verbose System Diagnostics
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h1>🔍 FON2FIX DIAGNOSTIC TOOL</h1>";
echo "<hr>";

// 1. CHECK CONFIG
echo "<h3>1. Checking db.php</h3>";
if (file_exists('db.php')) {
    echo "<p style='color:green'>✅ db.php found.</p>";
    require 'db.php';
} else {
    die("<h1 style='color:red'>❌ CRITICAL: db.php is missing!</h1>");
}

// 2. CHECK CONNECTION
echo "<h3>2. Database Connection</h3>";
try {
    $attr = $pdo->getAttribute(PDO::ATTR_CONNECTION_STATUS);
    echo "<p style='color:green'>✅ Connected successfully: $attr</p>";
    echo "Database: " . $pdo->query('select database()')->fetchColumn();
} catch (Exception $e) {
    die("<p style='color:red'>❌ Connection Failed: " . $e->getMessage() . "</p>");
}

// 3. CHECK TABLES
echo "<h3>3. Table Verification</h3>";
$required = ['customers', 'stock_list', 'jobs', 'transfer_logs'];
$found_tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);

$missing = false;
echo "<table border='1' cellpadding='5'><tr><th>Table</th><th>Status</th><th>Columns</th><th>Rows</th></tr>";

foreach ($required as $table) {
    echo "<tr><td><b>$table</b></td>";
    if (in_array($table, $found_tables)) {
        // Get Columns
        $cols = $pdo->query("DESCRIBE $table")->fetchAll(PDO::FETCH_COLUMN);
        $count = $pdo->query("SELECT COUNT(*) FROM $table")->fetchColumn();
        echo "<td style='color:green'>✅ OK</td>";
        echo "<td>" . implode(", ", $cols) . "</td>";
        echo "<td>$count</td>";
    } else {
        echo "<td style='color:red'>❌ MISSING</td><td>-</td><td>-</td>";
        $missing = true;
    }
    echo "</tr>";
}
echo "</table>";

if ($missing) {
    echo "<h2 style='color:red'>⚠️ DIAGNOSIS: You have missing tables. Run fix_crash.php immediately.</h2>";
} else {
    echo "<h2 style='color:green'>✅ DIAGNOSIS: Database Structure is CORRECT.</h2>";
}

// 4. CHECK SESSION
echo "<h3>4. Session Status</h3>";
echo "Session ID: " . session_id() . "<br>";
echo "User: " . ($_SESSION['user'] ?? 'NOT LOGGED IN') . "<br>";
echo "Role: " . ($_SESSION['role'] ?? 'N/A') . "<br>";

// 5. TEST QUERY
echo "<h3>5. API Simulation (Fetch Stock)</h3>";
try {
    $stmt = $pdo->query("SELECT * FROM stock_list LIMIT 1");
    $item = $stmt->fetch();
    if ($item) {
        echo "<p style='color:green'>✅ Read Success: Found item '{$item['part_name']}'</p>";
    } else {
        echo "<p style='color:orange'>⚠️ Read OK, but table is empty.</p>";
    }
} catch (Exception $e) {
    echo "<p style='color:red'>❌ Read Failed: " . $e->getMessage() . "</p>";
}
?>