<?php
/**
 * Admin Utilities for Shared Hosting
 *
 * Preferred URLs (with root .htaccess mapping public/ — no /public in the browser):
 *   https://yourdomain.com/admin-utils.php
 *   https://yourdomain.com/skmt-setup.php  (same tool; use if "admin" is blocked)
 *
 * If the host document root is the "public" folder only:
 *   https://yourdomain.com/admin-utils.php
 *
 * SECURITY: Change the password below and delete this file after setup!
 */

define('ADMIN_PASSWORD', 'SarkinMotaAdmin2024!'); // CHANGE THIS PASSWORD!

session_start();

// Check if logged in
if (!isset($_SESSION['admin_logged_in'])) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password'])) {
        if ($_POST['password'] === ADMIN_PASSWORD) {
            $_SESSION['admin_logged_in'] = true;
        } else {
            $error = 'Invalid password!';
        }
    }

    if (!isset($_SESSION['admin_logged_in'])) {
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <title>Admin Utilities - Login</title>
            <style>
                body { font-family: Arial, sans-serif; background: #f3f4f6; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
                .login-box { background: white; padding: 40px; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); width: 100%; max-width: 400px; }
                h2 { color: #2563eb; margin-top: 0; }
                input[type="password"] { width: 100%; padding: 12px; border: 1px solid #e5e7eb; border-radius: 6px; margin: 10px 0; box-sizing: border-box; }
                button { background: #2563eb; color: white; padding: 12px 24px; border: none; border-radius: 6px; cursor: pointer; width: 100%; font-size: 16px; }
                button:hover { background: #1d4ed8; }
                .error { color: #dc2626; margin-top: 10px; }
            </style>
        </head>
        <body>
            <div class="login-box">
                <h2>🔐 Admin Utilities Login</h2>
                <p>Enter password to access admin utilities</p>
                <form method="POST">
                    <input type="password" name="password" placeholder="Enter password" required autofocus>
                    <button type="submit">Login</button>
                </form>
                <?php if (isset($error)): ?>
                    <p class="error"><?= $error ?></p>
                <?php endif; ?>
            </div>
        </body>
        </html>
        <?php
        exit;
    }
}

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-utils.php');
    exit;
}

// Bootstrap Laravel only when a POST action needs it (not on every GET).
// Loading the dashboard while logged in used to boot Laravel on every request;
// a broken .env / vendor / PHP extension then caused a blank 500 with no login form.
$kernel = null;
$laravelBootstrapError = null;
$postAction = $_POST['action'] ?? null;
$actionsWithoutLaravel = ['composer_install', 'create_env', 'save_env'];
$shouldBootstrapLaravel = $_SERVER['REQUEST_METHOD'] === 'POST'
    && $postAction !== null
    && ! in_array($postAction, $actionsWithoutLaravel, true);

if ($shouldBootstrapLaravel && file_exists(__DIR__.'/../vendor/autoload.php')) {
    try {
        require_once __DIR__.'/../vendor/autoload.php';
        $app = require_once __DIR__.'/../bootstrap/app.php';
        $kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
    } catch (Throwable $e) {
        $laravelBootstrapError = $e->getMessage()."\n".$e->getFile().':'.$e->getLine();
    }
}

$output = '';
$success = false;

// Handle actions
if (isset($_POST['action'])) {
    ob_start();

    // Guard: actions that need Laravel but vendor is missing / kernel failed to boot
    $needsKernel = ! in_array($_POST['action'], ['composer_install', 'create_env', 'save_env'], true);
    if ($needsKernel && ! $kernel) {
        if (file_exists(__DIR__.'/../vendor/autoload.php') && ! empty($laravelBootstrapError)) {
            $output = "❌ Laravel failed to boot:\n\n".$laravelBootstrapError;
        } else {
            $output = "❌ vendor/autoload.php is missing!\n\nPlease click 'Run Composer Install' first, then try again.";
        }
    } else {
    try {
        switch ($_POST['action']) {
            case 'migrate':
                $kernel->call('migrate', ['--force' => true]);
                $success = true;
                break;

            case 'migrate_fresh':
                if (isset($_POST['confirm']) && $_POST['confirm'] === 'yes') {
                    $kernel->call('migrate:fresh', ['--force' => true, '--seed' => true]);
                    $success = true;
                } else {
                    $output = "⚠️ Please confirm this action. This will delete all data!";
                }
                break;

            case 'seed':
                $kernel->call('db:seed', ['--force' => true]);
                $success = true;
                break;

            case 'cache_clear':
                $kernel->call('cache:clear');
                $kernel->call('config:clear');
                $kernel->call('route:clear');
                $kernel->call('view:clear');
                $success = true;
                break;

            case 'config_cache':
                $kernel->call('config:cache');
                $kernel->call('route:cache');
                $kernel->call('view:cache');
                $success = true;
                break;

            case 'storage_link':
                $kernel->call('storage:link');
                $success = true;
                break;

            case 'optimize':
                $kernel->call('optimize');
                $success = true;
                break;

            case 'key_generate':
                $kernel->call('key:generate', ['--force' => true]);
                $success = true;
                break;

            case 'composer_install':
                $output .= "📦 Running composer install...\n\n";
                $vendorDir = __DIR__.'/../vendor';
                $composerJson = __DIR__.'/../composer.json';

                if (!file_exists($composerJson)) {
                    $output .= "❌ composer.json not found!\n";
                    break;
                }

                // Try multiple ways to run composer
                $composerPath = null;
                $paths = ['composer', '/usr/bin/composer', '/usr/local/bin/composer', '/opt/cpanel/composer/bin/composer'];
                foreach ($paths as $p) {
                    $test = shell_exec(escapeshellcmd($p) . ' --version 2>&1');
                    if ($test && strpos($test, 'Composer') !== false) {
                        $composerPath = $p;
                        $output .= "Found Composer: $p\n";
                        $output .= $test . "\n";
                        break;
                    }
                }

                if (!$composerPath) {
                    $output .= "❌ Composer not found on server.\n";
                    $output .= "You'll need to upload vendor/ manually or ask your host to install Composer.\n";
                    break;
                }

                $cmd = 'cd ' . escapeshellarg(__DIR__.'/..') . ' && ' . $composerPath . ' install --optimize-autoloader --no-dev 2>&1';
                $output .= "Running: $cmd\n\n";
                $result = shell_exec($cmd);
                $output .= $result;

                if (file_exists($vendorDir.'/autoload.php')) {
                    $output .= "\n✅ vendor/autoload.php created successfully!\n";
                    $success = true;
                } else {
                    $output .= "\n❌ vendor/autoload.php still missing. Shell may be restricted.\n";
                }
                break;

            case 'npm_build':
                $output .= "📦 Running npm install && npm run build...\n\n";

                $nodePaths = ['node', '/usr/bin/node', '/usr/local/bin/node'];
                $nodePath = null;
                foreach ($nodePaths as $p) {
                    $test = shell_exec(escapeshellcmd($p) . ' --version 2>&1');
                    if ($test && is_numeric(trim($test)[0] ?? '')) {
                        $nodePath = $p;
                        $output .= "Found Node: $p v$test\n";
                        break;
                    }
                }

                if (!$nodePath) {
                    $output .= "❌ Node.js not found on server. Frontend is pre-built in public/build/.\n";
                    $output .= "If you need to rebuild JS/CSS, do it locally and re-upload public/build/.\n";
                    break;
                }

                $npmPath = str_replace('node', 'npm', $nodePath);
                $cmd = 'cd ' . escapeshellarg(__DIR__.'/..') . ' && ' . $npmPath . ' install 2>&1 && ' . $npmPath . ' run build 2>&1';
                $output .= "Running: $cmd\n\n";
                $result = shell_exec($cmd);
                $output .= $result;

                if (file_exists(__DIR__.'/build/manifest.json')) {
                    $output .= "\n✅ Frontend built successfully!\n";
                    $success = true;
                }
                break;

            case 'setup_all':
                $output .= "⚡ STARTING COMPLETE SETUP...\n\n";

                // Step 0: Check vendor
                $vendorAutoload = __DIR__.'/../vendor/autoload.php';
                if (!file_exists($vendorAutoload)) {
                    $output .= "[0/5] vendor/ missing — trying composer install...\n";
                    $composerPath = null;
                    foreach (['composer', '/usr/bin/composer', '/usr/local/bin/composer'] as $p) {
                        $test = shell_exec(escapeshellcmd($p) . ' --version 2>&1');
                        if ($test && strpos($test, 'Composer') !== false) { $composerPath = $p; break; }
                    }
                    if ($composerPath) {
                        $cmd = 'cd ' . escapeshellarg(__DIR__.'/..') . ' && ' . $composerPath . ' install --optimize-autoloader --no-dev 2>&1';
                        $output .= shell_exec($cmd) . "\n";
                        if (file_exists($vendorAutoload)) {
                            $output .= "✅ Composer install successful!\n\n";
                        } else {
                            $output .= "❌ Composer failed. Click 'Run Composer Install' button above first.\n";
                            break;
                        }
                    } else {
                        $output .= "❌ Composer not found. Upload vendor/ manually.\n";
                        break;
                    }
                }

                // Step 1: Generate Key
                $output .= "[1/4] Generating app key...\n";
                try {
                    $kernel->call('key:generate', ['--force' => true]);
                    $output .= "✅ App key generated successfully.\n\n";
                } catch (Exception $e) {
                    $output .= "❌ Key generation failed: " . $e->getMessage() . "\n\n";
                }

                // Step 2: Run Migrations
                $output .= "[2/4] Running database migrations...\n";
                try {
                    $kernel->call('migrate', ['--force' => true]);
                    $output .= "✅ Migrations completed successfully.\n\n";
                } catch (Exception $e) {
                    $output .= "❌ Migration failed: " . $e->getMessage() . "\n\n";
                }

                // Step 3: Seed Database
                $output .= "[3/4] Seeding database...\n";
                try {
                    $kernel->call('db:seed', ['--force' => true]);
                    $output .= "✅ Database seeded successfully.\n\n";
                } catch (Exception $e) {
                    $output .= "❌ Seeding failed: " . $e->getMessage() . "\n\n";
                }

                // Step 4: Optimize
                $output .= "[4/4] Optimizing for production...\n";
                try {
                    $kernel->call('optimize');
                    $output .= "✅ Optimization completed.\n\n";
                } catch (Exception $e) {
                    $output .= "❌ Optimization failed: " . $e->getMessage() . "\n\n";
                }

                $output .= "═══════════════════════════════════\n";
                $output .= "🎉 SETUP COMPLETE!\n";
                $output .= "═══════════════════════════════════\n";
                $output .= "Default login: admin@sarkinmotagroup.com\n";
                $output .= "Default password: Admin@1234\n";
                $success = true;
                break;

            case 'create_env':
                $examplePath = __DIR__.'/../.env.example';
                $envPath = __DIR__.'/../.env';
                if (file_exists($examplePath)) {
                    if (copy($examplePath, $envPath)) {
                        $output = "✅ .env file created from .env.example!\nPlease configure your database settings above.";
                        $success = true;
                    } else {
                        $output = "❌ Failed to copy .env.example to .env. Check folder permissions.";
                    }
                } else {
                    $output = "❌ .env.example not found. Please upload it first.";
                }
                break;
        }

    } // end try

        $output .= ob_get_clean();

    } catch (Exception $e) {
        $output = "❌ Error: " . $e->getMessage();
        ob_end_clean();
    }
    } // end else (kernel check)
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Utilities - Sarkin Mota Group</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px; }
        .container { max-width: 1200px; margin: 0 auto; }
        .header { background: white; padding: 30px; border-radius: 10px; margin-bottom: 20px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .header h1 { color: #2563eb; margin-bottom: 10px; }
        .header p { color: #6b7280; }
        .logout-btn { float: right; background: #dc2626; color: white; padding: 8px 16px; border: none; border-radius: 6px; cursor: pointer; text-decoration: none; display: inline-block; }
        .logout-btn:hover { background: #b91c1c; }
        .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 20px; }
        .card { background: white; padding: 25px; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .card h3 { color: #1f2937; margin-bottom: 10px; font-size: 18px; }
        .card p { color: #6b7280; margin-bottom: 15px; font-size: 14px; }
        .btn { background: #2563eb; color: white; padding: 12px 24px; border: none; border-radius: 6px; cursor: pointer; width: 100%; font-size: 14px; font-weight: 500; transition: all 0.3s; }
        .btn:hover { background: #1d4ed8; transform: translateY(-2px); }
        .btn-danger { background: #dc2626; }
        .btn-danger:hover { background: #b91c1c; }
        .btn-warning { background: #f59e0b; }
        .btn-warning:hover { background: #d97706; }
        .btn-success { background: #10b981; }
        .btn-success:hover { background: #059669; }
        .output-box { background: #1f2937; color: #f3f4f6; padding: 20px; border-radius: 8px; margin-top: 20px; font-family: 'Courier New', monospace; font-size: 13px; line-height: 1.6; white-space: pre-wrap; word-wrap: break-word; max-height: 400px; overflow-y: auto; }
        .success { background: #d1fae5; color: #065f46; padding: 15px; border-radius: 8px; margin-top: 20px; border-left: 4px solid #10b981; }
        .warning { background: #fef3c7; color: #92400e; padding: 15px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #f59e0b; }
        .icon { font-size: 24px; margin-bottom: 10px; }
        form { display: inline; width: 100%; }
        .confirm-checkbox { margin: 10px 0; }
        .confirm-checkbox label { color: #dc2626; font-weight: 500; cursor: pointer; }
        .info-section { background: #eff6ff; border: 1px solid #bfdbfe; padding: 15px; border-radius: 8px; margin-bottom: 20px; }
        .info-section h4 { color: #1e40af; margin-bottom: 8px; }
        .info-section ul { margin-left: 20px; color: #1e40af; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <a href="?logout" class="logout-btn">Logout</a>
            <h1>🛠️ Admin Utilities</h1>
            <p>Sarkin Mota Group - Shared Hosting Management Tools</p>
        </div>

        <div class="warning">
            ⚠️ <strong>Security Warning:</strong> Delete this file after completing your setup! Anyone with the password can access these utilities.
        </div>

        <?php if (!empty($laravelBootstrapError)): ?>
            <div class="warning" style="background: #fee2e2; border-color: #fecaca; color: #991b1b;">
                <strong>Laravel could not boot on last action.</strong> Fix .env / database / vendor, or check <code>storage/logs/laravel.log</code> on the server.
                <pre style="margin-top:10px;white-space:pre-wrap;font-size:12px;"><?= htmlspecialchars($laravelBootstrapError) ?></pre>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="success">
                ✅ <strong>Success!</strong> Command executed successfully.
            </div>
        <?php endif; ?>

        <div class="info-section">
            <h4>📋 Before Using These Tools:</h4>
            <ul>
                <li>Make sure your .env file is configured correctly</li>
                <li>Database credentials must be set</li>
                <li>File permissions should be 755 for folders, 644 for files</li>
                <li>Back up your database before running destructive commands</li>
            </ul>
        </div>

        <!-- ============================================ -->
        <!-- ONE-CLICK SETUP SECTION -->
        <!-- ============================================ -->
        <div class="card" style="margin-bottom: 20px; border: 2px solid #5D4037;">
            <h3 style="color: #5D4037;">🚀 ONE-CLICK SETUP — Sarkin Mota Group</h3>
            <p style="margin-bottom: 15px;">Run all setup steps in order: Key Generate → Migrate → Seed → Optimize</p>

            <form method="POST">
                <input type="hidden" name="action" value="setup_all">
                <button type="submit" class="btn" style="background: #5D4037; font-size: 16px; padding: 16px;">
                    ⚡ RUN COMPLETE SETUP
                </button>
            </form>
            <p style="font-size: 12px; color: #6b7280; margin-top: 10px;">
                This will: generate app key → run migrations → seed database → optimize for production
            </p>
        </div>

        <!-- COMPOSER INSTALL SECTION -->
        <div class="card" style="margin-bottom: 20px; border: 2px solid #f59e0b;">
            <h3 style="color: #92400e;">📦 Install Dependencies (Composer)</h3>
            <p>Run composer install to generate the vendor/ folder. Required before setup!</p>
            <form method="POST">
                <input type="hidden" name="action" value="composer_install">
                <button type="submit" class="btn" style="background: #f59e0b; color: #000; font-size: 15px;">
                    📦 Run Composer Install
                </button>
            </form>
            <p style="font-size: 11px; color: #6b7280; margin-top: 8px;">
                This runs: composer install --optimize-autoloader --no-dev
            </p>
        </div>

        <!-- DATABASE CONFIG SECTION -->
        <div class="card" style="margin-bottom: 20px;">
            <h3>⚙️ Configure .env File</h3>
            <p style="margin-bottom: 15px;">Set your database credentials and app URL before running setup.</p>

            <?php
            $envPath = __DIR__.'/../.env';
            $envExists = file_exists($envPath);
            $currentEnv = $envExists ? file_get_contents($envPath) : '';

            // Extract current values
            $currentDbHost = ''; $currentDbName = ''; $currentDbUser = ''; $currentDbPass = ''; $currentAppUrl = '';
            if ($envExists) {
                preg_match('/^DB_HOST=(.*)$/m', $currentEnv, $m); $currentDbHost = $m[1] ?? '';
                preg_match('/^DB_DATABASE=(.*)$/m', $currentEnv, $m); $currentDbName = $m[1] ?? '';
                preg_match('/^DB_USERNAME=(.*)$/m', $currentEnv, $m); $currentDbUser = $m[1] ?? '';
                preg_match('/^DB_PASSWORD=(.*)$/m', $currentEnv, $m); $currentDbPass = $m[1] ?? '';
                preg_match('/^APP_URL=(.*)$/m', $currentEnv, $m); $currentAppUrl = $m[1] ?? '';
            }

            if (isset($_POST['action']) && $_POST['action'] === 'save_env') {
                $envContent = $currentEnv;
                $replacements = [
                    'APP_URL' => $_POST['app_url'] ?? $currentAppUrl,
                    'DB_HOST' => $_POST['db_host'] ?? $currentDbHost,
                    'DB_DATABASE' => $_POST['db_name'] ?? $currentDbName,
                    'DB_USERNAME' => $_POST['db_user'] ?? $currentDbUser,
                    'DB_PASSWORD' => $_POST['db_pass'] ?? $currentDbPass,
                ];

                foreach ($replacements as $key => $value) {
                    $envContent = preg_replace('/^'.$key.'=.*$/m', $key.'='.$value, $envContent);
                }

                if (file_put_contents($envPath, $envContent)) {
                    echo '<div class="success">✅ .env file updated successfully!</div>';
                } else {
                    echo '<div style="background: #fee2e2; color: #991b1b; padding: 15px; border-radius: 8px; margin-top: 10px;">❌ Failed to write .env file. Check permissions.</div>';
                }
            }
            ?>

            <form method="POST">
                <input type="hidden" name="action" value="save_env">
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                    <div>
                        <label style="display: block; font-size: 13px; font-weight: 600; color: #374151; margin-bottom: 4px;">App URL</label>
                        <input type="text" name="app_url" value="<?= htmlspecialchars($currentAppUrl) ?>" placeholder="https://yourdomain.com" style="width: 100%; padding: 10px; border: 1px solid #d1d5db; border-radius: 6px;">
                    </div>
                    <div>
                        <label style="display: block; font-size: 13px; font-weight: 600; color: #374151; margin-bottom: 4px;">DB Host</label>
                        <input type="text" name="db_host" value="<?= htmlspecialchars($currentDbHost) ?>" placeholder="localhost" style="width: 100%; padding: 10px; border: 1px solid #d1d5db; border-radius: 6px;">
                    </div>
                    <div>
                        <label style="display: block; font-size: 13px; font-weight: 600; color: #374151; margin-bottom: 4px;">DB Name</label>
                        <input type="text" name="db_name" value="<?= htmlspecialchars($currentDbName) ?>" placeholder="my_database" style="width: 100%; padding: 10px; border: 1px solid #d1d5db; border-radius: 6px;">
                    </div>
                    <div>
                        <label style="display: block; font-size: 13px; font-weight: 600; color: #374151; margin-bottom: 4px;">DB Username</label>
                        <input type="text" name="db_user" value="<?= htmlspecialchars($currentDbUser) ?>" placeholder="root" style="width: 100%; padding: 10px; border: 1px solid #d1d5db; border-radius: 6px;">
                    </div>
                    <div style="grid-column: span 2;">
                        <label style="display: block; font-size: 13px; font-weight: 600; color: #374151; margin-bottom: 4px;">DB Password</label>
                        <input type="password" name="db_pass" value="<?= htmlspecialchars($currentDbPass) ?>" placeholder="password" style="width: 100%; padding: 10px; border: 1px solid #d1d5db; border-radius: 6px;">
                    </div>
                </div>
                <button type="submit" class="btn btn-success" style="margin-top: 12px;">💾 Save .env Configuration</button>
            </form>

            <?php if (!$envExists): ?>
                <div class="warning" style="margin-top: 15px;">
                    ⚠️ No .env file found! A new one will be created from .env.example if available.
                </div>
                <form method="POST" style="margin-top: 10px;">
                    <input type="hidden" name="action" value="create_env">
                    <button type="submit" class="btn">📄 Create .env from .env.example</button>
                </form>
            <?php endif; ?>
        </div>

        <!-- FULL DIAGNOSTICS SECTION -->
        <div class="card" style="margin-bottom: 20px;">
            <h3>🔍 Full System Diagnostics</h3>
            <p style="margin-bottom: 20px;">Complete analysis of why the website might show a white screen</p>

            <?php
            $diagnostics = [];
            $criticalErrors = [];
            $warnings = [];

            // 1. Check PHP Version
            $phpVersion = phpversion();
            $diagnostics['PHP Version'] = $phpVersion;
            if (version_compare($phpVersion, '8.1', '<')) {
                $criticalErrors[] = "PHP version $phpVersion is too old. Requires PHP 8.1+";
            }

            // 2. Check .env file
            $envPath = __DIR__.'/../.env';
            if (!file_exists($envPath)) {
                $criticalErrors[] = ".env file is MISSING! This is likely why the site shows white screen.";
                $diagnostics['.env File'] = '❌ MISSING';
            } else {
                $diagnostics['.env File'] = '✅ EXISTS';
                $envContent = file_get_contents($envPath);

                // Check critical env variables
                if (strpos($envContent, 'APP_KEY=') === false || preg_match('/APP_KEY=\s*$/', $envContent)) {
                    $criticalErrors[] = "APP_KEY is not set in .env file!";
                }

                // Extract DB config
                preg_match('/DB_HOST=(.*)/', $envContent, $dbHost);
                preg_match('/DB_DATABASE=(.*)/', $envContent, $dbName);
                preg_match('/DB_USERNAME=(.*)/', $envContent, $dbUser);

                $diagnostics['DB Host'] = isset($dbHost[1]) ? trim($dbHost[1]) : 'NOT SET';
                $diagnostics['DB Name'] = isset($dbName[1]) ? trim($dbName[1]) : 'NOT SET';
                $diagnostics['DB User'] = isset($dbUser[1]) ? trim($dbUser[1]) : 'NOT SET';
            }

            // 3. Test Database Connection
            try {
                if (file_exists($envPath)) {
                    $pdo = new PDO(
                        "mysql:host=" . (isset($dbHost[1]) ? trim($dbHost[1]) : '127.0.0.1') . ";dbname=" . (isset($dbName[1]) ? trim($dbName[1]) : ''),
                        isset($dbUser[1]) ? trim($dbUser[1]) : '',
                        ''
                    );
                    $diagnostics['Database Connection'] = '✅ CONNECTED';
                } else {
                    $diagnostics['Database Connection'] = '❌ Cannot test (no .env)';
                }
            } catch (PDOException $e) {
                $criticalErrors[] = "Database connection FAILED: " . $e->getMessage();
                $diagnostics['Database Connection'] = '❌ FAILED';
            }

            // 4. Check critical directories
            $dirs = [
                'storage/framework/cache' => __DIR__.'/../storage/framework/cache',
                'storage/framework/sessions' => __DIR__.'/../storage/framework/sessions',
                'storage/framework/views' => __DIR__.'/../storage/framework/views',
                'storage/logs' => __DIR__.'/../storage/logs',
                'bootstrap/cache' => __DIR__.'/../bootstrap/cache',
            ];

            foreach ($dirs as $name => $path) {
                if (!is_dir($path)) {
                    $warnings[] = "Directory missing: $name";
                    $diagnostics[$name] = '❌ MISSING';
                } elseif (!is_writable($path)) {
                    $criticalErrors[] = "Directory not writable: $name (permissions issue!)";
                    $diagnostics[$name] = '⚠️ NOT WRITABLE';
                } else {
                    $diagnostics[$name] = '✅ OK';
                }
            }

            // 5. Check vendor directory
            if (!is_dir(__DIR__.'/../vendor')) {
                $criticalErrors[] = "vendor/ directory is MISSING! Run 'composer install'";
                $diagnostics['Composer Vendor'] = '❌ MISSING';
            } else {
                $diagnostics['Composer Vendor'] = '✅ EXISTS';
            }

            // 6. Check public/build (frontend assets)
            if (!file_exists(__DIR__.'/build/manifest.json')) {
                $warnings[] = "Frontend assets not built. Run 'npm run build'";
                $diagnostics['Frontend Build'] = '⚠️ NOT BUILT';
            } else {
                $diagnostics['Frontend Build'] = '✅ BUILT';
            }

            // 7. Check Laravel log for recent errors
            $logPath = __DIR__.'/../storage/logs/laravel.log';
            if (file_exists($logPath)) {
                $logContent = file_get_contents($logPath);
                $logLines = explode("\n", $logContent);
                $recentErrors = array_slice(array_filter($logLines, function($line) {
                    return strpos($line, 'ERROR') !== false ||
                           strpos($line, 'Exception') !== false ||
                           strpos($line, 'SQLSTATE') !== false;
                }), -5);

                if (!empty($recentErrors)) {
                    $diagnostics['Recent Log Errors'] = count($recentErrors) . ' errors found';
                } else {
                    $diagnostics['Recent Log Errors'] = '✅ No recent errors';
                }
            }

            // 8. Check PHP extensions
            $requiredExtensions = ['pdo', 'pdo_mysql', 'mbstring', 'openssl', 'tokenizer', 'xml', 'ctype', 'json'];
            $missingExtensions = [];
            foreach ($requiredExtensions as $ext) {
                if (!extension_loaded($ext)) {
                    $missingExtensions[] = $ext;
                }
            }
            if (!empty($missingExtensions)) {
                $criticalErrors[] = "Missing PHP extensions: " . implode(', ', $missingExtensions);
                $diagnostics['PHP Extensions'] = '❌ MISSING: ' . implode(', ', $missingExtensions);
            } else {
                $diagnostics['PHP Extensions'] = '✅ ALL LOADED';
            }

            // 9. Check file permissions on index.php
            if (!is_readable(__DIR__.'/index.php')) {
                $criticalErrors[] = "public/index.php is not readable!";
            }

            // 10. Memory limit
            $memoryLimit = ini_get('memory_limit');
            $diagnostics['PHP Memory Limit'] = $memoryLimit;
            if (intval($memoryLimit) < 128) {
                $warnings[] = "PHP memory_limit is low: $memoryLimit (recommend 256M+)";
            }

            ?>

            <div style="background: #1f2937; color: #f3f4f6; padding: 20px; border-radius: 8px; font-family: monospace; font-size: 13px; margin-bottom: 20px;">
                <strong style="color: #60a5fa; font-size: 16px;">📊 DIAGNOSTIC RESULTS:</strong><br><br>
                <?php foreach ($diagnostics as $key => $value): ?>
                    <div style="margin: 5px 0;">
                        <span style="color: #9ca3af;"><?= $key ?>:</span>
                        <span style="color: <?= strpos($value, '❌') !== false ? '#f87171' : (strpos($value, '⚠️') !== false ? '#fbbf24' : '#34d399') ?>;">
                            <?= htmlspecialchars($value) ?>
                        </span>
                    </div>
                <?php endforeach; ?>
            </div>

            <?php if (!empty($criticalErrors)): ?>
                <div style="background: #fee2e2; border-left: 4px solid #dc2626; padding: 15px; border-radius: 8px; margin-bottom: 15px;">
                    <strong style="color: #991b1b;">🚨 CRITICAL ERRORS (These cause white screen):</strong><br><br>
                    <?php foreach ($criticalErrors as $error): ?>
                        <div style="color: #991b1b; margin: 5px 0;">• <?= htmlspecialchars($error) ?></div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <?php if (!empty($warnings)): ?>
                <div style="background: #fef3c7; border-left: 4px solid #f59e0b; padding: 15px; border-radius: 8px; margin-bottom: 15px;">
                    <strong style="color: #92400e;">⚠️ WARNINGS:</strong><br><br>
                    <?php foreach ($warnings as $warning): ?>
                        <div style="color: #92400e; margin: 5px 0;">• <?= htmlspecialchars($warning) ?></div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <?php if (empty($criticalErrors) && empty($warnings)): ?>
                <div style="background: #d1fae5; border-left: 4px solid #10b981; padding: 15px; border-radius: 8px;">
                    <strong style="color: #065f46;">✅ ALL CHECKS PASSED!</strong><br>
                    <span style="color: #065f46;">System appears healthy. If still seeing white screen, check browser console for JavaScript errors.</span>
                </div>
            <?php endif; ?>

            <?php if (isset($recentErrors) && !empty($recentErrors)): ?>
                <div style="margin-top: 15px;">
                    <strong style="color: #1f2937;">📋 Recent Log Errors (Last 5):</strong>
                    <div style="background: #1f2937; color: #f87171; padding: 15px; border-radius: 8px; margin-top: 10px; font-family: monospace; font-size: 11px; max-height: 200px; overflow-y: auto;">
                        <?php foreach ($recentErrors as $error): ?>
                            <?= htmlspecialchars($error) ?><br>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>

            <div style="margin-top: 20px; padding: 15px; background: #eff6ff; border-radius: 8px;">
                <strong style="color: #1e40af;">💡 Quick Fixes for White Screen:</strong>
                <ol style="margin: 10px 0 0 20px; color: #1e40af;">
                    <li>If .env is missing: Copy .env.example to .env and configure it</li>
                    <li>If database fails: Check MySQL is running and credentials are correct</li>
                    <li>If permissions issue: Run chmod -R 775 storage bootstrap/cache</li>
                    <li>If vendor missing: Run composer install</li>
                    <li>Clear all caches using the button below</li>
                    <li>Check browser console (F12) for JavaScript errors</li>
                </ol>
            </div>
        </div>

        <div class="grid">
            <!-- Database Migrations -->
            <div class="card">
                <div class="icon">🗄️</div>
                <h3>Run Migrations</h3>
                <p>Execute database migrations to create or update tables.</p>
                <form method="POST">
                    <input type="hidden" name="action" value="migrate">
                    <button type="submit" class="btn">Run Migrations</button>
                </form>
            </div>

            <!-- Seed Database -->
            <div class="card">
                <div class="icon">🌱</div>
                <h3>Seed Database</h3>
                <p>Insert sample data including admin user and demo companies.</p>
                <form method="POST">
                    <input type="hidden" name="action" value="seed">
                    <button type="submit" class="btn btn-success">Seed Database</button>
                </form>
            </div>

            <!-- Clear Cache -->
            <div class="card">
                <div class="icon">🧹</div>
                <h3>Clear All Cache</h3>
                <p>Clear application, config, route, and view cache.</p>
                <form method="POST">
                    <input type="hidden" name="action" value="cache_clear">
                    <button type="submit" class="btn">Clear Cache</button>
                </form>
            </div>

            <!-- Optimize -->
            <div class="card">
                <div class="icon">⚡</div>
                <h3>Optimize Application</h3>
                <p>Cache config and routes for better performance.</p>
                <form method="POST">
                    <input type="hidden" name="action" value="config_cache">
                    <button type="submit" class="btn btn-success">Optimize</button>
                </form>
            </div>

            <!-- Storage Link -->
            <div class="card">
                <div class="icon">🔗</div>
                <h3>Create Storage Link</h3>
                <p>Link public storage for file uploads and avatars.</p>
                <form method="POST">
                    <input type="hidden" name="action" value="storage_link">
                    <button type="submit" class="btn">Create Link</button>
                </form>
            </div>

            <!-- Generate Key -->
            <div class="card">
                <div class="icon">🔑</div>
                <h3>Generate App Key</h3>
                <p>Generate new application encryption key.</p>
                <form method="POST">
                    <input type="hidden" name="action" value="key_generate">
                    <button type="submit" class="btn btn-warning">Generate Key</button>
                </form>
            </div>

            <!-- Fresh Migration (Dangerous) -->
            <div class="card">
                <div class="icon">⚠️</div>
                <h3>Fresh Migration + Seed</h3>
                <p><strong>DANGER:</strong> Drops all tables and recreates them with sample data.</p>
                <form method="POST" onsubmit="return confirm('This will DELETE ALL DATA! Are you sure?');">
                    <input type="hidden" name="action" value="migrate_fresh">
                    <div class="confirm-checkbox">
                        <input type="checkbox" name="confirm" value="yes" id="confirm" required>
                        <label for="confirm">I understand this deletes all data</label>
                    </div>
                    <button type="submit" class="btn btn-danger">Reset Database</button>
                </form>
            </div>

            <!-- Optimize Full -->
            <div class="card">
                <div class="icon">🚀</div>
                <h3>Full Optimization</h3>
                <p>Run all optimization commands for production.</p>
                <form method="POST">
                    <input type="hidden" name="action" value="optimize">
                    <button type="submit" class="btn btn-success">Full Optimize</button>
                </form>
            </div>
        </div>

        <?php if ($output): ?>
            <div class="card">
                <h3>Command Output:</h3>
                <div class="output-box"><?= htmlspecialchars($output) ?></div>
            </div>
        <?php endif; ?>

        <div class="info-section">
            <h4>🔒 Post-Setup Security Steps:</h4>
            <ul>
                <li><strong>DELETE this admin-utils.php file</strong> after setup</li>
                <li>Set APP_DEBUG=false in .env for production</li>
                <li>Change all default passwords</li>
                <li>Enable HTTPS/SSL on your domain</li>
                <li>Set proper file permissions (755/644)</li>
            </ul>
        </div>
    </div>
</body>
</html>
