<?php
/**
 * Phynix360 - 1-File Standalone Commercial Bootstrap Web Installer
 * 
 * Upload this single file to your webroot (public_html/ or /var/www/html) and open it in your browser.
 * It validates your hosting environment, verifies your license serial key, streams the full release package
 * directly from the PhynixOne Authority, extracts all application files, and launches the database setup wizard.
 * 
 * Version: 1.2.5
 * License: Proprietary Commercial Software
 * https://phynix.one
 */

declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '0');

@set_time_limit(300);
@ini_set('memory_limit', '256M');

define('PHYNIX_BOOTSTRAP_VERSION', '1.2.5');
define('PHYNIX_DEFAULT_AUTHORITY', 'https://phynix.one');

$targetDir = __DIR__;
$tempZipPath = $targetDir . '/phynix_release_' . substr(md5(__DIR__ . PHYNIX_BOOTSTRAP_VERSION), 0, 10) . '.zip';

// Helper: JSON Response
function sendJson(array $data, int $code = 200): void {
    http_response_code($code);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    exit;
}

// 1. AJAX Backend Handlers
$action = (string) ($_POST['action'] ?? ($_GET['action'] ?? ''));

if ($action === 'preflight') {
    $checks = [];
    $allPassed = true;

    // PHP Version
    $phpOk = version_compare(PHP_VERSION, '8.2.0', '>=');
    $checks[] = [
        'name' => 'PHP Modern Runtime (8.2+)',
        'status' => $phpOk,
        'info' => 'Current: PHP ' . PHP_VERSION,
        'required' => true,
    ];
    if (!$phpOk) $allPassed = false;

    // Required Standard Web & Security Extensions
    $extensionList = [
        'curl' => 'Secure Connection Engine (cURL)',
        'zip' => 'Automatic Package Extractor (ZipArchive)',
        'openssl' => 'SSL & Encryption Security (OpenSSL)',
        'pdo' => 'Database Connector (PDO)',
        'pdo_mysql' => 'MySQL / MariaDB Database Driver',
        'json' => 'Data Exchange Parser (JSON)',
        'mbstring' => 'International Character Encoding (mbstring)',
    ];

    foreach ($extensionList as $ext => $label) {
        $loaded = extension_loaded($ext);
        $checks[] = [
            'name' => $label,
            'status' => $loaded,
            'info' => $loaded ? 'Installed & Active' : 'Missing PHP module: ' . $ext,
            'required' => true,
        ];
        if (!$loaded) $allPassed = false;
    }

    // License Security Module (Sodium with OpenSSL fallback)
    $sodiumLoaded = extension_loaded('sodium');
    $opensslLoaded = extension_loaded('openssl');
    $securityActive = $sodiumLoaded || $opensslLoaded;
    $checks[] = [
        'name' => 'License Security Verification',
        'status' => $securityActive,
        'info' => $sodiumLoaded ? 'Installed & Active' : ($opensslLoaded ? 'Verified & Active (OpenSSL Mode)' : 'Missing security module'),
        'required' => true,
    ];
    if (!$securityActive) $allPassed = false;

    // Directory Writable Check
    $writable = is_writable($targetDir);
    $checks[] = [
        'name' => 'Target Webroot Directory Writable',
        'status' => $writable,
        'info' => $writable ? 'Writable: ' . $targetDir : 'Permission denied. Please chmod 755 or 777: ' . $targetDir,
        'required' => true,
    ];
    if (!$writable) $allPassed = false;

    sendJson([
        'success' => $allPassed,
        'checks' => $checks,
        'server' => [
            'os' => PHP_OS,
            'sapi' => PHP_SAPI,
            'software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
            'php' => PHP_VERSION,
            'webroot' => $targetDir,
        ],
    ]);
}

