<?php
/**
 * ===========================================
 * FLOWBOT DCI - DIAGNOSTIC TOOL
 * ===========================================
 * Access this file to diagnose server issues
 * DELETE THIS FILE AFTER DEBUGGING!
 */

error_reporting(E_ALL);
ini_set('display_errors', '1');

echo "<!DOCTYPE html><html><head><title>Flowbot DCI Diagnostics</title>";
echo "<style>body{font-family:sans-serif;padding:20px;background:#1a1a2e;color:#eee;max-width:900px;margin:0 auto;}";
echo "h1,h2{color:#4ecdc4;}table{width:100%;border-collapse:collapse;margin:15px 0;}";
echo "td,th{padding:10px;text-align:left;border:1px solid #333;}th{background:#16213e;}";
echo ".ok{color:#2ecc71;}.error{color:#e74c3c;}.warn{color:#f1c40f;}";
echo "pre{background:#16213e;padding:15px;overflow:auto;border-radius:5px;}</style></head><body>";

echo "<h1>Flowbot DCI - Diagnostics</h1>";

// 1. PHP Info
echo "<h2>1. PHP Version & Extensions</h2>";
echo "<table>";
echo "<tr><th>Item</th><th>Status</th><th>Value</th></tr>";
echo "<tr><td>PHP Version</td><td class='" . (version_compare(PHP_VERSION, '7.4', '>=') ? 'ok' : 'error') . "'>" . (version_compare(PHP_VERSION, '7.4', '>=') ? 'OK' : 'ERROR') . "</td><td>" . PHP_VERSION . "</td></tr>";

$extensions = ['curl', 'pdo', 'pdo_mysql', 'dom', 'json', 'mbstring', 'libxml'];
foreach ($extensions as $ext) {
    $loaded = extension_loaded($ext);
    echo "<tr><td>Extension: {$ext}</td><td class='" . ($loaded ? 'ok' : 'error') . "'>" . ($loaded ? 'OK' : 'MISSING') . "</td><td>" . ($loaded ? 'Loaded' : 'Not installed') . "</td></tr>";
}
echo "</table>";

// 2. Paths
echo "<h2>2. Path Configuration</h2>";
echo "<table>";
echo "<tr><th>Item</th><th>Value</th></tr>";
echo "<tr><td>__FILE__</td><td>" . __FILE__ . "</td></tr>";
echo "<tr><td>__DIR__</td><td>" . __DIR__ . "</td></tr>";
echo "<tr><td>dirname(__DIR__)</td><td>" . dirname(__DIR__) . "</td></tr>";
echo "<tr><td>DOCUMENT_ROOT</td><td>" . ($_SERVER['DOCUMENT_ROOT'] ?? 'N/A') . "</td></tr>";
echo "<tr><td>SCRIPT_FILENAME</td><td>" . ($_SERVER['SCRIPT_FILENAME'] ?? 'N/A') . "</td></tr>";
echo "<tr><td>SCRIPT_NAME</td><td>" . ($_SERVER['SCRIPT_NAME'] ?? 'N/A') . "</td></tr>";
echo "<tr><td>REQUEST_URI</td><td>" . ($_SERVER['REQUEST_URI'] ?? 'N/A') . "</td></tr>";
echo "</table>";

// 3. File Existence
echo "<h2>3. Required Files Check</h2>";
$basePath = dirname(__DIR__);
$files = [
    'autoload.php' => $basePath . '/src/autoload.php',
    'config.php' => $basePath . '/config/config.php',
    '.env' => $basePath . '/.env',
    'Application.php' => $basePath . '/src/Core/Application.php',
    'Database.php' => $basePath . '/src/Core/Database.php',
    'form.php' => $basePath . '/views/form.php',
    'progress.php' => $basePath . '/views/progress.php',
];

echo "<table>";
echo "<tr><th>File</th><th>Exists</th><th>Readable</th><th>Path</th></tr>";
foreach ($files as $name => $path) {
    $exists = file_exists($path);
    $readable = is_readable($path);
    echo "<tr>";
    echo "<td>{$name}</td>";
    echo "<td class='" . ($exists ? 'ok' : 'error') . "'>" . ($exists ? 'YES' : 'NO') . "</td>";
    echo "<td class='" . ($readable ? 'ok' : ($exists ? 'error' : 'warn')) . "'>" . ($readable ? 'YES' : 'NO') . "</td>";
    echo "<td><code>{$path}</code></td>";
    echo "</tr>";
}
echo "</table>";

