<?php
/**
 * FreeCMS - Professional Installation Wizard
 * This script will help you set up your forum and CMS platform.
 */

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

define('ROOT', dirname(__DIR__));
define('INSTALL_LOCK', ROOT . '/install.lock');

// Block access if already installed
if (file_exists(INSTALL_LOCK)) {
    die('<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Already Installed</title><style>body{font-family:sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;background:#0f172a;color:#f8fafc;} .box{text-align:center;padding:3rem;background:#1e293b;border-radius:1rem;border:1px solid #334155;} h1{color:#ef4444;} a{color:#6366f1;}</style></head><body><div class="box"><h1>&#128274; Already Installed</h1><p>FreeCMS is already installed. Delete <code>install.lock</code> to reinstall.</p><a href="/">Go to site</a></div></body></html>');
}

// Set session cookie params to ensure it works across different paths if needed
session_set_cookie_params([
    'path' => '/',
    'samesite' => 'Lax'
]);
session_start();

$step = (int)($_GET['step'] ?? 1);

// Supported languages
$languages = [
    'en' => ['name' => 'English',    'flag' => '🇬🇧'],
    'ua' => ['name' => 'Українська', 'flag' => '🇺🇦'],
    'ru' => ['name' => 'Русский',    'flag' => '🇷🇺'],
    'pl' => ['name' => 'Polski',     'flag' => '🇵🇱'],
];

