<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<!DOCTYPE html><html><head><title>Laravel Diagnostics</title>";
echo "<style>
    body { font-family: Arial; margin: 20px; background: #f5f5f5; }
    .section { background: white; padding: 20px; margin: 10px 0; border-radius: 5px; }
    .success { color: #10b981; }
    .error { color: #ef4444; }
    .warning { color: #f59e0b; }
    h1 { color: #2563eb; }
    h2 { color: #1f2937; border-bottom: 2px solid #e5e7eb; padding-bottom: 10px; }
    pre { background: #1f2937; color: #f3f4f6; padding: 15px; border-radius: 5px; overflow-x: auto; }
    .info { background: #dbeafe; padding: 10px; border-radius: 5px; margin: 5px 0; }
</style></head><body>";

echo "<h1>🔍 Laravel Diagnostics - Sarkin Mota Group</h1>";

// 1. PHP Information
echo "<div class='section'><h2>1. PHP Environment</h2>";
echo "<div class='info'><strong>PHP Version:</strong> " . phpversion() . "</div>";
echo "<div class='info'><strong>Server Software:</strong> " . $_SERVER['SERVER_SOFTWARE'] . "</div>";
echo "<div class='info'><strong>Document Root:</strong> " . $_SERVER['DOCUMENT_ROOT'] . "</div>";
echo "<div class='info'><strong>Current File:</strong> " . __FILE__ . "</div>";

// Check PHP Extensions
echo "<h3>Required PHP Extensions:</h3>";
$required_extensions = ['pdo', 'pdo_mysql', 'mbstring', 'openssl', 'tokenizer', 'xml', 'ctype', 'json', 'fileinfo', 'dom'];
foreach ($required_extensions as $ext) {
    $loaded = extension_loaded($ext);
    echo "<div class='" . ($loaded ? 'success' : 'error') . "'>";
    echo $loaded ? "✅ " : "❌ ";
    echo "$ext: " . ($loaded ? 'Loaded' : 'MISSING');
    echo "</div>";
}
echo "</div>";

// 2. File System Paths
echo "<div class='section'><h2>2. File System Check</h2>";

$base_path = dirname(__DIR__);
echo "<div class='info'><strong>Base Path:</strong> $base_path</div>";

$paths_to_check = [
    'Bootstrap' => $base_path . '/bootstrap/app.php',
    'Vendor Autoload' => $base_path . '/vendor/autoload.php',
    '.env File' => $base_path . '/.env',
    'Routes Web' => $base_path . '/routes/web.php',
    'Routes API' => $base_path . '/routes/api.php',
    'App Blade' => $base_path . '/resources/views/app.blade.php',
    'Storage Logs' => $base_path . '/storage/logs',
    'Bootstrap Cache' => $base_path . '/bootstrap/cache',
    'Build Assets CSS' => __DIR__ . '/build/assets/app-CFPfJzfQ.css',
    'Build Assets JS' => __DIR__ . '/build/assets/main-Hhf1Bkdr.js',
];

foreach ($paths_to_check as $name => $path) {
    $exists = file_exists($path);
    $writable = is_writable($path);
    echo "<div class='" . ($exists ? 'success' : 'error') . "'>";
    echo $exists ? "✅ " : "❌ ";
    echo "$name: ";
    if ($exists) {
        echo "EXISTS";
        if (is_dir($path)) {
            echo " (Writable: " . ($writable ? "YES" : "NO") . ")";
        }
    } else {
        echo "MISSING - $path";
    }
    echo "</div>";
}
echo "</div>";

// 3. Try Loading Laravel
echo "<div class='section'><h2>3. Laravel Bootstrap Test</h2>";
try {
    if (file_exists($base_path . '/vendor/autoload.php')) {
        require $base_path . '/vendor/autoload.php';
        echo "<div class='success'>✅ Vendor autoload loaded successfully</div>";
    } else {
        echo "<div class='error'>❌ Vendor autoload not found</div>";
    }
    
    if (file_exists($base_path . '/bootstrap/app.php')) {
        $app = require $base_path . '/bootstrap/app.php';
        echo "<div class='success'>✅ Laravel application bootstrapped</div>";
        echo "<div class='info'><strong>App Class:</strong> " . get_class($app) . "</div>";
        
        // Try to boot kernel
        try {
            $kernel = $app->make(\Illuminate\Contracts\Http\Kernel::class);
            echo "<div class='success'>✅ HTTP Kernel loaded</div>";
        } catch (Exception $e) {
            echo "<div class='error'>❌ Kernel Error: " . $e->getMessage() . "</div>";
        }
        
    } else {
        echo "<div class='error'>❌ Bootstrap file not found</div>";
    }
} catch (Exception $e) {
    echo "<div class='error'>❌ Bootstrap Error: " . $e->getMessage() . "</div>";
    echo "<pre>" . $e->getTraceAsString() . "</pre>";
}
echo "</div>";

// 4. Environment Variables
echo "<div class='section'><h2>4. Environment Configuration</h2>";
if (file_exists($base_path . '/.env')) {
    echo "<div class='success'>✅ .env file exists</div>";
    $env_content = file_get_contents($base_path . '/.env');
    $env_lines = explode("\n", $env_content);
    
    $important_vars = ['APP_NAME', 'APP_ENV', 'APP_KEY', 'APP_URL', 'DB_CONNECTION', 'DB_HOST', 'DB_DATABASE'];
    
    foreach ($important_vars as $var) {
        $found = false;
        $value = '';
        foreach ($env_lines as $line) {
            if (strpos($line, $var . '=') === 0) {
                $found = true;
                $parts = explode('=', $line, 2);
                $value = isset($parts[1]) ? $parts[1] : '';
                if ($var === 'APP_KEY') {
                    $value = !empty($value) ? 'SET (Hidden)' : 'EMPTY';
                }
                break;
            }
        }
        
        echo "<div class='" . ($found && !empty($value) ? 'success' : 'error') . "'>";
        echo ($found && !empty($value)) ? "✅ " : "❌ ";
        echo "$var: " . ($found ? $value : 'NOT SET');
        echo "</div>";
    }
} else {
    echo "<div class='error'>❌ .env file not found</div>";
}
echo "</div>";

// 5. Database Connection
echo "<div class='section'><h2>5. Database Connection Test</h2>";
try {
    if (isset($app)) {
        $db = $app->make('db');
        $pdo = $db->connection()->getPdo();
        echo "<div class='success'>✅ Database connected successfully</div>";
        
        // Try a simple query
        $result = $db->select('SELECT DATABASE() as db_name');
        echo "<div class='info'><strong>Connected to database:</strong> " . $result[0]->db_name . "</div>";
    } else {
        echo "<div class='warning'>⚠️ App not initialized, skipping DB test</div>";
    }
} catch (Exception $e) {
    echo "<div class='error'>❌ Database Error: " . $e->getMessage() . "</div>";
}
echo "</div>";

// 6. Route Loading Test
echo "<div class='section'><h2>6. Routes Test</h2>";
try {
    if (isset($app)) {
        $routes = $app->make('router')->getRoutes();
        $route_count = count($routes);
        echo "<div class='success'>✅ Routes loaded: $route_count routes registered</div>";
        
        // Show first few routes
        echo "<h3>Sample Routes:</h3><pre>";
        $count = 0;
        foreach ($routes as $route) {
            if ($count++ >= 10) break;
            echo $route->methods()[0] . " " . $route->uri() . "\n";
        }
        echo "</pre>";
    } else {
        echo "<div class='warning'>⚠️ App not initialized, skipping routes test</div>";
    }
} catch (Exception $e) {
    echo "<div class='error'>❌ Routes Error: " . $e->getMessage() . "</div>";
}
echo "</div>";

// 7. Asset Files
echo "<div class='section'><h2>7. Frontend Assets Check</h2>";
$build_dir = __DIR__ . '/build';
if (is_dir($build_dir)) {
    echo "<div class='success'>✅ Build directory exists</div>";
    
    // List files in build/assets
    $assets_dir = $build_dir . '/assets';
    if (is_dir($assets_dir)) {
        $files = scandir($assets_dir);
        echo "<h3>Assets Found:</h3><pre>";
        foreach ($files as $file) {
            if ($file !== '.' && $file !== '..') {
                $size = filesize($assets_dir . '/' . $file);
                echo "$file (" . number_format($size / 1024, 2) . " KB)\n";
            }
        }
        echo "</pre>";
    }
} else {
    echo "<div class='error'>❌ Build directory not found at: $build_dir</div>";
}
echo "</div>";

// 8. Permissions Check
echo "<div class='section'><h2>8. Critical Permissions</h2>";
$perm_checks = [
    'storage' => $base_path . '/storage',
    'storage/logs' => $base_path . '/storage/logs',
    'storage/framework' => $base_path . '/storage/framework',
    'bootstrap/cache' => $base_path . '/bootstrap/cache',
];

foreach ($perm_checks as $name => $path) {
    if (file_exists($path)) {
        $perms = substr(sprintf('%o', fileperms($path)), -4);
        $writable = is_writable($path);
        echo "<div class='" . ($writable ? 'success' : 'warning') . "'>";
        echo $writable ? "✅ " : "⚠️ ";
        echo "$name: $perms " . ($writable ? "(Writable)" : "(NOT Writable)");
        echo "</div>";
    } else {
        echo "<div class='error'>❌ $name: Directory not found</div>";
    }
}
echo "</div>";

// 9. Recommendations
echo "<div class='section'><h2>9. 🎯 Diagnosis Summary</h2>";
echo "<div class='info'><strong>Next Steps:</strong></div>";
echo "<ol>";
echo "<li>Check any ❌ (red) items above - these are critical issues</li>";
echo "<li>Check ⚠️ (yellow) items - these might cause problems</li>";
echo "<li>Ensure APP_KEY is set in .env</li>";
echo "<li>Verify database credentials are correct</li>";
echo "<li>Ensure storage/ and bootstrap/cache/ are writable (755)</li>";
echo "<li>Check that routes are loading properly</li>";
echo "</ol>";
echo "</div>";

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