<?php
/**
 * FULL SITE DIAGNOSTIC — Sarkin Mota Group
 *
 * Open: https://YOURDOMAIN/full-diagnose.php
 * (With root .htaccess, no /public needed in the URL)
 *
 * DELETE THIS FILE after fixing issues — it exposes server details.
 */
error_reporting(E_ALL);
ini_set('display_errors', '1');

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function fd_ok(bool $pass): string
{
    return $pass ? 'pass' : 'fail';
}

function fd_icon(bool $pass): string
{
    return $pass ? '✅' : '❌';
}

function fd_warn(bool $pass): string
{
    return $pass ? 'pass' : 'warn';
}

function fd_human_bytes(int $bytes): string
{
    if ($bytes >= 1048576) {
        return round($bytes / 1048576, 2) . ' MB';
    }
    if ($bytes >= 1024) {
        return round($bytes / 1024, 1) . ' KB';
    }
    return $bytes . ' B';
}

function fd_check(string $label, bool $pass, string $detail = '', string $fix = ''): array
{
    return compact('label', 'pass', 'detail', 'fix');
}

function fd_env_value(string $path, string $key): ?string
{
    if (! is_file($path)) {
        return null;
    }
    $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#')) {
            continue;
        }
        if (str_starts_with($line, $key . '=')) {
            $v = substr($line, strlen($key) + 1);
            return trim($v, " \t\"'");
        }
    }
    return null;
}

function fd_http_get(string $url): array
{
    $ctx = stream_context_create([
        'http' => [
            'method' => 'GET',
            'timeout' => 10,
            'ignore_errors' => true,
            'header' => "User-Agent: SarkinMota-FullDiagnose/1.0\r\n",
        ],
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false,
        ],
    ]);
    $body = @file_get_contents($url, false, $ctx);
    $code = 0;
    if (isset($http_response_header[0]) && preg_match('/\d{3}/', $http_response_header[0], $m)) {
        $code = (int) $m[0];
    }
    return ['code' => $code, 'body' => $body === false ? '' : $body, 'headers' => $http_response_header ?? []];
}

function fd_first_existing(array $paths): ?string
{
    foreach ($paths as $p) {
        if ($p && (is_file($p) || is_dir($p))) {
            return $p;
        }
    }
    return null;
}

// ---------------------------------------------------------------------------
// Detect layout (standard Laravel vs flattened deploy-package)
// ---------------------------------------------------------------------------

$publicDir = __DIR__;
$rootDir = is_file($publicDir . '/../vendor/autoload.php')
    ? realpath($publicDir . '/..')
    : $publicDir;

$layout = ($rootDir === realpath($publicDir)) ? 'flattened (docroot ≈ public)' : 'standard (docroot = project root, public/ subfolder)';

$checks = [];
$sections = [];

// ---------------------------------------------------------------------------
// 1. SERVER & PHP
// ---------------------------------------------------------------------------

$phpOk = version_compare(PHP_VERSION, '8.1.0', '>=');
$checks[] = fd_check('PHP 8.1+', $phpOk, 'Current: ' . PHP_VERSION, 'Upgrade PHP in cPanel to 8.1 or 8.2');

$exts = ['pdo', 'pdo_mysql', 'mbstring', 'openssl', 'tokenizer', 'xml', 'ctype', 'json', 'fileinfo', 'curl'];
$extResults = [];
foreach ($exts as $ext) {
    $loaded = extension_loaded($ext);
    $extResults[] = fd_check("PHP ext: $ext", $loaded, $loaded ? 'loaded' : 'MISSING', "Enable $ext in cPanel → Select PHP Version → Extensions");
    $checks[] = $extResults[count($extResults) - 1];
}