// 4. Temp Directory
echo "<h2>4. Temp Directory</h2>";
$tempDir = $basePath . '/temp';
echo "<table>";
echo "<tr><th>Check</th><th>Status</th><th>Value</th></tr>";
echo "<tr><td>Path</td><td>-</td><td>" . $tempDir . "</td></tr>";
echo "<tr><td>Exists</td><td class='" . (is_dir($tempDir) ? 'ok' : 'error') . "'>" . (is_dir($tempDir) ? 'YES' : 'NO') . "</td><td>-</td></tr>";
echo "<tr><td>Writable</td><td class='" . (is_writable($tempDir) ? 'ok' : 'error') . "'>" . (is_writable($tempDir) ? 'YES' : 'NO') . "</td><td>-</td></tr>";
echo "</table>";

// 5. Try loading config
echo "<h2>5. Configuration Load Test</h2>";
try {
    if (file_exists($basePath . '/config/config.php')) {
        $config = require $basePath . '/config/config.php';
        echo "<p class='ok'>Configuration loaded successfully!</p>";
        echo "<pre>";
        echo "ENV Loaded: " . ($GLOBALS['env_loaded'] ?? 'N/A') . "\n";
        if (!empty($GLOBALS['env_errors'])) {
            echo "ENV Errors: " . implode(', ', $GLOBALS['env_errors']) . "\n";
        }
        echo "\nConfig Keys: " . implode(', ', array_keys($config)) . "\n";
        echo "Debug Mode: " . ($config['app']['debug'] ? 'true' : 'false') . "\n";
        echo "DB Host: " . ($config['database']['host'] ?? 'N/A') . "\n";
        echo "DB Name: " . ($config['database']['name'] ?? 'N/A') . "\n";
        echo "</pre>";
    } else {
        echo "<p class='error'>Config file not found!</p>";
    }
} catch (Throwable $e) {
    echo "<p class='error'>Config Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<pre>" . htmlspecialchars($e->getTraceAsString()) . "</pre>";
}

// 6. Try loading autoloader
echo "<h2>6. Autoloader Test</h2>";
try {
    if (file_exists($basePath . '/src/autoload.php')) {
        require_once $basePath . '/src/autoload.php';
        echo "<p class='ok'>Autoloader loaded!</p>";

        // Verify classes
        if (function_exists('verifyAutoloader')) {
            $results = verifyAutoloader();
            echo "<table>";
            echo "<tr><th>Class</th><th>File Exists</th><th>Readable</th></tr>";
            foreach ($results as $class => $info) {
                echo "<tr>";
                echo "<td>{$class}</td>";
                echo "<td class='" . ($info['exists'] ? 'ok' : 'error') . "'>" . ($info['exists'] ? 'YES' : 'NO') . "</td>";
                echo "<td class='" . ($info['readable'] ? 'ok' : 'error') . "'>" . ($info['readable'] ? 'YES' : 'NO') . "</td>";
                echo "</tr>";
            }
            echo "</table>";
        }
    } else {
        echo "<p class='error'>Autoloader file not found!</p>";
    }
} catch (Throwable $e) {
    echo "<p class='error'>Autoloader Error: " . htmlspecialchars($e->getMessage()) . "</p>";
}

// 7. Try database connection
echo "<h2>7. Database Connection Test</h2>";
try {
    if (isset($config['database'])) {
        $dsn = sprintf(
            "mysql:host=%s;dbname=%s;charset=%s",
            $config['database']['host'],
            $config['database']['name'],
            $config['database']['charset'] ?? 'utf8mb4'
        );

        $pdo = new PDO($dsn, $config['database']['user'], $config['database']['password'], [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_TIMEOUT => 5
        ]);

        echo "<p class='ok'>Database connected successfully!</p>";

        // Show tables
        $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
        echo "<p>Tables found: " . count($tables) . "</p>";
        if (!empty($tables)) {
            echo "<pre>" . implode("\n", $tables) . "</pre>";
        }
    } else {
        echo "<p class='error'>Database config not available</p>";
    }
} catch (PDOException $e) {
    echo "<p class='error'>Database Error: " . htmlspecialchars($e->getMessage()) . "</p>";
}

// 8. Try instantiating Application
echo "<h2>8. Application Test</h2>";
try {
    if (class_exists('\\FlowbotDCI\\Core\\Application')) {
        echo "<p class='ok'>Application class found!</p>";

        // Try to instantiate (but don't run)
        $app = new \FlowbotDCI\Core\Application($config);
        echo "<p class='ok'>Application instantiated successfully!</p>";
    } else {
        echo "<p class='error'>Application class NOT found. Check autoloader.</p>";

        // Show autoloader errors if any
        if (function_exists('getAutoloadErrors')) {
            $errors = getAutoloadErrors();
            if (!empty($errors)) {
                echo "<h4>Autoloader Errors:</h4><pre>";
                print_r($errors);
                echo "</pre>";
            }
        }
    }
} catch (Throwable $e) {
    echo "<p class='error'>Application Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<pre>" . htmlspecialchars($e->getTraceAsString()) . "</pre>";
}

echo "<hr><p><strong>DELETE THIS FILE AFTER DEBUGGING!</strong></p>";
echo "</body></html>";