// Translations for installer UI
$i18n = [
    'en' => [
        'title'           => 'FreeCMS Installer',
        'step1'           => 'Language',
        'step2'           => 'Requirements',
        'step3'           => 'Database',
        'step4'           => 'Site & Admin',
        'step5'           => 'Install',
        'select_lang'     => 'Select Language',
        'continue'        => 'Continue',
        'req_ok'          => 'All requirements met!',
        'req_fail'        => 'Some requirements are not met. Fix them before continuing.',
        'php_version'     => 'PHP Version (8.0+)',
        'pdo_ext'         => 'PDO Extension',
        'pdo_mysql'       => 'PDO MySQL Driver',
        'mbstring'        => 'Mbstring Extension',
        'openssl'         => 'OpenSSL Extension',
        'json_ext'        => 'JSON Extension',
        'writable_root'   => 'Root directory writable',
        'writable_public' => 'Public directory writable',
        'db_host'         => 'Database Host',
        'db_port'         => 'Database Port',
        'db_name'         => 'Database Name',
        'db_user'         => 'Database Username',
        'db_pass'         => 'Database Password',
        'test_conn'       => 'Test Connection',
        'conn_ok'         => 'Connection successful!',
        'conn_fail'       => 'Connection failed',
        'site_name'       => 'Site Name',
        'site_url'        => 'Site URL',
        'app_env'         => 'Environment',
        'admin_user'      => 'Admin Username',
        'admin_email'     => 'Admin Email',
        'admin_pass'      => 'Admin Password',
        'admin_pass2'     => 'Confirm Password',
        'install_btn'     => 'Install FreeCMS',
        'installing'      => 'Installing...',
        'success'         => 'Installation Complete!',
        'success_msg'     => 'FreeCMS has been successfully installed. The installer has been locked.',
        'go_site'         => 'Go to Site',
        'go_login'        => 'Login as Admin',
        'error'           => 'Error',
        'pass_mismatch'   => 'Passwords do not match.',
        'pass_weak'       => 'Password must be at least 8 characters.',
        'env_written'     => '.env file written',
        'db_imported'     => 'Database imported',
        'admin_created'   => 'Admin account created',
        'locked'          => 'Installer locked',
        'next'            => 'Next →',
        'back'            => '← Back',
        'themes'          => 'Themes',
        'participants'    => 'Participants',
        'online'          => 'Online',
    ],
    'ua' => [
        'title'           => 'Інсталятор FreeCMS',
        'step1'           => 'Мова',
        'step2'           => 'Вимоги',
        'step3'           => 'База даних',
        'step4'           => 'Сайт та адмін',
        'step5'           => 'Встановлення',
        'select_lang'     => 'Оберіть мову',
        'continue'        => 'Продовжити',
        'req_ok'          => 'Всі вимоги виконані!',
        'req_fail'        => 'Деякі вимоги не виконані. Виправте їх перед продовженням.',
        'php_version'     => 'Версія PHP (8.0+)',
        'pdo_ext'         => 'Розширення PDO',
        'pdo_mysql'       => 'Драйвер PDO MySQL',
        'mbstring'        => 'Розширення Mbstring',
        'openssl'         => 'Розширення OpenSSL',
        'json_ext'        => 'Розширення JSON',
        'writable_root'   => 'Коренева директорія доступна для запису',
        'writable_public' => 'Директорія public доступна для запису',
        'db_host'         => 'Хост бази даних',
        'db_port'         => 'Порт бази даних',
        'db_name'         => 'Ім\'я бази даних',
        'db_user'         => 'Користувач БД',
        'db_pass'         => 'Пароль БД',
        'test_conn'       => 'Перевірити з\'єднання',
        'conn_ok'         => 'З\'єднання успішне!',
        'conn_fail'       => 'Помилка з\'єднання',
        'site_name'       => 'Назва сайту',
        'site_url'        => 'URL сайту',
        'app_env'         => 'Середовище',
        'admin_user'      => 'Ім\'я адміністратора',
        'admin_email'     => 'Email адміністратора',
        'admin_pass'      => 'Пароль адміністратора',
        'admin_pass2'     => 'Підтвердіть пароль',
        'install_btn'     => 'Встановити FreeCMS',
        'installing'      => 'Встановлення...',
        'success'         => 'Встановлення завершено!',
        'success_msg'     => 'FreeCMS успішно встановлено. Папку інсталятора заблоковано.',
        'go_site'         => 'На сайт',
        'go_login'        => 'Увійти як адмін',
        'error'           => 'Помилка',
        'pass_mismatch'   => 'Паролі не збігаються.',
        'pass_weak'       => 'Пароль має бути не менше 8 символів.',
        'env_written'     => 'Файл .env записано',
        'db_imported'     => 'Базу даних імпортовано',
        'admin_created'   => 'Обліковий запис адміна створено',
        'locked'          => 'Інсталятор заблоковано',
        'next'            => 'Далі →',
        'back'            => '← Назад',
        'themes'          => 'Теми',
        'participants'    => 'Учасники',
        'online'          => 'Онлайн',
    ],
    'ru' => [
        'title'           => 'Установщик FreeCMS',
        'step1'           => 'Язык',
        'step2'           => 'Требования',
        'step3'           => 'База данных',
        'step4'           => 'Сайт и админ',
        'step5'           => 'Установка',
        'select_lang'     => 'Выберите язык',
        'continue'        => 'Продолжить',
        'req_ok'          => 'Все требования выполнены!',
        'req_fail'        => 'Некоторые требования не выполнены. Исправьте их перед продолжением.',
        'php_version'     => 'Версия PHP (8.0+)',
        'pdo_ext'         => 'Расширение PDO',
        'pdo_mysql'       => 'Драйвер PDO MySQL',
        'mbstring'        => 'Расширение Mbstring',
        'openssl'         => 'Расширение OpenSSL',
        'json_ext'        => 'Расширение JSON',
        'writable_root'   => 'Корневая директория доступна для записи',
        'writable_public' => 'Директория public доступна для записи',
        'db_host'         => 'Хост базы данных',
        'db_port'         => 'Порт базы данных',
        'db_name'         => 'Имя базы данных',
        'db_user'         => 'Пользователь БД',
        'db_pass'         => 'Пароль БД',
        'test_conn'       => 'Проверить соединение',
        'conn_ok'         => 'Соединение успешно!',
        'conn_fail'       => 'Ошибка соединения',
        'site_name'       => 'Название сайта',
        'site_url'        => 'URL сайта',
        'app_env'         => 'Среда',
        'admin_user'      => 'Имя администратора',
        'admin_email'     => 'Email администратора',
        'admin_pass'      => 'Пароль администратора',
        'admin_pass2'     => 'Подтвердите пароль',
        'install_btn'     => 'Установить FreeCMS',
        'installing'      => 'Установка...',
        'success'         => 'Установка завершена!',
        'success_msg'     => 'FreeCMS успешно установлена. Инсталлятор заблокирован.',
        'go_site'         => 'На сайт',
        'go_login'        => 'Войти как админ',
        'error'           => 'Ошибка',
        'pass_mismatch'   => 'Пароли не совпадают.',
        'pass_weak'       => 'Пароль должен быть не менее 8 символов.',
        'env_written'     => 'Файл .env записан',
        'db_imported'     => 'База данных импортирована',
        'admin_created'   => 'Аккаунт админа создан',
        'locked'          => 'Инсталлятор заблокирован',
        'next'            => 'Далее →',
        'back'            => '← Назад',
        'themes'          => 'Темы',
        'participants'    => 'Участники',
        'online'          => 'Онлайн',
    ],
    'pl' => [
        'title'           => 'Instalator FreeCMS',
        'step1'           => 'Język',
        'step2'           => 'Wymagania',
        'step3'           => 'Baza danych',
        'step4'           => 'Witryna i admin',
        'step5'           => 'Instalacja',
        'select_lang'     => 'Wybierz język',
        'continue'        => 'Kontynuuj',
        'req_ok'          => 'Wszystkie wymagania spełnione!',
        'req_fail'        => 'Niektóre wymagania nie są spełnione. Popraw je przed kontynuacją.',
        'php_version'     => 'Wersja PHP (8.0+)',
        'pdo_ext'         => 'Rozszerzenie PDO',
        'pdo_mysql'       => 'Sterownik PDO MySQL',
        'mbstring'        => 'Rozszerzenie Mbstring',
        'openssl'         => 'Rozszerzenie OpenSSL',
        'json_ext'        => 'Rozszerzenie JSON',
        'writable_root'   => 'Katalog główny zapisywalny',
        'writable_public' => 'Katalog public zapisywalny',
        'db_host'         => 'Host bazy danych',
        'db_port'         => 'Port bazy danych',
        'db_name'         => 'Nazwa bazy danych',
        'db_user'         => 'Użytkownik bazy danych',
        'db_pass'         => 'Hasło bazy danych',
        'test_conn'       => 'Testuj połączenie',
        'conn_ok'         => 'Połączenie pomyślne!',
        'conn_fail'       => 'Połączenie nieudane',
        'site_name'       => 'Nazwa witryny',
        'site_url'        => 'URL witryny',
        'app_env'         => 'Środowisko',
        'admin_user'      => 'Nazwa użytkownika administratora',
        'admin_email'     => 'E-mail administratora',
        'admin_pass'      => 'Hasło administratora',
        'admin_pass2'     => 'Potwierdź hasło',
        'install_btn'     => 'Zainstaluj FreeCMS',
        'installing'      => 'Instalowanie...',
        'success'         => 'Instalacja zakończona!',
        'success_msg'     => 'FreeCMS została pomyślnie zainstalowana. Instalator został zablokowany.',
        'go_site'         => 'Przejdź do witryny',
        'go_login'        => 'Zaloguj się jako administrator',
        'error'           => 'Błąd',
        'pass_mismatch'   => 'Hasła nie pasują do siebie.',
        'pass_weak'       => 'Hasło musi mieć co najmniej 8 znaków.',
        'env_written'     => 'Plik .env został zapisany',
        'db_imported'     => 'Baza danych została zaimportowana',
        'admin_created'   => 'Konto administratora zostało utworzone',
        'locked'          => 'Instalator zablokowany',
        'next'            => 'Dalej →',
        'back'            => '← Wstecz',
        'themes'          => 'Tematy',
        'participants'    => 'Uczestnicy',
        'online'          => 'Online',
    ],
];