$sections['1_server'] = [
    'title' => 'Server & PHP',
    'items' => array_merge(
        [$checks[count($checks) - count($exts) - 1]],
        $extResults
    ),
    'meta' => [
        'SERVER_SOFTWARE' => $_SERVER['SERVER_SOFTWARE'] ?? 'unknown',
        'DOCUMENT_ROOT' => $_SERVER['DOCUMENT_ROOT'] ?? 'unknown',
        'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? 'unknown',
        'REQUEST_URI' => $_SERVER['REQUEST_URI'] ?? 'unknown',
        'HTTPS' => (! empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'yes' : 'no',
        'Layout detected' => $layout,
        'Public dir (__DIR__)' => $publicDir,
        'Project root' => $rootDir,
    ],
];

// ---------------------------------------------------------------------------
// 2. CRITICAL FILES
// ---------------------------------------------------------------------------

$fileMap = [
    'Root .htaccess' => [$rootDir . '/.htaccess'],
    'Root index.php' => [$rootDir . '/index.php'],
    'public/.htaccess' => [$publicDir . '/.htaccess'],
    'public/index.php' => [$publicDir . '/index.php'],
    'vendor/autoload.php' => [$rootDir . '/vendor/autoload.php', $publicDir . '/vendor/autoload.php'],
    'bootstrap/app.php' => [$rootDir . '/bootstrap/app.php', $publicDir . '/bootstrap/app.php'],
    '.env' => [$rootDir . '/.env', $publicDir . '/.env'],
    '.env.example' => [$rootDir . '/.env.example', $publicDir . '/.env.example'],
    'routes/web.php' => [$rootDir . '/routes/web.php'],
    'resources/views/app.blade.php' => [$rootDir . '/resources/views/app.blade.php', $publicDir . '/resources/views/app.blade.php'],
    'config/sanctum.php' => [$rootDir . '/config/sanctum.php'],
    'config/app.php' => [$rootDir . '/config/app.php'],
];

$fileItems = [];
foreach ($fileMap as $label => $paths) {
    $found = fd_first_existing($paths);
    $pass = $found !== null;
    $detail = $pass ? $found : 'Tried: ' . implode(' | ', $paths);
    $fix = match ($label) {
        'vendor/autoload.php' => 'Upload vendor/ from your PC (after composer install) or run Composer on server',
        '.env' => 'Copy .env.example → .env and set DB + APP_URL',
        'Root .htaccess' => 'Upload project-root .htaccess (clean URLs without /public)',
        default => 'Upload missing file from your local project',
    };
    $item = fd_check($label, $pass, $detail, $pass ? '' : $fix);
    $fileItems[] = $item;
    $checks[] = $item;
}

$sections['2_files'] = ['title' => 'Critical files', 'items' => $fileItems];

// ---------------------------------------------------------------------------
// 3. .ENV
// ---------------------------------------------------------------------------

$envPath = fd_first_existing([$rootDir . '/.env', $publicDir . '/.env']);
$envItems = [];

$envKeys = [
    'APP_NAME' => 'Application name',
    'APP_ENV' => 'Should be production on live server',
    'APP_KEY' => 'Required — run key:generate or skmt-setup',
    'APP_DEBUG' => 'Should be false on production',
    'APP_URL' => 'Must match domain (no /public)',
    'DB_CONNECTION' => 'Usually mysql',
    'DB_HOST' => 'Often localhost',
    'DB_DATABASE' => 'Database name from cPanel',
    'DB_USERNAME' => 'Database user',
    'DB_PASSWORD' => 'Database password (can be empty on some hosts)',
];

foreach ($envKeys as $key => $hint) {
    $val = $envPath ? fd_env_value($envPath, $key) : null;
    $pass = $val !== null && $val !== '';
    if ($key === 'APP_DEBUG' && $val !== null) {
        $pass = true;
        $detail = $val . ' — ' . ($val === 'false' || $val === '0' ? 'OK for production' : '⚠️ true shows errors to users');
    } elseif ($key === 'APP_KEY') {
        $pass = $val !== null && strlen($val) > 10;
        $detail = $pass ? 'Set (' . strlen($val) . ' chars)' : 'EMPTY';
    } elseif ($key === 'APP_URL') {
        $pass = $val !== null && $val !== '' && ! str_contains($val, '/public');
        $detail = ($val ?? 'NOT SET') . ($val && str_contains($val, '/public') ? ' — remove /public from APP_URL' : '');
    } elseif ($key === 'DB_PASSWORD') {
        $pass = $val !== null;
        $detail = ($val === '' || $val === null) ? '(empty)' : 'Set';
    } else {
        $detail = $val ?? 'NOT SET';
    }
    $item = fd_check("$key", $pass || ($key === 'DB_PASSWORD' && $val !== null), $detail, $hint);
    $envItems[] = $item;
    $checks[] = $item;
}

$assetUrl = $envPath ? fd_env_value($envPath, 'ASSET_URL') : null;
if ($assetUrl !== null) {
    $pass = ! str_contains($assetUrl, '/public');
    $item = fd_check('ASSET_URL', $pass, $assetUrl ?: '(empty)', 'Remove ASSET_URL or set without /public');
    $envItems[] = $item;
    $checks[] = $item;
}

$sections['3_env'] = ['title' => '.env configuration', 'items' => $envItems, 'meta' => ['env file' => $envPath ?? 'NOT FOUND']];

// ---------------------------------------------------------------------------
// 4. VITE / FRONTEND BUILD (common white-screen cause)
// ---------------------------------------------------------------------------

$manifestPaths = [
    $publicDir . '/build/manifest.json',
    $rootDir . '/public/build/manifest.json',
    $rootDir . '/build/manifest.json',
];
$manifestPath = fd_first_existing($manifestPaths);
$viteItems = [];

$viteItems[] = fd_check(
    'Vite manifest.json',
    $manifestPath !== null,
    $manifestPath ?? 'Not found. Upload public/build/ from your PC after npm run build',
    'Run npm run build locally, upload entire public/build/ folder'
);

$manifest = null;
$buildDir = null;
$missingAssets = [];
$assetItems = [];

if ($manifestPath) {
    $buildDir = dirname($manifestPath);
    $manifest = json_decode(file_get_contents($manifestPath), true);
    $viteItems[] = fd_check('manifest.json valid JSON', is_array($manifest), is_array($manifest) ? count($manifest) . ' entries' : 'Invalid JSON');

    if (is_array($manifest)) {
        foreach ($manifest as $key => $entry) {
            foreach (['file'] as $k) {
                if (! empty($entry[$k])) {
                    $assetPath = $buildDir . '/' . $entry[$k];
                    $exists = is_file($assetPath);
                    if (! $exists) {
                        $missingAssets[] = $entry[$k];
                    }
                    $assetItems[] = fd_check('Asset: ' . $entry[$k], $exists, $exists ? fd_human_bytes(filesize($assetPath)) : 'MISSING on disk', 'Re-upload public/build/assets/');
                }
            }
            if (! empty($entry['css']) && is_array($entry['css'])) {
                foreach ($entry['css'] as $css) {
                    $cssPath = $buildDir . '/' . $css;
                    $exists = is_file($cssPath);
                    if (! $exists) {
                        $missingAssets[] = $css;
                    }
                    $assetItems[] = fd_check('Asset CSS: ' . $css, $exists, $exists ? fd_human_bytes(filesize($cssPath)) : 'MISSING', 'Re-upload public/build/assets/');
                }
            }
        }
    }
}

$sections['4_vite'] = ['title' => 'Frontend build (Vite)', 'items' => array_merge($viteItems, $assetItems)];

// ---------------------------------------------------------------------------
// 5. PERMISSIONS
// ---------------------------------------------------------------------------

$permDirs = [
    'storage' => $rootDir . '/storage',
    'storage/framework' => $rootDir . '/storage/framework',
    'storage/framework/cache' => $rootDir . '/storage/framework/cache',
    'storage/framework/sessions' => $rootDir . '/storage/framework/sessions',
    'storage/framework/views' => $rootDir . '/storage/framework/views',
    'storage/logs' => $rootDir . '/storage/logs',
    'bootstrap/cache' => $rootDir . '/bootstrap/cache',
];

$permItems = [];
foreach ($permDirs as $label => $path) {
    $exists = is_dir($path);
    $writable = $exists && is_writable($path);
    $perms = $exists ? substr(sprintf('%o', fileperms($path)), -4) : 'n/a';
    $permItems[] = fd_check($label, $exists && $writable, ($exists ? "perms $perms" : 'MISSING') . ($writable ? ', writable' : ', NOT writable'), 'chmod 755 folders, 644 files; storage/ must be writable');
    $checks[] = $permItems[count($permItems) - 1];
}

$sections['5_permissions'] = ['title' => 'Writable directories', 'items' => $permItems];

// ---------------------------------------------------------------------------
// 6. LARAVEL BOOTSTRAP
// ---------------------------------------------------------------------------

$laravelItems = [];
$app = null;
$kernel = null;
$bootstrapError = null;

$autoload = fd_first_existing([$rootDir . '/vendor/autoload.php', $publicDir . '/vendor/autoload.php']);
$bootstrap = fd_first_existing([$rootDir . '/bootstrap/app.php', $publicDir . '/bootstrap/app.php']);

if ($autoload && $bootstrap && $envPath) {
    try {
        require_once $autoload;
        $app = require_once $bootstrap;
        $laravelItems[] = fd_check('Laravel application boot', true, get_class($app));
        try {
            $kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
            $laravelItems[] = fd_check('HTTP Kernel', true, get_class($kernel));
        } catch (Throwable $e) {
            $laravelItems[] = fd_check('HTTP Kernel', false, $e->getMessage(), 'Check config/ and .env');
        }
    } catch (Throwable $e) {
        $bootstrapError = $e;
        $laravelItems[] = fd_check('Laravel bootstrap', false, $e->getMessage() . ' @ ' . $e->getFile() . ':' . $e->getLine(), 'Fix .env, vendor/, or config/sanctum.php');
    }
} else {
    $laravelItems[] = fd_check('Laravel bootstrap', false, 'Missing vendor, bootstrap, or .env', 'Upload vendor/, create .env');
}

// Sanctum CSRF class (ValidateCsrfToken vs VerifyCsrfToken bug)
$sanctumPath = $rootDir . '/config/sanctum.php';
if (is_file($sanctumPath)) {
    $sanctumContent = file_get_contents($sanctumPath);
    $badCsrf = str_contains($sanctumContent, 'ValidateCsrfToken');
    $laravelItems[] = fd_check(
        'config/sanctum.php CSRF class',
        ! $badCsrf,
        $badCsrf ? 'Still references removed ValidateCsrfToken class' : 'Uses VerifyCsrfToken / App middleware',
        'Set validate_csrf_token => App\\Http\\Middleware\\VerifyCsrfToken::class'
    );
}

$sections['6_laravel'] = ['title' => 'Laravel bootstrap', 'items' => $laravelItems];

// ---------------------------------------------------------------------------
// 7. DATABASE
// ---------------------------------------------------------------------------

$dbItems = [];
if ($app) {
    try {
        $db = $app->make('db');
        $pdo = $db->connection()->getPdo();
        $dbItems[] = fd_check('Database connection', true, 'PDO connected');

        $dbName = $db->select('SELECT DATABASE() as n')[0]->n ?? '?';
        $dbItems[] = fd_check('Active database', true, $dbName);

        $tables = $db->select('SHOW TABLES');
        $tableCount = count($tables);
        $dbItems[] = fd_check('Tables exist', $tableCount > 0, "$tableCount tables", 'Run migrations via skmt-setup.php');

        $hasUsers = false;
        $userCount = 0;
        try {
            $userCount = (int) $db->table('users')->count();
            $hasUsers = $userCount > 0;
        } catch (Throwable $e) {
            $hasUsers = false;
        }
        $dbItems[] = fd_check('users table + rows', $hasUsers, $hasUsers ? "$userCount user(s)" : ($tableCount ? 'users empty or missing — run db:seed' : 'No tables yet'), 'Migrate + seed: admin@sarkinmotagroup.com / Admin@1234');

        try {
            $roleCount = (int) $db->table('roles')->count();
            $dbItems[] = fd_check('roles seeded', $roleCount > 0, "$roleCount roles", 'Run php artisan db:seed');
        } catch (Throwable $e) {
            $dbItems[] = fd_check('roles table', false, $e->getMessage(), 'Run migrations');
        }
    } catch (Throwable $e) {
        $dbItems[] = fd_check('Database connection', false, $e->getMessage(), 'Fix DB_* in .env — use cPanel MySQL credentials');
    }
} else {
    $dbItems[] = fd_check('Database', false, 'Laravel not booted', 'Fix bootstrap first');
}

$sections['7_database'] = ['title' => 'Database', 'items' => $dbItems];

// ---------------------------------------------------------------------------
// 8. HOMEPAGE & WHITE SCREEN ANALYSIS
// ---------------------------------------------------------------------------

$homeItems = [];
$homeHtml = '';
$homeCode = 0;

$scheme = (! empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$baseUrl = $scheme . '://' . $host;

if ($kernel) {
    try {
        $request = Illuminate\Http\Request::create('/', 'GET');
        $response = $kernel->handle($request);
        $homeCode = $response->getStatusCode();
        $homeHtml = $response->getContent();
        $kernel->terminate($request, $response);

        $homeItems[] = fd_check('Homepage HTTP status', $homeCode >= 200 && $homeCode < 400, "HTTP $homeCode", $homeCode >= 500 ? 'Check storage/logs/laravel.log' : '');
        $homeItems[] = fd_check('Homepage body length', strlen($homeHtml) > 200, strlen($homeHtml) . ' bytes', 'Response too short — likely error or redirect');

        $needles = [
            '<div id="app"' => 'React mount point #app',
            'csrf-token' => 'CSRF meta tag',
            '@vite' => 'Blade still has @vite (uncompiled?)',
            'build/assets/' => 'Vite asset URLs in HTML',
            '.js' => 'JavaScript reference',
            '.css' => 'CSS reference',
        ];
        foreach ($needles as $needle => $label) {
            $found = str_contains($homeHtml, $needle);
            $pass = $found;
            if ($needle === '@vite') {
                $pass = ! $found;
            }
            $homeItems[] = fd_check("HTML: $label", $pass, $found ? 'found' : 'NOT found', $needle === 'build/assets/' ? 'Fix APP_URL, upload public/build, clear view cache' : '');
        }

        if (preg_match_all('/(?:src|href)=["\']([^"\']+)["\']/', $homeHtml, $m)) {
            $assetUrls = array_filter($m[1], fn ($u) => str_contains($u, 'build/') || str_contains($u, '.js') || str_contains($u, '.css'));
            foreach (array_slice(array_unique($assetUrls), 0, 6) as $rel) {
                $url = str_starts_with($rel, 'http') ? $rel : rtrim($baseUrl, '/') . '/' . ltrim($rel, '/');
                $res = fd_http_get($url);
                $ok = $res['code'] === 200 && strlen($res['body']) > 100;
                $homeItems[] = fd_check('HTTP asset: ' . $rel, $ok, 'HTTP ' . $res['code'] . ', ' . fd_human_bytes(strlen($res['body'])), 'Asset 404 — check root .htaccess maps public/build');
            }
        }
    } catch (Throwable $e) {
        $homeItems[] = fd_check('Render homepage', false, $e->getMessage(), 'See laravel.log');
    }
} else {
    $res = fd_http_get($baseUrl . '/');
    $homeCode = $res['code'];
    $homeHtml = $res['body'];
    $homeItems[] = fd_check('Homepage (HTTP fetch)', $res['code'] === 200, 'HTTP ' . $res['code'] . ', ' . fd_human_bytes(strlen($res['body'])), 'Laravel not booted — fix vendor/.env first');
}

// White screen verdict
$whiteScreenCauses = [];
if ($homeCode >= 500) {
    $whiteScreenCauses[] = 'Server returns HTTP ' . $homeCode . ' — backend error (check laravel.log)';
}
if ($manifestPath === null) {
    $whiteScreenCauses[] = 'Missing Vite manifest — Laravel throws before HTML loads';
}
if ($missingAssets) {
    $whiteScreenCauses[] = 'Missing built JS/CSS files: ' . implode(', ', $missingAssets);
}
if ($homeHtml && ! str_contains($homeHtml, '<div id="app"')) {
    $whiteScreenCauses[] = 'HTML has no #app div — wrong view or error page';
}
if ($homeHtml && str_contains($homeHtml, '<div id="app"') && ! str_contains($homeHtml, '.js')) {
    $whiteScreenCauses[] = 'HTML has #app but no JS — Vite assets not injected (manifest/build issue)';
}
if ($homeHtml && strlen($homeHtml) < 300) {
    $whiteScreenCauses[] = 'Homepage response is nearly empty';
}
if ($bootstrapError) {
    $whiteScreenCauses[] = 'Laravel failed to boot: ' . $bootstrapError->getMessage();
}

$sections['8_homepage'] = [
    'title' => 'Homepage & white screen',
    'items' => $homeItems,
    'causes' => $whiteScreenCauses,
    'html_preview' => $homeHtml ? htmlspecialchars(substr($homeHtml, 0, 4000)) : '',
];

// ---------------------------------------------------------------------------
// 9. LARAVEL LOG (last errors)
// ---------------------------------------------------------------------------

$logItems = [];
$logPath = $rootDir . '/storage/logs/laravel.log';
if (is_file($logPath) && is_readable($logPath)) {
    $logSize = filesize($logPath);
    $tail = '';
    if ($logSize > 0) {
        $fh = fopen($logPath, 'r');
        $chunk = $logSize > 50000 ? 50000 : $logSize;
        if ($logSize > $chunk) {
            fseek($fh, -$chunk, SEEK_END);
        }
        $tail = fread($fh, $chunk);
        fclose($fh);
    }
    $logItems[] = fd_check('laravel.log readable', true, fd_human_bytes($logSize));
    $sections['9_log'] = ['title' => 'Recent Laravel log (tail)', 'items' => $logItems, 'log_tail' => $tail];
} else {
    $logItems[] = fd_check('laravel.log', false, is_file($logPath) ? 'Not readable' : 'Not found yet', 'Errors will appear here after first request');
    $sections['9_log'] = ['title' => 'Laravel log', 'items' => $logItems];
}

// ---------------------------------------------------------------------------
// 10. TOOL URLS
// ---------------------------------------------------------------------------

$toolUrls = [
    'Setup tools' => $baseUrl . '/skmt-setup.php',
    'Admin tools' => $baseUrl . '/admin-utils.php',
    'This diagnostic' => $baseUrl . '/full-diagnose.php',
    'PHP ping' => $baseUrl . '/php-ping.php',
];

$toolItems = [];
foreach ($toolUrls as $name => $url) {
    $res = fd_http_get($url);
    $pass = $res['code'] === 200 && strlen($res['body']) > 50;
    $toolItems[] = fd_check($name, $pass, "HTTP {$res['code']} — $url", $pass ? '' : 'Upload file or fix .htaccess');
}

$sections['10_tools'] = ['title' => 'Utility URLs', 'items' => $toolItems];

// ---------------------------------------------------------------------------
// SUMMARY
// ---------------------------------------------------------------------------

$passCount = 0;
$failCount = 0;
$warnCount = 0;
foreach ($checks as $c) {
    if ($c['pass']) {
        $passCount++;
    } else {
        $failCount++;
    }
}

$overallOk = $failCount === 0 && empty($whiteScreenCauses);

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Full Diagnostic — Sarkin Mota Group</title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: system-ui, -apple-system, Segoe UI, sans-serif; background: #0f172a; color: #e2e8f0; line-height: 1.5; padding: 20px; }
        .wrap { max-width: 1100px; margin: 0 auto; }
        h1 { font-size: 1.6rem; margin-bottom: 8px; color: #f8fafc; }
        .sub { color: #94a3b8; margin-bottom: 24px; font-size: 0.95rem; }
        .banner { padding: 16px 20px; border-radius: 10px; margin-bottom: 24px; font-weight: 600; }
        .banner.ok { background: #064e3b; border: 1px solid #10b981; color: #a7f3d0; }
        .banner.bad { background: #450a0a; border: 1px solid #ef4444; color: #fecaca; }
        .stats { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 24px; }
        .stat { background: #1e293b; padding: 12px 18px; border-radius: 8px; min-width: 120px; }
        .stat b { display: block; font-size: 1.4rem; }
        .stat.pass b { color: #34d399; }
        .stat.fail b { color: #f87171; }
        section { background: #1e293b; border-radius: 10px; margin-bottom: 16px; overflow: hidden; border: 1px solid #334155; }
        section h2 { font-size: 1rem; padding: 14px 18px; background: #334155; color: #f1f5f9; }
        .meta { padding: 12px 18px; font-size: 0.85rem; color: #94a3b8; border-bottom: 1px solid #334155; }
        .meta div { margin: 4px 0; }
        table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
        th, td { padding: 10px 18px; text-align: left; border-bottom: 1px solid #334155; vertical-align: top; }
        th { color: #94a3b8; font-weight: 600; width: 28%; }
        td.pass { color: #86efac; }
        td.fail { color: #fca5a5; }
        td.fix { color: #fcd34d; font-size: 0.85rem; }
        pre { background: #0f172a; padding: 14px 18px; margin: 0; overflow: auto; font-size: 12px; max-height: 320px; color: #cbd5e1; white-space: pre-wrap; word-break: break-word; }
        .causes { padding: 14px 18px; }
        .causes li { margin: 6px 0 6px 20px; color: #fca5a5; }
        .delete { margin-top: 24px; padding: 14px; background: #422006; border: 1px solid #f59e0b; border-radius: 8px; color: #fde68a; }
    </style>
</head>
<body>
<div class="wrap">
    <h1>Full site diagnostic</h1>
    <p class="sub">Sarkin Mota Group · <?= htmlspecialchars($baseUrl) ?> · <?= date('Y-m-d H:i:s T') ?></p>

    <div class="banner <?= $overallOk ? 'ok' : 'bad' ?>">
        <?= $overallOk ? '✅ All critical checks passed — white screen is likely browser/JS cache or API login issue.' : '❌ Issues found — see failed checks and white-screen causes below.' ?>
    </div>

    <div class="stats">
        <div class="stat pass"><b><?= $passCount ?></b> passed</div>
        <div class="stat fail"><b><?= $failCount ?></b> failed</div>
        <div class="stat"><b><?= count($sections) ?></b> sections</div>
    </div>

    <?php if (! empty($whiteScreenCauses)): ?>
    <section>
        <h2>🎯 Likely white-screen causes</h2>
        <div class="causes">
            <ul>
                <?php foreach ($whiteScreenCauses as $cause): ?>
                    <li><?= htmlspecialchars($cause) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    </section>
    <?php endif; ?>

    <?php foreach ($sections as $sec): ?>
    <section>
        <h2><?= htmlspecialchars($sec['title']) ?></h2>
        <?php if (! empty($sec['meta'])): ?>
            <div class="meta">
                <?php foreach ($sec['meta'] as $k => $v): ?>
                    <div><strong><?= htmlspecialchars($k) ?>:</strong> <?= htmlspecialchars((string) $v) ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
        <table>
            <thead><tr><th>Check</th><th>Result</th><th>Fix</th></tr></thead>
            <tbody>
            <?php foreach ($sec['items'] as $item): ?>
                <tr>
                    <td><?= htmlspecialchars($item['label']) ?></td>
                    <td class="<?= $item['pass'] ? 'pass' : 'fail' ?>">
                        <?= fd_icon($item['pass']) ?> <?= htmlspecialchars($item['detail']) ?>
                    </td>
                    <td class="fix"><?= htmlspecialchars($item['fix'] ?? '') ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php if (! empty($sec['html_preview'])): ?>
            <pre><?= $sec['html_preview'] ?></pre>
        <?php endif; ?>
        <?php if (! empty($sec['log_tail'])): ?>
            <pre><?= htmlspecialchars($sec['log_tail']) ?></pre>
        <?php endif; ?>
    </section>
    <?php endforeach; ?>

    <div class="delete">
        ⚠️ <strong>Delete public/full-diagnose.php</strong> after fixing issues — this page exposes server paths and configuration.
    </div>
</div>
</body>
</html>