if ($action === 'verify_key') {
    $serial = trim((string) ($_POST['serial'] ?? ''));
    $authorityUrl = rtrim(trim((string) ($_POST['authority_url'] ?? PHYNIX_DEFAULT_AUTHORITY)), '/');

    if ($serial === '' || !preg_match('/^PX1-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/i', $serial)) {
        sendJson(['success' => false, 'message' => 'Invalid Serial Format. Serial keys must follow PX1-XXXX-XXXX-XXXX-XXXX format.'], 422);
    }

    // Determine current domain
    $domain = (string) ($_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'localhost');
    $domain = preg_replace('/:\d+$/', '', strtolower($domain));

    // Remote Verification Query
    $endpoint = $authorityUrl . '/api/v1/license/verify';
    $postPayload = json_encode([
        'serial' => $serial,
        'domain' => $domain,
        'version' => PHYNIX_BOOTSTRAP_VERSION,
        'timestamp' => time(),
    ]);

    $ch = curl_init($endpoint);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postPayload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'User-Agent: PhynixOne-Bootstrapper/' . PHYNIX_BOOTSTRAP_VERSION]);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($response === false || $httpCode < 200 || $httpCode >= 400) {
        // Fallback: Check if this is local authority or server has direct connectivity
        sendJson([
            'success' => false,
            'message' => 'Authority Validation Failed: ' . ($curlError ?: "HTTP Error {$httpCode} from {$endpoint}"),
            'details' => $response ? json_decode((string) $response, true) : null,
        ], 400);
    }

    $decoded = json_decode((string) $response, true);
    if (!is_array($decoded) || empty($decoded['valid'])) {
        $msg = $decoded['message'] ?? 'License key could not be verified by the central authority.';
        sendJson(['success' => false, 'message' => $msg, 'data' => $decoded], 403);
    }

    sendJson([
        'success' => true,
        'message' => 'License Serial Key verified successfully!',
        'license' => $decoded,
    ]);
}

if ($action === 'download_and_extract') {
    $serial = trim((string) ($_POST['serial'] ?? ''));
    $authorityUrl = rtrim(trim((string) ($_POST['authority_url'] ?? PHYNIX_DEFAULT_AUTHORITY)), '/');

    if ($serial === '') {
        sendJson(['success' => false, 'message' => 'License serial key is required to stream the release package.'], 422);
    }

    // 1. Download stream from Authority
    $downloadUrl = $authorityUrl . '/api/v1/updates/download?serial=' . urlencode($serial) . '&version=' . PHYNIX_BOOTSTRAP_VERSION;

    $fp = fopen($tempZipPath, 'wb');
    if ($fp === false) {
        sendJson(['success' => false, 'message' => 'Failed to create temporary archive file at: ' . $tempZipPath], 500);
    }

    $ch = curl_init($downloadUrl);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 180);
    curl_setopt($ch, CURLOPT_USERAGENT, 'PhynixOne-Installer/' . PHYNIX_BOOTSTRAP_VERSION);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

    $success = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlErr = curl_error($ch);
    curl_close($ch);
    fclose($fp);

    if (!$success || $httpCode !== 200 || filesize($tempZipPath) < 5000) {
        @unlink($tempZipPath);
        sendJson([
            'success' => false,
            'message' => 'Failed to stream release archive from authority (' . ($curlErr ?: "HTTP {$httpCode}") . '). Please ensure serial key is valid.',
        ], 400);
    }

    $zipSize = filesize($tempZipPath);

    // 2. Extract Archive
    $zip = new ZipArchive();
    $res = $zip->open($tempZipPath);
    if ($res !== true) {
        @unlink($tempZipPath);
        sendJson(['success' => false, 'message' => 'Downloaded archive is corrupt or unreadable (ZipArchive code: ' . $res . ').'], 500);
    }

    $extractedCount = 0;
    for ($i = 0; $i < $zip->numFiles; $i++) {
        $entry = $zip->getNameIndex($i);
        // Security check: avoid directory traversal
        if (str_contains($entry, '../') || str_starts_with($entry, '/')) {
            continue;
        }
        $extractedCount++;
    }

    $extractSuccess = $zip->extractTo($targetDir);
    $zip->close();
    @unlink($tempZipPath);

    if (!$extractSuccess) {
        sendJson(['success' => false, 'message' => 'Failed to extract package contents into target directory. Check permissions.'], 500);
    }

    // 3. Ensure required runtime storage subdirectories exist
    $runtimeDirs = [
        $targetDir . '/storage',
        $targetDir . '/storage/framework',
        $targetDir . '/storage/framework/sessions',
        $targetDir . '/storage/backups',
        $targetDir . '/storage/logs',
        $targetDir . '/public/uploads',
    ];
    foreach ($runtimeDirs as $rDir) {
        if (!is_dir($rDir)) {
            @mkdir($rDir, 0755, true);
        }
    }

    // Return success with forward URL
    $nextUrl = '/install.php?serial=' . urlencode($serial) . '&bootstrapped=1';
    if (!file_exists($targetDir . '/public/install.php') && file_exists($targetDir . '/install.php')) {
        $nextUrl = 'install.php?serial=' . urlencode($serial) . '&bootstrapped=1';
    }

    sendJson([
        'success' => true,
        'message' => 'Core files deployed and extracted successfully!',
        'files_extracted' => $extractedCount,
        'archive_size_bytes' => $zipSize,
        'next_url' => $nextUrl,
    ]);
}