// Ensure session starts at the very beginning of the handle Step 1
if (session_status() === PHP_SESSION_NONE) {
    session_set_cookie_params(['path' => '/', 'samesite' => 'Lax']);
    session_start();
}

// Handle Step 1 POST: set language
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['lang'])) {
    $lang = in_array($_POST['lang'], array_keys($languages)) ? $_POST['lang'] : 'en';
    $_SESSION['install_lang'] = $lang;
    header('Location: ?step=2');
    exit;
}

$lang = $_SESSION['install_lang'] ?? 'en';
$t    = $i18n[$lang] ?? $i18n['en'];

// ── Requirements check ──────────────────────────────────────────────────────
function checkRequirements(): array {
    return [
        'php_version'     => version_compare(PHP_VERSION, '8.0.0', '>='),
        'pdo_ext'         => extension_loaded('pdo'),
        'pdo_mysql'       => extension_loaded('pdo_mysql'),
        'mbstring'        => extension_loaded('mbstring'),
        'openssl'         => extension_loaded('openssl'),
        'json_ext'        => extension_loaded('json'),
        'writable_root'   => is_writable(ROOT),
        'writable_public' => is_writable(ROOT . '/public'),
    ];
}

// ── Handle Step 2 → 3 POST ──────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $step === 2) {
    $reqs = checkRequirements();
    if (!in_array(false, $reqs, true)) {
        header('Location: ?step=3');
        exit;
    }
}

