<?php
/**
 * Neptuno ERP - Server Diagnostic Tool v0.0.7
 * Upload this to your server root and visit it in the browser.
 * It will identify the exact cause of the 500 error.
 */

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

echo '<!DOCTYPE html><html><head><meta charset="utf-8"><title>Neptuno Diagnostics</title></head>';
echo '<body style="background:#0f172a;color:#e2e8f0;font-family:monospace;padding:40px;">';
echo '<h1 style="color:#38bdf8;">🔍 Neptuno Server Diagnostics</h1>';

function check($label, $result, $detail = '') {
    $icon = $result ? '✅' : '❌';
    $color = $result ? '#10b981' : '#ef4444';
    echo "<p style='color:{$color};margin:6px 0;'>{$icon} <strong>{$label}</strong>";
    if ($detail) echo " — <span style='color:#94a3b8;'>{$detail}</span>";
    echo "</p>";
    return $result;
}

// 1. PHP Version
$phpVer = phpversion();
check("PHP Version", version_compare($phpVer, '8.0', '>='), $phpVer);

// 2. Required Extensions
$exts = ['openssl', 'pdo', 'mbstring', 'tokenizer', 'xml', 'ctype', 'json', 'bcmath', 'fileinfo', 'pdo_mysql'];
echo '<h3 style="color:#f59e0b;margin-top:20px;">PHP Extensions</h3>';
foreach ($exts as $ext) {
    check("ext-{$ext}", extension_loaded($ext), extension_loaded($ext) ? 'loaded' : 'MISSING');
}

// 3. Directory Structure
echo '<h3 style="color:#f59e0b;margin-top:20px;">Directory Structure</h3>';
$root = __DIR__;
$paths = [
    'public/index.php',
    'public/.htaccess',
    'public/build',
    'vendor/autoload.php',
    'bootstrap/app.php',
    'storage',
    'storage/app',
    'storage/framework',
    'storage/framework/cache',
    'storage/framework/sessions',
    'storage/framework/views',
    'storage/logs',
    'bootstrap/cache',
    '.env',
    'artisan',
    'config/app.php',
    'routes/web.php',
];

foreach ($paths as $p) {
    $full = $root . '/' . $p;
    $exists = file_exists($full) || is_dir($full);
    $info = '';
    if ($exists && is_dir($full)) {
        $info = 'dir, perms: ' . substr(sprintf('%o', fileperms($full)), -4);
        $info .= ', writable: ' . (is_writable($full) ? 'yes' : 'NO');
    } elseif ($exists) {
        $info = 'file, ' . filesize($full) . ' bytes';
    }
    check($p, $exists, $exists ? $info : 'NOT FOUND');
}

// 4. .env Contents (safe keys only)
echo '<h3 style="color:#f59e0b;margin-top:20px;">.env Configuration</h3>';
$envFile = $root . '/.env';
if (file_exists($envFile)) {
    $env = file_get_contents($envFile);
    $hasKey = preg_match('/APP_KEY=base64:.+/', $env);
    check("APP_KEY set", $hasKey, $hasKey ? 'Present' : 'EMPTY — Laravel will 500 without this');
    
    preg_match('/APP_ENV=(.*)/', $env, $m);
    check("APP_ENV", true, trim($m[1] ?? 'not set'));
    
    preg_match('/APP_DEBUG=(.*)/', $env, $m);
    check("APP_DEBUG", true, trim($m[1] ?? 'not set'));
    
    preg_match('/DB_CONNECTION=(.*)/', $env, $m);
    check("DB_CONNECTION", true, trim($m[1] ?? 'not set'));
} else {
    check(".env file", false, 'File not found! Laravel cannot boot without .env');
}

// 5. Try to actually boot Laravel and catch the error
echo '<h3 style="color:#f59e0b;margin-top:20px;">Laravel Boot Test</h3>';
try {
    // Check autoload
    $autoload = $root . '/vendor/autoload.php';
    if (!file_exists($autoload)) {
        check("Vendor autoload", false, "vendor/autoload.php not found — composer dependencies missing");
    } else {
        check("Vendor autoload", true, "Found");
        require $autoload;
        check("Autoload loaded", true, "Classes registered");
        
        // 3. Clear Laravel Caches (if bootstrap exists)
        echo "<p>🧹 <b>Laravel Cache:</b> Cleaning bootstrap/cache directory...<br>";
        $cacheDir = __DIR__ . '/bootstrap/cache';
        if (is_dir($cacheDir)) {
            $files = scandir($cacheDir);
            foreach ($files as $file) {
                if ($file !== '.' && $file !== '..' && $file !== '.gitignore') {
                    @unlink($cacheDir . '/' . $file);
                    echo "&nbsp;&nbsp;- Deleted $file<br>";
                }
            }
            echo "✅ Laravel cache directory cleared.</p>";
        } else {
            echo "⚠️ bootstrap/cache directory not found.</p>";
        }

        // 4. File Extraction Check
        echo "<h2>📂 File Extraction Verification</h2>";
        $authFile = __DIR__ . '/app/Http/Controllers/Auth/EmailVerificationPromptController.php';
        if (file_exists($authFile)) {
            echo "<p>✅ <b>Auth Controller File:</b> Exists on disk.</p>";
            if (is_readable($authFile)) {
                echo "<p>✅ <b>Auth Controller Permissions:</b> Readable.</p>";
            } else {
                 echo "<p>❌ <b>Auth Controller Permissions:</b> Unreadable!</p>";
            }
        } else {
            echo "<p>❌ <b>CRITICAL ERROR:</b> The Auth Controller file does NOT exist on the server!<br>";
            echo "This means the ZIP extractor failed to write new files to your <code>app/</code> folder. Please manually delete the <code>app/</code> and <code>vendor/</code> folders via Hostnet control panel, then run the installer again.</p>";
        }

        echo "<h3>✅ Diagnostics & Cache Clearing Complete.</h3>";
        
        // Try bootstrap
        $bootstrap = $root . '/bootstrap/app.php';
        if (file_exists($bootstrap)) {
            $app = require_once $bootstrap;
            check("Bootstrap", true, "Application created");
            
            // Try to boot
            $kernel = $app->make(\Illuminate\Contracts\Http\Kernel::class);
            check("HTTP Kernel", true, "Kernel resolved");
        } else {
            check("Bootstrap", false, "bootstrap/app.php not found");
        }
    }
} catch (\Throwable $e) {
    check("Laravel Boot FAILED", false, get_class($e) . ': ' . $e->getMessage());
    echo '<pre style="background:#1e293b;padding:16px;border-radius:8px;color:#fbbf24;margin-top:10px;overflow-x:auto;font-size:12px;">';
    echo htmlspecialchars($e->getTraceAsString());
    echo '</pre>';
}

// 6. Server Info
echo '<h3 style="color:#f59e0b;margin-top:20px;">Server Environment</h3>';
check("Server Software", true, $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown');
check("Document Root", true, $_SERVER['DOCUMENT_ROOT'] ?? 'Unknown');
check("Script Path", true, __FILE__);
check("Current Directory", true, __DIR__);
check("Disk Free Space", true, round(disk_free_space($root) / 1024 / 1024, 1) . ' MB');

echo '<hr style="border-color:#334155;margin:30px 0;">';
echo '<p style="color:#94a3b8;">Diagnostic complete. Share the output above for troubleshooting.</p>';
echo '</body></html>';
?>
