<?php
echo "<h1>🔍 DEBUG 500 INTERNAL SERVER ERROR</h1>";
echo "<style>body{font-family:Arial,sans-serif;margin:20px;font-size:14px;} .error{color:red;font-weight:bold;} .success{color:green;font-weight:bold;} .warning{color:orange;font-weight:bold;} .info{color:blue;} pre{background:#f5f5f5;padding:10px;border-radius:4px;margin:10px 0;max-height:300px;overflow:auto;}</style>";

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

echo "<h2>1. PHP Configuration</h2>";
echo "<p><strong>PHP Version:</strong> " . phpversion() . "</p>";
echo "<p><strong>Error Reporting:</strong> " . (error_reporting() ? 'Enabled' : 'Disabled') . "</p>";
echo "<p><strong>Display Errors:</strong> " . (ini_get('display_errors') ? 'On' : 'Off') . "</p>";

echo "<h2>2. Laravel Environment Check</h2>";

// Check if .env exists
$envFile = '../.env';
if (file_exists($envFile)) {
    echo "<p class='success'>✅ .env file exists</p>";

    $envContent = file_get_contents($envFile);
    $lines = explode("\n", $envContent);

    echo "<p><strong>Key Configuration:</strong></p>";
    $config = [];
    foreach ($lines as $line) {
        if (strpos($line, '=') !== false) {
            list($key, $value) = explode('=', $line, 2);
            $key = trim($key);
            if (in_array($key, ['APP_ENV', 'APP_DEBUG', 'APP_KEY', 'DB_CONNECTION', 'DB_HOST', 'DB_DATABASE'])) {
                $config[$key] = trim($value);
                echo "<div style='margin-left:20px;'>• <strong>$key:</strong> $value</div>";
            }
        }
    }

    // Check APP_KEY validity
    if (isset($config['APP_KEY']) && !empty($config['APP_KEY'])) {
        echo "<p class='success'>✅ APP_KEY is set</p>";
    } else {
        echo "<p class='error'>❌ APP_KEY is missing or empty</p>";
    }

} else {
    echo "<p class='error'>❌ .env file missing</p>";
}

echo "<h2>3. Directory Permissions</h2>";
$dirsToCheck = [
    '../storage' => 'Storage directory',
    '../storage/logs' => 'Storage logs',
    '../storage/framework' => 'Storage framework',
    '../storage/framework/cache' => 'Cache directory',
    '../storage/framework/sessions' => 'Sessions directory',
    '../storage/framework/views' => 'Views directory',
    '../bootstrap/cache' => 'Bootstrap cache'
];

foreach ($dirsToCheck as $dir => $name) {
    if (is_dir($dir)) {
        $writable = is_writable($dir);
        echo "<p>" . ($writable ? "<span class='success'>✅</span>" : "<span class='error'>❌</span>") . " $name: " . ($writable ? 'Writable' : 'NOT writable') . "</p>";
    } else {
        echo "<p class='warning'>⚠️ $name: Directory does not exist</p>";
    }
}

echo "<h2>4. Laravel Framework Test</h2>";
try {
    require_once '../vendor/autoload.php';
    echo "<p class='success'>✅ Composer autoload successful</p>";

    $app = require_once '../bootstrap/app.php';
    echo "<p class='success'>✅ Laravel app bootstrap successful</p>";

    $kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
    $kernel->bootstrap();
    echo "<p class='success'>✅ Laravel kernel bootstrap successful</p>";

} catch (Exception $e) {
    echo "<p class='error'>❌ Laravel bootstrap failed: " . $e->getMessage() . "</p>";
    echo "<pre>" . $e->getTraceAsString() . "</pre>";
}

echo "<h2>5. Database Connection Test</h2>";
try {
    require_once '../vendor/autoload.php';
    $app = require_once '../bootstrap/app.php';
    $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

    $pdo = DB::connection('mysql')->getPdo();
    echo "<p class='success'>✅ Database connection successful</p>";

    // Test basic queries
    $users = DB::table('users')->count();
    $profiles = DB::table('profiles')->count();
    $articles = DB::table('articles')->count();

    echo "<p class='success'>✅ Database queries working:</p>";
    echo "<ul style='margin-left:20px;'>";
    echo "<li>Users: $users</li>";
    echo "<li>Profiles: $profiles</li>";
    echo "<li>Articles: $articles</li>";
    echo "</ul>";

} catch (Exception $e) {
    echo "<p class='error'>❌ Database test failed: " . $e->getMessage() . "</p>";
    echo "<pre>" . $e->getTraceAsString() . "</pre>";
}

echo "<h2>6. Route & Controller Test</h2>";
try {
    require_once '../vendor/autoload.php';
    $app = require_once '../bootstrap/app.php';
    $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

    // Test route resolution
    $router = app('router');
    $routes = $router->getRoutes();

    echo "<p class='success'>✅ Router initialized, " . count($routes) . " routes registered</p>";

    // Test controller instantiation
    $controller = app(\App\Http\Controllers\BpmController::class);
    echo "<p class='success'>✅ BpmController can be instantiated</p>";

    // Test home method
    if (method_exists($controller, 'home')) {
        echo "<p class='success'>✅ BpmController::home method exists</p>";
    } else {
        echo "<p class='error'>❌ BpmController::home method missing</p>";
    }

} catch (Exception $e) {
    echo "<p class='error'>❌ Route/Controller test failed: " . $e->getMessage() . "</p>";
    echo "<pre>" . $e->getTraceAsString() . "</pre>";
}

echo "<h2>7. View Test</h2>";
try {
    require_once '../vendor/autoload.php';
    $app = require_once '../bootstrap/app.php';
    $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

    // Test view rendering
    $view = view('pages.home');
    echo "<p class='success'>✅ View 'pages.home' can be rendered</p>";

} catch (Exception $e) {
    echo "<p class='error'>❌ View test failed: " . $e->getMessage() . "</p>";
    echo "<pre>" . substr($e->getTraceAsString(), 0, 1000) . "...</pre>";
}

echo "<h2>8. Quick Fix Actions</h2>";
echo "<div style='background:#e8f4f8;padding:15px;border-radius:8px;margin:10px 0;'>";
echo "<h3>🔧 Recommended Fixes:</h3>";
echo "<ol>";
echo "<li><a href='fix_permissions.php' style='color:#007bff;'>Fix Directory Permissions</a></li>";
echo "<li><a href='generate_app_key.php' style='color:#007bff;'>Generate APP_KEY</a></li>";
echo "<li><a href='clear_all_cache.php' style='color:#007bff;'>Clear All Laravel Caches</a></li>";
echo "<li><a href='check_logs.php' style='color:#007bff;'>Check Laravel Logs</a></li>";
echo "</ol>";
echo "</div>";

echo "<hr>";
echo "<p><strong>Debug executed at:</strong> " . date('Y-m-d H:i:s') . "</p>";
echo "<p><strong>Request URI:</strong> " . $_SERVER['REQUEST_URI'] . "</p>";
echo "<p><strong>Server IP:</strong> " . $_SERVER['SERVER_ADDR'] . "</p>";
?>