// ── Handle Step 3: Save DB config ───────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $step === 3) {
    $_SESSION['install_db'] = [
        'host'     => trim($_POST['db_host'] ?? 'localhost'),
        'port'     => (int)($_POST['db_port'] ?? 3306),
        'database' => trim($_POST['db_name'] ?? ''),
        'username' => trim($_POST['db_user'] ?? ''),
        'password' => $_POST['db_pass'] ?? '',
    ];
    header('Location: ?step=4');
    exit;
}

// ── Handle Step 4: Save site/admin config ───────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $step === 4) {
    $errors = [];
    $pass  = $_POST['admin_pass']  ?? '';
    $pass2 = $_POST['admin_pass2'] ?? '';
    if ($pass !== $pass2) $errors[] = $t['pass_mismatch'];
    if (strlen($pass) < 8)  $errors[] = $t['pass_weak'];

    if (empty($errors)) {
        $_SESSION['install_site'] = [
            'site_name' => trim($_POST['site_name'] ?? 'FreeCMS'),
            'site_url'  => rtrim(trim($_POST['site_url']  ?? ''), '/'),
            'app_env'   => in_array($_POST['app_env'] ?? '', ['production','development']) ? $_POST['app_env'] : 'production',
        ];
        $_SESSION['install_admin'] = [
            'username' => trim($_POST['admin_user']  ?? 'admin'),
            'email'    => trim($_POST['admin_email'] ?? ''),
            'password' => $pass,
        ];
        header('Location: ?step=5');
        exit;
    }
}

// ── Handle Step 5: Do the install ───────────────────────────────────────────
$installLog    = [];
$installErrors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $step === 5) {
    $db   = $_SESSION['install_db']    ?? [];
    $site = $_SESSION['install_site']  ?? [];
    $adm  = $_SESSION['install_admin'] ?? [];

    try {
        // 1. Connect to MySQL
        $dsn = "mysql:host={$db['host']};port={$db['port']};charset=utf8mb4";
        $pdo = new PDO($dsn, $db['username'], $db['password'], [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        ]);

        // 2. Create DB if not exists
        $dbName = preg_replace('/[^a-zA-Z0-9_]/', '', $db['database']);
        $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$dbName}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
        $pdo->exec("USE `{$dbName}`");

        // 3. Import schema
        $sqlFile = ROOT . '/schema.sql';
        if (!file_exists($sqlFile)) throw new Exception("schema.sql not found at " . $sqlFile);
        $sql = file_get_contents($sqlFile);
        
        // Execute statement by statement - Improved Regex to handle semicolons in strings
        $queries = preg_split("/;(?=(?:[^'\"`]*['\"`][^'\"`]*['\"`])*[^'\"`]*$)/", $sql);
        foreach ($queries as $q) {
            $q = trim($q);
            if ($q !== '') {
                try {
                    $pdo->exec($q);
                } catch (Exception $e) {
                    // Log error but continue for IF NOT EXISTS/IGNORE queries
                    error_log("SQL Error in installer: " . $e->getMessage() . " Query: " . substr($q, 0, 100));
                }
            }
        }

        $installLog[] = ['ok' => true, 'msg' => $t['db_imported']];

        // 4. Create admin user (role_id=3)
        $hash = password_hash($adm['password'], PASSWORD_BCRYPT, ['cost' => 12]);
        $stmt = $pdo->prepare("INSERT INTO users (username, email, password, role_id, email_verified_at) VALUES (?, ?, ?, 3, NOW()) ON DUPLICATE KEY UPDATE password=VALUES(password), role_id=3");
        $stmt->execute([$adm['username'], $adm['email'], $hash]);
        $installLog[] = ['ok' => true, 'msg' => $t['admin_created']];

        // 5. Write .env
        $appKey = bin2hex(random_bytes(32));
        $env = "APP_NAME=\"{$site['site_name']}\"\n";
        $env .= "APP_ENV={$site['app_env']}\n";
        $env .= "APP_URL={$site['site_url']}\n";
        $env .= "APP_KEY={$appKey}\n\n";
        $env .= "DB_CONNECTION=mysql\n";
        $env .= "DB_HOST={$db['host']}\n";
        $env .= "DB_PORT={$db['port']}\n";
        $env .= "DB_DATABASE={$dbName}\n";
        $env .= "DB_USERNAME={$db['username']}\n";
        $env .= "DB_PASSWORD={$db['password']}\n\n";
        $env .= "DEFAULT_LANG={$lang}\n";

        file_put_contents(ROOT . '/.env', $env);
        $installLog[] = ['ok' => true, 'msg' => $t['env_written']];

        // 6. Lock the installer
        file_put_contents(INSTALL_LOCK, date('Y-m-d H:i:s') . ' — Installed by ' . htmlspecialchars($adm['username']));
        $installLog[] = ['ok' => true, 'msg' => $t['locked']];

        // 7. Clear session
        session_destroy();
        $step = 99; // success screen

    } catch (Exception $e) {
        $installErrors[] = $e->getMessage();
    }
}

