<?php
/**
 * FRONTEND DEBUG — Diagnose white screen / blank page
 * DELETE AFTER USE
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Try to find and bootstrap Laravel
$autoloadPaths = [
    __DIR__ . '/vendor/autoload.php',
    __DIR__ . '/../vendor/autoload.php',
];
$autoload = null;
foreach ($autoloadPaths as $p) { if (file_exists($p)) { $autoload = $p; break; } }

echo "<h2>🔍 Frontend Debug — Sarkin Mota Group</h2>";
echo "<pre style='background:#1e1e1e;color:#d4d4d4;padding:20px;font-size:13px;line-height:1.6;'>";

if (!$autoload) {
    die("❌ vendor/autoload.php not found. Run composer install first.");
}
require $autoload;

$appPaths = [
    __DIR__ . '/bootstrap/app.php',
    __DIR__ . '/../bootstrap/app.php',
];
$appPath = null;
foreach ($appPaths as $p) { if (file_exists($p)) { $appPath = $p; break; } }

if (!$appPath) {
    die("❌ bootstrap/app.php not found.");
}

$app = require_once $appPath;
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

// Capture the actual homepage output
try {
    $request = Illuminate\Http\Request::create('/', 'GET');
    $response = $kernel->handle($request);
    $content = $response->getContent();
    $status = $response->getStatusCode();

    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
    echo "📄 HOMEPAGE RESPONSE\n";
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
    echo "HTTP Status: $status\n";
    echo "Content Length: " . strlen($content) . " chars\n\n";

    // Check what's in the HTML
    $checks = [
        '<div id="app"' => 'React mount point (#app)',
        '<script' => 'Script tags present',
        '<link' => 'CSS link tags present',
        'manifest.json' => 'Vite references manifest',
        'csrf-token' => 'CSRF token present',
        'Sarkin Mota' => 'Brand name present',
    ];

    foreach ($checks as $needle => $label) {
        $found = strpos($content, $needle) !== false;
        echo ($found ? "✅" : "❌") . " $label\n";
    }

    echo "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
    echo "📄 RAW HTML (first 3000 chars):\n";
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
    echo htmlspecialchars(substr($content, 0, 3000));
    echo "\n\n";

    // Check build assets
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
    echo "📦 BUILD ASSETS CHECK\n";
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";

    $buildPaths = [
        __DIR__ . '/build/manifest.json',
        __DIR__ . '/../build/manifest.json',
        __DIR__ . '/public/build/manifest.json',
        __DIR__ . '/../public/build/manifest.json',
    ];

    $manifestPath = null;
    foreach ($buildPaths as $p) { if (file_exists($p)) { $manifestPath = $p; break; } }

    if ($manifestPath) {
        echo "✅ manifest.json found at: $manifestPath\n";
        $manifest = json_decode(file_get_contents($manifestPath), true);
        $buildDir = dirname($manifestPath) . '/';

        foreach ($manifest as $key => $entry) {
            if (isset($entry['file'])) {
                $assetPath = $buildDir . $entry['file'];
                $exists = file_exists($assetPath);
                $size = $exists ? filesize($assetPath) : 0;
                echo ($exists ? "✅" : "❌") . " {$entry['file']}";
                if ($exists) echo " (" . round($size/1024, 1) . "KB)";
                echo "\n";
            }
            if (isset($entry['css'])) {
                foreach ($entry['css'] as $css) {
                    $cssPath = $buildDir . $css;
                    $exists = file_exists($cssPath);
                    echo ($exists ? "✅" : "❌") . " $css (CSS)\n";
                }
            }
        }

        // Check if build dir is at the right place relative to request
        echo "\n📌 Asset URLs expected at:\n";
        echo "   https://sarkinmota-autos.com/build/assets/...\n";
        echo "   OR https://sarkinmota-autos.com/public/build/assets/...\n";

        // Test if assets are accessible via HTTP
        foreach ($manifest as $entry) {
            if (isset($entry['file'])) {
                $testUrl = '/build/' . $entry['file'];
                $testReq = Illuminate\Http\Request::create($testUrl, 'GET');
                try {
                    $testRes = $kernel->handle($testReq);
                    echo "\n🔗 $testUrl → HTTP " . $testRes->getStatusCode() . " (" . strlen($testRes->getContent()) . " bytes)";
                } catch (Exception $e) {
                    echo "\n🔗 $testUrl → ERROR";
                }
            }
            break; // just test first one
        }

    } else {
        echo "❌ manifest.json NOT FOUND in any expected location\n";
        echo "Expected at:\n";
        foreach ($buildPaths as $p) echo "  - $p\n";
    }

    // Check blade view
    echo "\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
    echo "🖥️ BLADE VIEW CHECK\n";
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";

    // Check if the blade file exists
    $bladePaths = [
        __DIR__ . '/../resources/views/app.blade.php',
        __DIR__ . '/resources/views/app.blade.php',
    ];
    foreach ($bladePaths as $bp) {
        echo (file_exists($bp) ? "✅" : "❌") . " Blade view: $bp\n";
    }

    // Check compiled views
    $viewDirs = [
        __DIR__ . '/../storage/framework/views',
        __DIR__ . '/storage/framework/views',
    ];
    foreach ($viewDirs as $vd) {
        if (is_dir($vd)) {
            $compiled = glob($vd . '/*.php');
            echo "Compiled views: " . count($compiled) . " files in $vd\n";
            foreach ($compiled as $c) {
                $cContent = file_get_contents($c);
                if (strpos($cContent, '@vite') !== false || strpos($cContent, 'manifest') !== false) {
                    echo "  📝 " . basename($c) . " — contains Vite/manifest references\n";
                }
            }
        }
    }

    echo "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
    echo "🔧 QUICK FIX SUGGESTIONS\n";
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";

    if (strlen($content) < 500) {
        echo "⚠️ Very short response — likely an error page or redirect\n";
        echo "   Check: APP_URL in .env matches your domain\n";
        echo "   Check: .env has APP_ENV=production (not local)\n";
    }

    if (strpos($content, '<div id="app"') === false) {
        echo "⚠️ React mount point missing — blade template may not be loading\n";
    }

    $hasScripts = strpos($content, '.js') !== false;
    $hasStyles = strpos($content, '.css') !== false;
    if (!$hasScripts && !$hasStyles) {
        echo "⚠️ No JS/CSS links in HTML — Vite may not be injecting assets\n";
        echo "   Try: php artisan optimize:clear\n";
    }

} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
    echo $e->getTraceAsString() . "\n";
}

echo "</pre>";
echo "<p style='color:red;font-weight:bold;'>⚠️ DELETE this file (frontend-debug.php) after use!</p>";