// 2. Render HTML Wizard UI
?>
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>PhynixOne - 60-Second Web Bootstrapper</title>
    <link rel="icon" type="image/x-icon" href="/favicon.ico">
    <link rel="icon" type="image/png" sizes="32x32" href="/assets/brand/phynix-one-icon.png">
    <link rel="icon" type="image/png" sizes="192x192" href="/assets/brand/phynix-one-icon.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/assets/brand/phynix-one-icon.png">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #0052ff;
            --primary-glow: rgba(0, 82, 255, 0.35);
            --accent-cyan: #06b6d4;
            --accent-emerald: #10b981;
            --accent-amber: #f59e0b;
            --accent-rose: #ef4444;
            --bg-base: #07090e;
            --bg-surface: #0e121b;
            --bg-elevated: #151b26;
            --border-subtle: rgba(255, 255, 255, 0.08);
            --border-active: rgba(0, 82, 255, 0.4);
            --text-main: #f8fafc;
            --text-muted: #94a3b8;
        }
        [data-theme="light"] {
            --bg-base: #f8fafc;
            --bg-surface: #ffffff;
            --bg-elevated: #f1f5f9;
            --border-subtle: #e2e8f0;
            --border-active: rgba(0, 82, 255, 0.4);
            --text-main: #0f172a;
            --text-muted: #64748b;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: 'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, sans-serif;
            background-color: var(--bg-base);
            color: var(--text-main);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: flex-start;
            padding: 24px 16px 40px;
            background-image: 
                radial-gradient(circle at 50% 0%, rgba(0, 82, 255, 0.18), transparent 50%),
                radial-gradient(circle at 100% 100%, rgba(255, 85, 0, 0.08), transparent 40%);
        }
        [data-theme="light"] body {
            background-image: 
                radial-gradient(circle at 50% 0%, rgba(0, 82, 255, 0.08), transparent 50%),
                radial-gradient(circle at 100% 100%, rgba(255, 85, 0, 0.04), transparent 40%);
        }
        .phx-top-nav {
            width: 100%;
            max-width: 680px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 12px 18px;
            background: rgba(14, 18, 27, 0.7);
            border: 1px solid var(--border-subtle);
            border-radius: 14px;
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            margin-bottom: 24px;
        }
        [data-theme="light"] .phx-top-nav {
            background: rgba(255, 255, 255, 0.9);
            border-color: #e2e8f0;
            box-shadow: 0 4px 15px rgba(15, 23, 42, 0.04);
        }
        .phx-brand {
            display: flex;
            align-items: center;
            gap: 10px;
            text-decoration: none;
            color: var(--text-main);
            font-size: 15px;
            font-weight: 700;
        }
        .phx-badge-inline {
            background: rgba(0, 82, 255, 0.15);
            color: #60a5fa;
            border: 1px solid rgba(0, 82, 255, 0.3);
            font-size: 10px;
            font-weight: 800;
            padding: 2px 7px;
            border-radius: 999px;
            text-transform: uppercase;
            letter-spacing: 0.04em;
        }
        [data-theme="light"] .phx-badge-inline {
            background: #eff6ff;
            color: #1d4ed8;
            border-color: #bfdbfe;
        }
        .phx-nav-actions {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .phx-top-btn {
            font-size: 12.5px;
            font-weight: 600;
            color: var(--text-muted);
            text-decoration: none;
            padding: 6px 12px;
            border-radius: 8px;
            transition: all 0.2s;
        }
        .phx-top-btn:hover {
            color: var(--text-main);
            background: rgba(255, 255, 255, 0.05);
        }
        [data-theme="light"] .phx-top-btn:hover {
            background: #f1f5f9;
        }
        .phx-top-btn.flame {
            background: linear-gradient(135deg, #ff4500 0%, #ff8c00 100%);
            color: #fff !important;
            font-weight: 700;
            box-shadow: 0 2px 10px rgba(255, 69, 0, 0.35);
        }
        .phx-top-btn.flame:hover {
            filter: brightness(1.1);
        }
        .theme-toggle-btn {
            background: transparent;
            border: 1px solid var(--border-subtle);
            border-radius: 8px;
            padding: 5px 10px;
            cursor: pointer;
            font-size: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
            color: var(--text-main);
        }
        .theme-toggle-btn:hover {
            background: var(--bg-elevated);
        }
        .installer-card {
            background: var(--bg-surface);
            border: 1px solid var(--border-subtle);
            border-top: 4px solid var(--primary);
            border-radius: 20px;
            width: 100%;
            max-width: 680px;
            box-shadow: 0 25px 60px -15px rgba(0, 0, 0, 0.7);
            overflow: hidden;
            animation: fadeIn 0.4s ease-out;
        }
        [data-theme="light"] .installer-card {
            box-shadow: 0 20px 45px rgba(15, 23, 42, 0.08);
            border-color: #e2e8f0;
        }
        [data-theme="light"] .installer-header {
            background: #ffffff;
            border-color: #e2e8f0;
        }
        [data-theme="light"] .brand-title {
            background: none;
            -webkit-text-fill-color: #0f172a;
            color: #0f172a;
        }
        [data-theme="light"] .step-progress-bar {
            background: #f8fafc;
            border-bottom-color: #e2e8f0;
        }
        [data-theme="light"] .step-tab {
            color: #64748b;
        }
        [data-theme="light"] .step-tab.active {
            color: #0052ff;
            background: #eff6ff;
            border-bottom-color: #0052ff;
        }
        [data-theme="light"] .step-tab-num {
            background: #e2e8f0;
            color: #475569;
        }
        [data-theme="light"] .step-tab.active .step-tab-num {
            background: #0052ff;
            color: #ffffff;
        }
        [data-theme="light"] h3 {
            color: #0f172a;
        }
        [data-theme="light"] label {
            color: #334155;
        }
        [data-theme="light"] .check-row {
            background: #f8fafc;
            border-color: #e2e8f0;
        }
        [data-theme="light"] .check-title {
            color: #0f172a;
        }
        [data-theme="light"] .check-badge.pass {
            background: #ecfdf5;
            color: #059669;
            border-color: #a7f3d0;
        }
        [data-theme="light"] .check-badge.fail {
            background: #fef2f2;
            color: #dc2626;
            border-color: #fecaca;
        }
        [data-theme="light"] input[type="text"] {
            background: #ffffff;
            border-color: #cbd5e1;
            color: #0f172a;
        }
        [data-theme="light"] .btn-secondary {
            background: #f1f5f9;
            border-color: #cbd5e1;
            color: #334155;
        }
        [data-theme="light"] .btn-secondary:hover {
            background: #e2e8f0;
            color: #0f172a;
        }
        [data-theme="light"] .installer-footer {
            background: #f8fafc;
            border-top-color: #e2e8f0;
            color: #64748b;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(12px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .installer-header {
            padding: 28px 32px 20px;
            border-bottom: 1px solid var(--border-subtle);
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 16px;
        }
        .brand-cluster {
            display: flex;
            align-items: center;
            gap: 14px;
        }
        .brand-icon {
            width: 44px;
            height: 44px;
            border-radius: 12px;
            background: linear-gradient(135deg, #0052ff 0%, #06b6d4 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 16px var(--primary-glow);
            color: #fff;
            font-weight: 800;
            font-size: 20px;
        }
        .brand-title {
            font-size: 20px;
            font-weight: 800;
            letter-spacing: -0.02em;
            background: linear-gradient(135deg, #ffffff 0%, #cbd5e1 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        .brand-subtitle {
            font-size: 12px;
            color: var(--text-muted);
            font-weight: 500;
        }
        .badge-version {
            font-family: 'JetBrains Mono', monospace;
            font-size: 11px;
            font-weight: 600;
            background: rgba(0, 82, 255, 0.12);
            color: #60a5fa;
            border: 1px solid rgba(0, 82, 255, 0.3);
            padding: 4px 10px;
            border-radius: 9999px;
        }
        .step-progress-bar {
            display: flex;
            background: rgba(0, 0, 0, 0.25);
            border-bottom: 1px solid var(--border-subtle);
        }
        .step-tab {
            flex: 1;
            padding: 12px 16px;
            font-size: 12px;
            font-weight: 600;
            color: var(--text-muted);
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            border-bottom: 2px solid transparent;
            transition: all 0.2s;
        }
        .step-tab.active {
            color: #fff;
            border-bottom-color: var(--primary);
            background: rgba(0, 82, 255, 0.05);
        }
        .step-tab.completed {
            color: var(--accent-emerald);
            border-bottom-color: var(--accent-emerald);
        }
        .step-tab-num {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.1);
            font-size: 11px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .step-tab.active .step-tab-num {
            background: var(--primary);
            color: #fff;
        }
        .step-tab.completed .step-tab-num {
            background: var(--accent-emerald);
            color: #000;
        }
        .installer-body {
            padding: 32px;
        }
        .step-pane {
            display: none;
        }
        .step-pane.active {
            display: block;
        }
        h3 {
            font-size: 18px;
            font-weight: 700;
            margin-bottom: 8px;
            letter-spacing: -0.01em;
        }
        p.desc {
            font-size: 13.5px;
            color: var(--text-muted);
            line-height: 1.6;
            margin-bottom: 24px;
        }
        .check-grid {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-bottom: 24px;
        }
        .check-row {
            background: var(--bg-elevated);
            border: 1px solid var(--border-subtle);
            border-radius: 10px;
            padding: 12px 16px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 16px;
        }
        .check-title {
            font-size: 13px;
            font-weight: 600;
        }
        .check-info {
            font-size: 11.5px;
            color: var(--text-muted);
            font-family: 'JetBrains Mono', monospace;
            margin-top: 2px;
        }
        .check-badge {
            font-size: 11px;
            font-weight: 700;
            padding: 4px 10px;
            border-radius: 6px;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        .check-badge.pass {
            background: rgba(16, 185, 129, 0.12);
            color: #34d399;
            border: 1px solid rgba(16, 185, 129, 0.3);
        }
        .check-badge.fail {
            background: rgba(239, 68, 68, 0.12);
            color: #f87171;
            border: 1px solid rgba(239, 68, 68, 0.3);
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            font-size: 12.5px;
            font-weight: 600;
            color: #cbd5e1;
            margin-bottom: 8px;
            text-transform: uppercase;
            letter-spacing: 0.04em;
        }
        input[type="text"] {
            width: 100%;
            background: var(--bg-elevated);
            border: 1px solid var(--border-subtle);
            border-radius: 10px;
            padding: 14px 16px;
            color: #fff;
            font-family: 'JetBrains Mono', monospace;
            font-size: 14px;
            transition: all 0.2s;
        }
        input[type="text"]:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px var(--primary-glow);
        }
        .btn-row {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            gap: 12px;
            margin-top: 28px;
        }
        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            padding: 12px 24px;
            border-radius: 10px;
            font-size: 13.5px;
            font-weight: 700;
            cursor: pointer;
            border: none;
            transition: all 0.2s;
            text-decoration: none;
        }
        .btn-primary {
            background: linear-gradient(135deg, #0052ff 0%, #0045d8 100%);
            color: #fff;
            box-shadow: 0 4px 16px var(--primary-glow);
        }
        .btn-primary:hover:not(:disabled) {
            transform: translateY(-1px);
            box-shadow: 0 6px 20px rgba(0, 82, 255, 0.5);
        }
        .btn-primary:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .btn-secondary {
            background: var(--bg-elevated);
            color: var(--text-muted);
            border: 1px solid var(--border-subtle);
        }
        .btn-secondary:hover {
            color: #fff;
            border-color: rgba(255, 255, 255, 0.2);
        }
        .console-stream {
            background: #06080c;
            border: 1px solid rgba(255, 255, 255, 0.08);
            border-radius: 10px;
            padding: 16px;
            font-family: 'JetBrains Mono', monospace;
            font-size: 12px;
            color: #94a3b8;
            height: 180px;
            overflow-y: auto;
            margin-bottom: 20px;
            line-height: 1.7;
        }
        .console-stream .log-ok { color: #34d399; }
        .console-stream .log-err { color: #f87171; }
        .console-stream .log-info { color: #60a5fa; }
        .progress-bar-container {
            height: 8px;
            background: var(--bg-elevated);
            border-radius: 9999px;
            overflow: hidden;
            margin-bottom: 20px;
        }
        .progress-bar-fill {
            height: 100%;
            width: 0%;
            background: linear-gradient(90deg, #0052ff, #06b6d4);
            transition: width 0.3s ease;
        }
        .installer-footer {
            padding: 16px 32px;
            border-top: 1px solid var(--border-subtle);
            background: rgba(0, 0, 0, 0.2);
            font-size: 11.5px;
            color: var(--text-muted);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
    </style>
</head>
<body>

<!-- Phynix Unified Brand Topbar -->
<header class="phx-top-nav">
    <a href="https://phynix.one" target="_blank" rel="noopener" class="phx-brand">
        <img src="/assets/brand/phynix-one-icon.png" alt="PhynixOne" style="height:26px;width:26px;object-fit:contain;border-radius:6px;">
        <span class="phx-logo-text">Phynix<strong style="background:linear-gradient(135deg, #E6011D, #79037F, #0052FF);-webkit-background-clip:text;-webkit-text-fill-color:transparent;">One</strong></span>
    </a>
    <div class="phx-nav-actions">
        <button type="button" class="theme-toggle-btn" onclick="toggleInstallerTheme()" id="themeToggleBtn" title="Toggle Light / Dark Mode">
            <span id="themeToggleIcon">🌙</span>
        </button>
        <a href="https://phynix.one/buy-license" target="_blank" rel="noopener" class="phx-top-btn flame">Buy License &rarr;</a>
        <a href="https://phynix.one/docs" target="_blank" rel="noopener" class="phx-top-btn">Docs</a>
        <a href="https://phynix.one/portal" target="_blank" rel="noopener" class="phx-top-btn">Client Portal</a>
    </div>
</header>

<div class="installer-card">
    <div class="installer-header">
        <div class="brand-cluster">
            <img src="/assets/brand/phynix-one-icon.png" alt="PhynixOne" style="height:40px;width:40px;object-fit:contain;border-radius:10px;">
            <div>
                <div class="brand-title">PhynixOne</div>
                <div class="brand-subtitle">Autonomous Web Hosting &amp; Cloud Platform</div>
            </div>
        </div>
        <div class="badge-version">v<?= htmlspecialchars(PHYNIX_BOOTSTRAP_VERSION) ?></div>
    </div>

    <div class="step-progress-bar">
        <div class="step-tab active" id="tab-1">
            <span class="step-tab-num">1</span>
            <span>Pre-Flight</span>
        </div>
        <div class="step-tab" id="tab-2">
            <span class="step-tab-num">2</span>
            <span>License Key</span>
        </div>
        <div class="step-tab" id="tab-3">
            <span class="step-tab-num">3</span>
            <span>Deploy Core</span>
        </div>
        <div class="step-tab" id="tab-4">
            <span class="step-tab-num">4</span>
            <span>Complete</span>
        </div>
    </div>

    <div class="installer-body">
        <!-- Step 1: Pre-Flight -->
        <div class="step-pane active" id="pane-1">
            <h3>System Environment Diagnostics</h3>
            <p class="desc">Verifying your server's PHP runtime, cryptographic libraries, and file write permissions before downloading the core suite.</p>
            
            <div class="check-grid" id="checks-container">
                <div style="text-align:center; padding: 24px; color: var(--text-muted);">
                    Running environment inspection...
                </div>
            </div>

            <div class="btn-row">
                <button type="button" class="btn btn-secondary" onclick="runPreflight()">Re-Scan Environment</button>
                <button type="button" class="btn btn-primary" id="btn-to-step2" disabled onclick="goToStep(2)">
                    Continue to License &rarr;
                </button>
            </div>
        </div>

        <!-- Step 2: License Key -->
        <div class="step-pane" id="pane-2">
            <h3>License Authorization</h3>
            <p class="desc">Enter the commercial product serial key delivered in your order confirmation email or client portal.</p>

            <div style="background:rgba(0, 82, 255, 0.08); border:1px solid rgba(0, 82, 255, 0.25); border-radius:12px; padding:12px 16px; margin-bottom:20px; font-size:13px; color:#cbd5e1; display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap;">
                <span>Need a commercial license key?</span>
                <a href="https://phynix.one/buy-license" target="_blank" rel="noopener" style="color:#60a5fa; font-weight:700; text-decoration:none;">Buy Phynix360 on phynix.one &rarr;</a>
            </div>

            <div class="form-group">
                <label for="serial_key">License Serial Key</label>
                <input type="text" id="serial_key" placeholder="PX1-XXXX-XXXX-XXXX-XXXX" autocomplete="off" spellcheck="false">
                <div style="font-size: 11.5px; color: var(--text-muted); margin-top: 6px;">
                    Format: <code>PX1-XXXX-XXXX-XXXX-XXXX</code> (Included in your purchase receipt)
                </div>
            </div>

            <div class="form-group">
                <label for="authority_url">Authority Endpoint (Default: phynix.one)</label>
                <input type="text" id="authority_url" value="https://phynix.one">
            </div>

            <div id="license-alert" style="display:none; padding:12px 16px; border-radius:10px; font-size:13px; margin-bottom:16px;"></div>

            <div class="btn-row">
                <button type="button" class="btn btn-secondary" onclick="goToStep(1)">&larr; Back</button>
                <button type="button" class="btn btn-primary" id="btn-verify-license" onclick="verifyLicense()">
                    Verify & Stream Package &rarr;
                </button>
            </div>
        </div>

        <!-- Step 3: Stream and Extract -->
        <div class="step-pane" id="pane-3">
            <h3>Streaming Core Platform Package</h3>
            <p class="desc">Downloading production release archive from the central authority and extracting files into your webroot.</p>

            <div class="progress-bar-container">
                <div class="progress-bar-fill" id="deploy-progress"></div>
            </div>

            <div class="console-stream" id="deploy-console">
                <div class="log-info">[INIT] Ready to stream release package...</div>
            </div>

            <div class="btn-row">
                <button type="button" class="btn btn-primary" id="btn-start-extract" onclick="startStreamExtract()">
                    Start 60-Second Setup
                </button>
            </div>
        </div>

        <!-- Step 4: Complete -->
        <div class="step-pane" id="pane-4">
            <div style="text-align: center; padding: 16px 0;">
                <div style="font-size: 48px; margin-bottom: 16px;">&#x2705;</div>
                <h3>Core Platform Deployed Successfully!</h3>
                <p class="desc" style="max-width: 500px; margin: 0 auto 24px;">
                    All application source files, controllers, views, assets, and storage directories have been extracted. You are now ready to launch the interactive database setup wizard.
                </p>

                <div style="background: var(--bg-elevated); border:1px solid var(--border-subtle); border-radius:12px; padding:16px; max-width:440px; margin:0 auto 24px; text-align:left; font-size:13px;">
                    <div style="color:var(--text-muted); margin-bottom:6px;">Next Step:</div>
                    <div style="font-weight:700; color:#fff;">Interactive Database & Administrator Setup</div>
                    <div style="color:var(--accent-cyan); font-size:12px; margin-top:4px;">Creates MySQL tables and registers your superadmin credentials.</div>
                </div>

                <a href="#" id="link-launch-installer" class="btn btn-primary" style="padding:14px 32px; font-size:15px;">
                    Launch Database Installer (install.php) &rarr;
                </a>
            </div>
        </div>
    </div>

    <div class="installer-footer">
        <div>Powered by <a href="https://phynix.one" target="_blank" rel="noopener" style="color:var(--text-muted); text-decoration:none; font-weight:700;">Phynix360</a> Enterprise Engine</div>
        <div>&copy; <?= date('Y') ?> Phynix Technologies Private Limited · <a href="https://phynix.one" target="_blank" rel="noopener" style="color:#60a5fa; text-decoration:none;">phynix.one</a></div>
    </div>
</div>

<script>
function initInstallerTheme() {
    const saved = localStorage.getItem('phx_installer_theme') || 'light';
    applyInstallerTheme(saved);
}
function toggleInstallerTheme() {
    const current = document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
    localStorage.setItem('phx_installer_theme', current);
    applyInstallerTheme(current);
}
function applyInstallerTheme(theme) {
    document.documentElement.setAttribute('data-theme', theme);
    const icon = document.getElementById('themeToggleIcon');
    if (icon) {
        icon.textContent = theme === 'dark' ? '☀️' : '🌙';
    }
}
initInstallerTheme();

let state = {
    step: 1,
    serial: '',
    authority: 'https://phynix.one',
    preflightPassed: false
};

function logToConsole(msg, type = 'info') {
    const consoleEl = document.getElementById('deploy-console');
    const div = document.createElement('div');
    div.className = 'log-' + type;
    div.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`;
    consoleEl.appendChild(div);
    consoleEl.scrollTop = consoleEl.scrollHeight;
}

function setProgress(pct) {
    document.getElementById('deploy-progress').style.width = pct + '%';
}

function goToStep(stepNum) {
    state.step = stepNum;
    for (let i = 1; i <= 4; i++) {
        const tab = document.getElementById('tab-' + i);
        const pane = document.getElementById('pane-' + i);
        if (i === stepNum) {
            tab.className = 'step-tab active';
            pane.className = 'step-pane active';
        } else if (i < stepNum) {
            tab.className = 'step-tab completed';
            pane.className = 'step-pane';
        } else {
            tab.className = 'step-tab';
            pane.className = 'step-pane';
        }
    }
}

async function runPreflight() {
    const container = document.getElementById('checks-container');
    container.innerHTML = '<div style="text-align:center; padding: 24px; color: var(--text-muted);">Running environment inspection...</div>';
    
    try {
        const res = await fetch('phynix-setup.php?action=preflight');
        const data = await res.json();
        
        container.innerHTML = '';
        data.checks.forEach(check => {
            const row = document.createElement('div');
            row.className = 'check-row';
            row.innerHTML = `
                <div>
                    <div class="check-title">${check.name}</div>
                    <div class="check-info">${check.info}</div>
                </div>
                <span class="check-badge ${check.status ? 'pass' : 'fail'}">${check.status ? 'PASS' : 'FAIL'}</span>
            `;
            container.appendChild(row);
        });

        state.preflightPassed = data.success;
        document.getElementById('btn-to-step2').disabled = !data.success;
    } catch (err) {
        container.innerHTML = `<div style="color:var(--accent-rose); padding:16px;">Error inspecting environment: ${err.message}</div>`;
    }
}

async function verifyLicense() {
    const serialInput = document.getElementById('serial_key').value.trim();
    const authorityInput = document.getElementById('authority_url').value.trim();
    const alertBox = document.getElementById('license-alert');
    const btn = document.getElementById('btn-verify-license');

    if (!serialInput) {
        alertBox.style.display = 'block';
        alertBox.style.background = 'rgba(239, 68, 68, 0.15)';
        alertBox.style.color = '#f87171';
        alertBox.textContent = 'Please enter your license serial key.';
        return;
    }

    state.serial = serialInput;
    state.authority = authorityInput;

    btn.disabled = true;
    btn.textContent = 'Validating Serial Key...';
    alertBox.style.display = 'none';

    try {
        const formData = new FormData();
        formData.append('action', 'verify_key');
        formData.append('serial', serialInput);
        formData.append('authority_url', authorityInput);

        const res = await fetch('phynix-setup.php', { method: 'POST', body: formData });
        const data = await res.json();

        if (data.success) {
            goToStep(3);
        } else {
            alertBox.style.display = 'block';
            alertBox.style.background = 'rgba(239, 68, 68, 0.15)';
            alertBox.style.color = '#f87171';
            alertBox.textContent = data.message || 'License validation failed.';
        }
    } catch (err) {
        alertBox.style.display = 'block';
        alertBox.style.background = 'rgba(239, 68, 68, 0.15)';
        alertBox.style.color = '#f87171';
        alertBox.textContent = 'Network error contacting verification endpoint: ' + err.message;
    } finally {
        btn.disabled = false;
        btn.textContent = 'Verify & Stream Package \u2192';
    }
}

async function startStreamExtract() {
    const btn = document.getElementById('btn-start-extract');
    btn.disabled = true;
    btn.textContent = 'Streaming & Extracting...';

    setProgress(20);
    logToConsole('Connecting to release repository at ' + state.authority, 'info');

    try {
        const formData = new FormData();
        formData.append('action', 'download_and_extract');
        formData.append('serial', state.serial);
        formData.append('authority_url', state.authority);

        setProgress(45);
        logToConsole('Downloading release package payload...', 'info');

        const res = await fetch('phynix-setup.php', { method: 'POST', body: formData });
        const data = await res.json();

        if (data.success) {
            setProgress(85);
            logToConsole('Archive received (' + Math.round(data.archive_size_bytes / 1024) + ' KB)', 'ok');
            logToConsole('Extracted ' + data.files_extracted + ' files successfully.', 'ok');
            logToConsole('Directory permissions & storage runtime configured.', 'ok');
            setProgress(100);

            document.getElementById('link-launch-installer').href = data.next_url;
            setTimeout(() => {
                goToStep(4);
            }, 800);
        } else {
            setProgress(0);
            logToConsole('DEPLOYMENT FAILED: ' + data.message, 'err');
            btn.disabled = false;
            btn.textContent = 'Retry Deployment';
        }
    } catch (err) {
        setProgress(0);
        logToConsole('EXCEPTION: ' + err.message, 'err');
        btn.disabled = false;
        btn.textContent = 'Retry Deployment';
    }
}

// Initial preflight trigger
window.addEventListener('DOMContentLoaded', () => {
    // If URL contains serial param, prepopulate
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('serial')) {
        document.getElementById('serial_key').value = urlParams.get('serial');
    }
    runPreflight();
});
</script>
</body>
</html>