// ── AJAX: Test DB connection (Step 3) ───────────────────────────────────────
if (isset($_GET['action']) && $_GET['action'] === 'test_db') {
    header('Content-Type: application/json');
    try {
        $h = $_POST['db_host'] ?? 'localhost';
        $p = (int)($_POST['db_port'] ?? 3306);
        $u = $_POST['db_user'] ?? '';
        $pw = $_POST['db_pass'] ?? '';
        $pdo = new PDO("mysql:host=$h;port=$p;charset=utf8mb4", $u, $pw, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
        echo json_encode(['ok' => true, 'msg' => $t['conn_ok']]);
    } catch (Exception $e) {
        echo json_encode(['ok' => false, 'msg' => $t['conn_fail'] . ': ' . $e->getMessage()]);
    }
    exit;
}

$reqs    = checkRequirements();
$allGood = !in_array(false, $reqs, true);
$errors  = $errors ?? [];
?>
<!DOCTYPE html>
<html lang="<?= $lang ?>" data-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $t['title'] ?></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
:root {
    --primary: #6366f1;
    --primary-hover: #4f46e5;
    --bg: #0f172a;
    --card: rgba(30,41,59,0.9);
    --text: #f8fafc;
    --text-muted: #94a3b8;
    --border: rgba(51,65,85,0.6);
    --success: #10b981;
    --error: #ef4444;
    --radius: 1rem;
}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    background: var(--bg);
    background-image: radial-gradient(at 0% 0%, rgba(99,102,241,.15) 0, transparent 50%),
                      radial-gradient(at 100% 100%, rgba(99,102,241,.1) 0, transparent 50%);
    color: var(--text);
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 2rem 1rem;
}
.installer {
    width: 100%;
    max-width: 580px;
}
.logo {
    font-size: 2rem;
    font-weight: 800;
    background: linear-gradient(135deg, #6366f1, #ec4899);
    -webkit-background-clip: text;
    background-clip: text;
    -webkit-text-fill-color: transparent;
    text-align: center;
    margin-bottom: 0.25rem;
}
.subtitle { text-align: center; color: var(--text-muted); margin-bottom: 2rem; font-size: 0.9rem; }
.steps {
    display: flex;
    justify-content: center;
    gap: 0;
    margin-bottom: 2rem;
    overflow: hidden;
    border-radius: 0.75rem;
    border: 1px solid var(--border);
}
.step-item {
    flex: 1;
    padding: 0.6rem 0.5rem;
    text-align: center;
    font-size: 0.72rem;
    font-weight: 600;
    color: var(--text-muted);
    background: var(--card);
    border-right: 1px solid var(--border);
    transition: all 0.3s;
}
.step-item:last-child { border-right: none; }
.step-item.active { background: var(--primary); color: white; }
.step-item.done { background: rgba(16,185,129,.15); color: var(--success); }
.card {
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 2rem;
    backdrop-filter: blur(20px);
}
h2 { font-size: 1.3rem; margin-bottom: 1.5rem; display: flex; align-items: center; gap: 0.75rem; }
h2 i { color: var(--primary); }
.lang-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 0.75rem;
    margin-bottom: 1.5rem;
}
.lang-btn {
    padding: 1rem;
    border-radius: 0.75rem;
    border: 2px solid var(--border);
    background: transparent;
    color: var(--text);
    font-size: 1rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    gap: 0.75rem;
    justify-content: center;
}
.lang-btn:hover, .lang-btn.selected { border-color: var(--primary); background: rgba(99,102,241,.1); color: var(--primary); }
.lang-btn .flag { font-size: 1.5rem; }
.form-group { margin-bottom: 1.25rem; }
label { display: block; margin-bottom: 0.4rem; font-size: 0.85rem; color: var(--text-muted); font-weight: 600; }
input, select {
    width: 100%;
    padding: 0.75rem 1rem;
    background: rgba(15,23,42,.8);
    border: 1px solid var(--border);
    border-radius: 0.75rem;
    color: var(--text);
    font-size: 0.95rem;
    transition: border-color 0.2s;
    outline: none;
}
input:focus, select:focus { border-color: var(--primary); }
.btn {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.8rem 1.75rem;
    border-radius: 0.75rem;
    font-weight: 700;
    font-size: 0.95rem;
    cursor: pointer;
    border: none;
    transition: all 0.2s;
    text-decoration: none;
}
.btn-primary { background: linear-gradient(135deg, var(--primary), #818cf8); color: white; width: 100%; justify-content: center; }
.btn-primary:hover { opacity: 0.9; transform: translateY(-1px); }
.btn-secondary { background: transparent; border: 1px solid var(--border); color: var(--text); }
.btn-sm { padding: 0.5rem 1rem; font-size: 0.85rem; width: auto; }
.req-list { list-style: none; display: flex; flex-direction: column; gap: 0.5rem; margin-bottom: 1.5rem; }
.req-item { display: flex; align-items: center; gap: 0.75rem; padding: 0.6rem 0.75rem; border-radius: 0.5rem; font-size: 0.9rem; }
.req-item.ok { background: rgba(16,185,129,.08); }
.req-item.fail { background: rgba(239,68,68,.08); }
.req-item .icon-ok { color: var(--success); }
.req-item .icon-fail { color: var(--error); }
.alert { padding: 0.75rem 1rem; border-radius: 0.75rem; margin-bottom: 1rem; font-size: 0.9rem; display: flex; align-items: center; gap: 0.5rem; }
.alert-success { background: rgba(16,185,129,.1); color: var(--success); border: 1px solid rgba(16,185,129,.2); }
.alert-error { background: rgba(239,68,68,.1); color: var(--error); border: 1px solid rgba(239,68,68,.2); }
.install-log { list-style: none; display: flex; flex-direction: column; gap: 0.5rem; margin-bottom: 1.5rem; }
.log-item { display: flex; align-items: center; gap: 0.75rem; padding: 0.6rem 0.75rem; border-radius: 0.5rem; font-size: 0.9rem; }
.log-item.ok { background: rgba(16,185,129,.08); color: var(--success); }
.log-item.err { background: rgba(239,68,68,.08); color: var(--error); }
.success-icon { font-size: 4rem; text-align: center; margin-bottom: 1rem; }
.success-title { font-size: 1.5rem; font-weight: 800; text-align: center; color: var(--success); margin-bottom: 0.5rem; }
.success-msg { text-align: center; color: var(--text-muted); margin-bottom: 1.5rem; font-size: 0.9rem; }
.btn-row { display: flex; gap: 1rem; }
.btn-row .btn { flex: 1; justify-content: center; }
#conn-result { margin-top: 0.75rem; }
.nav-row { display: flex; justify-content: space-between; align-items: center; margin-top: 1.25rem; gap: 1rem; }
.nav-row .btn-primary { flex: 1; }
.two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
@media (max-width: 480px) { .two-col { grid-template-columns: 1fr; } .lang-grid { grid-template-columns: 1fr 1fr; } }
</style>
</head>
<body>

<div class="installer">
    <div class="logo">FreeCMS</div>
    <div class="subtitle"><?= $t['title'] ?></div>

    <?php if ($step < 99): ?>
    <div class="steps">
        <?php $stepNames = [$t['step1'],$t['step2'],$t['step3'],$t['step4'],$t['step5']];
        foreach ($stepNames as $i => $name): $n=$i+1; ?>
            <div class="step-item <?= $step==$n?'active':($step>$n?'done':'') ?>">
                <?= $step>$n?'✓ ':'' ?><?= $name ?>
            </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <div class="card">

    <?php if ($step === 1): ?>
    <h2><i class="fas fa-globe"></i> <?= $t['select_lang'] ?></h2>
    <form method="POST" action="?step=1">
        <div class="lang-grid">
            <?php foreach ($languages as $code => $info): ?>
            <button type="submit" name="lang" value="<?= $code ?>" class="lang-btn <?= ($lang===$code)?'selected':'' ?>">
                <span class="flag"><?= $info['flag'] ?></span> <?= $info['name'] ?>
            </button>
            <?php endforeach; ?>
        </div>
    </form>

    <?php elseif ($step === 2): ?>
    <h2><i class="fas fa-clipboard-check"></i> <?= $t['step2'] ?></h2>
    <?php $keys = ['php_version','pdo_ext','pdo_mysql','mbstring','openssl','json_ext','writable_root','writable_public']; ?>
    <ul class="req-list">
        <?php foreach ($keys as $k): ?>
        <li class="req-item <?= $reqs[$k]?'ok':'fail' ?>">
            <i class="fas <?= $reqs[$k]?'fa-check-circle icon-ok':'fa-times-circle icon-fail' ?>"></i>
            <?= $t[$k] ?>
            <span style="margin-left:auto;font-weight:700;font-size:0.8rem;"><?= $reqs[$k]?'OK':'FAIL' ?></span>
        </li>
        <?php endforeach; ?>
    </ul>
    <?php if ($allGood): ?>
        <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= $t['req_ok'] ?></div>
        <form method="POST" action="?step=2">
            <button type="submit" class="btn btn-primary"><?= $t['next'] ?></button>
        </form>
    <?php else: ?>
        <div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> <?= $t['req_fail'] ?></div>
    <?php endif; ?>

    <?php elseif ($step === 3): ?>
    <h2><i class="fas fa-database"></i> <?= $t['step3'] ?></h2>
    <?php $saved = $_SESSION['install_db'] ?? []; ?>
    <form method="POST" action="?step=3" id="db-form">
        <div class="two-col">
            <div class="form-group">
                <label><?= $t['db_host'] ?></label>
                <input type="text" name="db_host" id="db_host" value="<?= htmlspecialchars($saved['host'] ?? 'localhost') ?>" required>
            </div>
            <div class="form-group">
                <label><?= $t['db_port'] ?></label>
                <input type="number" name="db_port" id="db_port" value="<?= htmlspecialchars($saved['port'] ?? '3306') ?>" required>
            </div>
        </div>
        <div class="form-group">
            <label><?= $t['db_name'] ?></label>
            <input type="text" name="db_name" value="<?= htmlspecialchars($saved['database'] ?? 'freecms') ?>" required>
        </div>
        <div class="form-group">
            <label><?= $t['db_user'] ?></label>
            <input type="text" name="db_user" id="db_user" value="<?= htmlspecialchars($saved['username'] ?? '') ?>" required>
        </div>
        <div class="form-group">
            <label><?= $t['db_pass'] ?></label>
            <input type="password" name="db_pass" id="db_pass" value="">
        </div>
        <div id="conn-result"></div>
        <div class="nav-row">
            <a href="?step=2" class="btn btn-secondary"><?= $t['back'] ?></a>
            <button type="button" class="btn btn-secondary btn-sm" onclick="testConn()"><?= $t['test_conn'] ?></button>
            <button type="submit" class="btn btn-primary"><?= $t['next'] ?></button>
        </div>
    </form>

    <?php elseif ($step === 4): ?>
    <h2><i class="fas fa-cog"></i> <?= $t['step4'] ?></h2>
    <?php if (!empty($errors)): ?>
        <?php foreach ($errors as $e): ?>
            <div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($e) ?></div>
        <?php endforeach; ?>
    <?php endif; ?>
    <?php $savedSite = $_SESSION['install_site'] ?? []; $savedAdm = $_SESSION['install_admin'] ?? []; ?>
    <form method="POST" action="?step=4">
        <div class="two-col">
            <div class="form-group">
                <label><?= $t['site_name'] ?></label>
                <input type="text" name="site_name" value="<?= htmlspecialchars($savedSite['site_name'] ?? 'FreeCMS') ?>" required>
            </div>
            <div class="form-group">
                <label><?= $t['app_env'] ?></label>
                <select name="app_env">
                    <option value="production" <?= ($savedSite['app_env']??'production')==='production'?'selected':'' ?>>Production</option>
                    <option value="development" <?= ($savedSite['app_env']??'')==='development'?'selected':'' ?>>Development</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label><?= $t['site_url'] ?></label>
            <input type="url" name="site_url" value="<?= htmlspecialchars($savedSite['site_url'] ?? ('http://'.$_SERVER['HTTP_HOST'])) ?>" required>
        </div>
        <hr style="border:none;border-top:1px solid var(--border);margin:1.25rem 0;">
        <div class="form-group">
            <label><?= $t['admin_user'] ?></label>
            <input type="text" name="admin_user" value="<?= htmlspecialchars($savedAdm['username'] ?? 'admin') ?>" required>
        </div>
        <div class="form-group">
            <label><?= $t['admin_email'] ?></label>
            <input type="email" name="admin_email" value="<?= htmlspecialchars($savedAdm['email'] ?? '') ?>" required>
        </div>
        <div class="two-col">
            <div class="form-group">
                <label><?= $t['admin_pass'] ?></label>
                <input type="password" name="admin_pass" required minlength="8">
            </div>
            <div class="form-group">
                <label><?= $t['admin_pass2'] ?></label>
                <input type="password" name="admin_pass2" required minlength="8">
            </div>
        </div>
        <div class="nav-row">
            <a href="?step=3" class="btn btn-secondary"><?= $t['back'] ?></a>
            <button type="submit" class="btn btn-primary"><?= $t['next'] ?></button>
        </div>
    </form>

    <?php elseif ($step === 5): ?>
    <h2><i class="fas fa-rocket"></i> <?= $t['step5'] ?></h2>
    <?php if (!empty($installErrors)): ?>
        <?php foreach ($installErrors as $e): ?>
            <div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($t['error'].': '.$e) ?></div>
        <?php endforeach; ?>
        <a href="?step=4" class="btn btn-secondary"><?= $t['back'] ?></a>
    <?php else: ?>
        <form method="POST" action="?step=5" id="install-form">
            <p style="text-align:left; color:var(--text-muted); margin-bottom:1.5rem;">Ready to install FreeCMS? This will create the database and set up your admin account.</p>
            <div class="nav-row">
                <a href="?step=4" class="btn btn-secondary"><?= $t['back'] ?></a>
                <button type="submit" id="install-btn" class="btn btn-primary">
                    <i class="fas fa-rocket"></i> <?= $t['install_btn'] ?>
                </button>
            </div>
        </form>
    <?php endif; ?>

    <?php elseif ($step === 99): ?>
    <div class="success-icon">🎉</div>
    <div class="success-title"><?= $t['success'] ?></div>
    <div class="success-msg"><?= $t['success_msg'] ?></div>
    <div class="btn-row">
        <a href="/" class="btn btn-secondary"><i class="fas fa-home"></i> <?= $t['go_site'] ?></a>
        <a href="/login" class="btn btn-primary"><i class="fas fa-sign-in-alt"></i> <?= $t['go_login'] ?></a>
    </div>
    <?php endif; ?>

    </div>
</div>

<script>
function testConn() {
    const res = document.getElementById('conn-result');
    res.innerHTML = '<div class="alert" style="background:rgba(99,102,241,.1);border:1px solid rgba(99,102,241,.2);"><i class="fas fa-spinner fa-spin"></i> Testing...</div>';
    const f = document.getElementById('db-form');
    const data = new FormData(f);
    fetch('?step=3&action=test_db', { method: 'POST', body: data })
        .then(r => r.json())
        .then(d => {
            res.innerHTML = `<div class="alert ${d.ok?'alert-success':'alert-error'}"><i class="fas ${d.ok?'fa-check-circle':'fa-times-circle'}"></i> ${d.msg}</div>`;
        })
        .catch(() => { res.innerHTML = '<div class="alert alert-error">Request failed</div>'; });
}
const installBtn = document.getElementById('install-btn');
if (installBtn) {
    document.getElementById('install-form').addEventListener('submit', () => {
        installBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Installing...';
        installBtn.disabled = true;
    });
}
</script>
</body>
</html>
