<?php
/**
 * Complete Laravel White Screen Diagnostic Tool
 * Place this file in your Laravel root directory (where artisan is located)
 * Access: https://sarkinmota-autos.com/diagnose.php
 */

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

echo "<!DOCTYPE html>
<html>
<head>
    <title>Laravel Diagnostic Tool</title>
    <style>
        body { font-family: monospace; margin: 20px; background: #f5f5f5; }
        .section { background: white; margin: 20px 0; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .success { color: green; font-weight: bold; }
        .error { color: red; font-weight: bold; }
        .warning { color: orange; font-weight: bold; }
        .info { color: blue; }
        pre { background: #f0f0f0; padding: 10px; overflow-x: auto; }
        h2 { margin-top: 0; color: #333; }
        table { width: 100%; border-collapse: collapse; }
        td, th { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; }
    </style>
</head>
<body>
    <h1>🔍 Laravel White Screen Diagnostic Tool</h1>
    <p><strong>URL:</strong> https://sarkinmota-autos.com/diagnose.php</p>
    <p><strong>Time:</strong> " . date('Y-m-d H:i:s') . "</p>";

// Section 1: Server Information
echo "<div class='section'>
    <h2>📡 Section 1: Server Information</h2>
    <table>
        <tr><td><strong>Document Root:</strong></td><td>{$_SERVER['DOCUMENT_ROOT']}</td></tr>
        <tr><td><strong>Script Filename:</strong></td><td>{$_SERVER['SCRIPT_FILENAME']}</td></tr>
        <tr><td><strong>Current Directory:</strong></td><td>" . __DIR__ . "</td></tr>
        <tr><td><strong>PHP Version:</strong></td><td>" . PHP_VERSION . "</td></tr>
        <tr><td><strong>Server Software:</strong></td><td>" . ($_SERVER['SERVER_SOFTWARE'] ?? 'Unknown') . "</td></tr>
        <tr><td><strong>Request URI:</strong></td><td>{$_SERVER['REQUEST_URI']}</td></tr>
    </table>
</div>";

// Section 2: Critical File Checks
echo "<div class='section'>
    <h2>📁 Section 2: Critical File Locations</h2>
    <table>
        <tr><th>File/Folder</th><th>Expected Path</th><th>Status</th></tr>";

$checks = [
    'public/index.php' => __DIR__ . '/public/index.php',
    'vendor/autoload.php' => __DIR__ . '/vendor/autoload.php',
    'bootstrap/app.php' => __DIR__ . '/bootstrap/app.php',
    '.env' => __DIR__ . '/.env',
    'artisan' => __DIR__ . '/artisan',
    'routes/web.php' => __DIR__ . '/routes/web.php',
    'storage' => __DIR__ . '/storage',
    'bootstrap/cache' => __DIR__ . '/bootstrap/cache',
];

foreach ($checks as $name => $path) {
    $exists = file_exists($path);
    $status = $exists ? "<span class='success'>✅ EXISTS</span>" : "<span class='error'>❌ MISSING</span>";
    echo "<tr><td><strong>$name</strong></td><td>$path</td><td>$status</td></tr>";
}
echo "</table></div>";

// Section 3: .htaccess Files
echo "<div class='section'>
    <h2>🔧 Section 3: .htaccess Files</h2>";

$htaccessFiles = [
    'Root .htaccess' => __DIR__ . '/.htaccess',
    'Public .htaccess' => __DIR__ . '/public/.htaccess',
];

foreach ($htaccessFiles as $name => $path) {
    if (file_exists($path)) {
        echo "<strong>$name:</strong> <span class='success'>✅ EXISTS</span><br>";
        echo "<pre>" . htmlspecialchars(file_get_contents($path)) . "</pre>";
    } else {
        echo "<strong>$name:</strong> <span class='error'>❌ NOT FOUND</span><br>";
    }
}
echo "</div>";

// Section 4: URL Rewriting Test
echo "<div class='section'>
    <h2>🔄 Section 4: URL Rewriting Test</h2>";

// Create test files
$testFiles = [
    'public/test-1.txt' => 'Test file 1 in public',
    'test-2.txt' => 'Test file 2 in root',
];

foreach ($testFiles as $file => $content) {
    file_put_contents(__DIR__ . '/' . $file, $content);
}

echo "<table>
    <tr><th>Test</th><th>URL</th><th>Expected</th><th>Result</th></tr>
    <tr>
        <td>Direct file access</td>
        <td><a href='/test-2.txt' target='_blank'>/test-2.txt</a></td>
        <td>Should show text</td>
        <td id='test2'>Check manually</td>
    </tr>
    <tr>
        <td>Public file access</td>
        <td><a href='/public/test-1.txt' target='_blank'>/public/test-1.txt</a></td>
        <td>Should show text</td>
        <td id='test1'>Check manually</td>
    </tr>
    <tr>
        <td>PHP file in public</td>
        <td><a href='/public/info.php' target='_blank'>/public/info.php</a></td>
        <td>PHP info page</td>
        <td id='phpinfo'>Will create if missing</td>
    </tr>
</table>";

// Create info.php if it doesn't exist
if (!file_exists(__DIR__ . '/public/info.php')) {
    file_put_contents(__DIR__ . '/public/info.php', '<?php phpinfo(); ?>');
}
echo "</div>";

// Section 5: Laravel Bootstrap Test
echo "<div class='section'>
    <h2>🎯 Section 5: Laravel Direct Bootstrap Test</h2>";

try {
    if (file_exists(__DIR__ . '/vendor/autoload.php') && file_exists(__DIR__ . '/bootstrap/app.php')) {
        require __DIR__ . '/vendor/autoload.php';
        $app = require_once __DIR__ . '/bootstrap/app.php';
        $kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
        
        echo "<span class='success'>✅ Laravel kernel created successfully</span><br>";
        
        // Test with a fake request to home
        $request = Illuminate\Http\Request::create('/', 'GET');
        try {
            $response = $kernel->handle($request);
            echo "<span class='success'>✅ Laravel handled request to '/' successfully</span><br>";
            echo "<strong>Response status:</strong> " . $response->getStatusCode() . "<br>";
            echo "<strong>Response content length:</strong> " . strlen($response->getContent()) . " bytes<br>";
            
            if (strlen($response->getContent()) < 100 && empty(trim($response->getContent()))) {
                echo "<span class='error'>⚠️ WARNING: Response to '/' is empty (white screen)!</span><br>";
                echo "This means your route '/' is returning nothing.<br>";
            } else {
                echo "<span class='success'>✅ Response has content!</span><br>";
            }
        } catch (Exception $e) {
            echo "<span class='error'>❌ Error handling request: " . $e->getMessage() . "</span><br>";
        }
    } else {
        echo "<span class='error'>❌ Cannot bootstrap Laravel - missing files</span><br>";
    }
} catch (Exception $e) {
    echo "<span class='error'>❌ Bootstrap error: " . $e->getMessage() . "</span><br>";
}
echo "</div>";

// Section 6: Routes Analysis
echo "<div class='section'>
    <h2>🗺️ Section 6: Routes Analysis</h2>";

if (file_exists(__DIR__ . '/routes/web.php')) {
    echo "<strong>routes/web.php content:</strong><br>";
    echo "<pre>" . htmlspecialchars(file_get_contents(__DIR__ . '/routes/web.php')) . "</pre>";
    
    // Try to get registered routes
    try {
        require __DIR__ . '/vendor/autoload.php';
        $app = require_once __DIR__ . '/bootstrap/app.php';
        $router = $app->make(Illuminate\Routing\Router::class);
        
        echo "<strong>Registered Routes:</strong><br>";
        $routes = $router->getRoutes();
        if (count($routes) > 0) {
            echo "<table><tr><th>Method</th><th>URI</th><th>Action</th></tr>";
            foreach ($routes as $route) {
                echo "<tr>
                    <td>" . implode(',', $route->methods()) . "</td>
                    <td>" . $route->uri() . "</td>
                    <td>" . ($route->getActionName() ?? 'Closure') . "</td>
                </tr>";
            }
            echo "</table>";
        } else {
            echo "<span class='warning'>⚠️ No routes registered!</span><br>";
        }
    } catch (Exception $e) {
        echo "<span class='error'>Could not list routes: " . $e->getMessage() . "</span><br>";
    }
} else {
    echo "<span class='error'>❌ routes/web.php not found</span><br>";
}
echo "</div>";

// Section 7: .env Configuration
echo "<div class='section'>
    <h2>⚙️ Section 7: .env Configuration</h2>";

if (file_exists(__DIR__ . '/.env')) {
    $envContent = file_get_contents(__DIR__ . '/.env');
    $lines = explode("\n", $envContent);
    $envVars = [];
    foreach ($lines as $line) {
        if (strpos($line, '=') !== false && strpos($line, '#') !== 0) {
            $parts = explode('=', $line, 2);
            $key = trim($parts[0]);
            $value = trim($parts[1] ?? '');
            $envVars[$key] = $value;
        }
    }
    
    $importantVars = ['APP_ENV', 'APP_DEBUG', 'APP_URL', 'DB_DATABASE'];
    echo "<table>";
    foreach ($importantVars as $var) {
        $value = $envVars[$var] ?? 'NOT SET';
        $status = ($var == 'APP_DEBUG' && $value == 'true') ? "<span class='info'>Debug ON</span>" : "";
        echo "<tr><td><strong>$var</strong></td><td>$value</td><td>$status</td></tr>";
    }
    echo "</table>";
    
    if (isset($envVars['APP_DEBUG']) && $envVars['APP_DEBUG'] == 'false') {
        echo "<span class='warning'>⚠️ APP_DEBUG is false. Set to true to see errors.</span><br>";
    }
} else {
    echo "<span class='error'>❌ .env file not found - copy .env.example to .env</span><br>";
}
echo "</div>";

// Section 8: Permissions
echo "<div class='section'>
    <h2>🔐 Section 8: File Permissions</h2>
    <table>
        <tr><th>Path</th><th>Writable?</th></tr>";

$permChecks = [
    'storage' => __DIR__ . '/storage',
    'storage/framework' => __DIR__ . '/storage/framework',
    'storage/framework/views' => __DIR__ . '/storage/framework/views',
    'storage/logs' => __DIR__ . '/storage/logs',
    'bootstrap/cache' => __DIR__ . '/bootstrap/cache',
];

foreach ($permChecks as $name => $path) {
    $writable = is_writable($path);
    $status = $writable ? "<span class='success'>✅ Writable</span>" : "<span class='error'>❌ Not writable</span>";
    echo "<tr><td><strong>$name</strong></td><td>$status</td></tr>";
}
echo "</table></div>";

// Section 9: Quick Fix Recommendations
echo "<div class='section'>
    <h2>🔧 Section 9: Fix Recommendations</h2>";

// Check for root route
$hasRootRoute = false;
if (file_exists(__DIR__ . '/routes/web.php')) {
    $routeContent = file_get_contents(__DIR__ . '/routes/web.php');
    if (strpos($routeContent, "Route::get('/'") !== false || strpos($routeContent, "Route::get('/',") !== false) {
        $hasRootRoute = true;
    }
}

if (!$hasRootRoute) {
    echo "<div class='error'>❌ No root route '/' found in routes/web.php</div>";
    echo "<pre>Add this to your routes/web.php:
Route::get('/', function () {
    return view('welcome');
    // Or return response()->json(['message' => 'Working']);
});</pre>";
}

// Check for correct .htaccess
$rootHtaccess = __DIR__ . '/.htaccess';
$publicHtaccess = __DIR__ . '/public/.htaccess';

if (!file_exists($rootHtaccess) && !file_exists($publicHtaccess)) {
    echo "<div class='error'>❌ No .htaccess file found. Create one in /public/ folder:</div>";
    echo "<pre>&lt;IfModule mod_rewrite.c&gt;
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
&lt;/IfModule&gt;</pre>";
}

echo "<hr>";

// Final test URLs
echo "<h3>🧪 Final Test URLs to try:</h3>
<ul>
    <li><a href='/public' target='_blank'>/public</a> - Access Laravel via public folder</li>
    <li><a href='/public/index.php' target='_blank'>/public/index.php</a> - Direct access to index.php</li>
    <li><a href='/test-2.txt' target='_blank'>/test-2.txt</a> - Test static file access</li>
    <li><a href='/public/test-1.txt' target='_blank'>/public/test-1.txt</a> - Test public file access</li>
    <li><a href='/public/info.php' target='_blank'>/public/info.php</a> - PHP info</li>
</ul>";

echo "<div class='success' style='margin-top: 20px; padding: 10px; background: #d4edda; border-radius: 5px;'>
    <strong>📝 Next Steps:</strong><br>
    1. Look for any ❌ or ⚠️ above<br>
    2. Check what <a href='/public/index.php' target='_blank'>/public/index.php</a> returns<br>
    3. If that works, the issue is .htaccess configuration<br>
    4. If that gives white screen, check Laravel routes and views<br>
    5. Set APP_DEBUG=true in .env to see actual errors
</div>";

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

// Cleanup test files
// Note: Comment these out if you want to keep test files
if (file_exists(__DIR__ . '/test-2.txt')) unlink(__DIR__ . '/test-2.txt');
if (file_exists(__DIR__ . '/public/test-1.txt')) unlink(__DIR__ . '/public/test-1.txt');
?>