<?php
/**
 * MTEngine Professional Installer
 *
 * Entry point: /install/  (primary installation wizard)
 *
 * Steps:
 * 1) Language
 * 2) Requirements
 * 3) Database
 * 4) Import SQL
 * 5) Create Admin
 * 6) Activation (Required)
 * 7) Finish
 */

require_once __DIR__ . '/../core/system/Env.php';
require_once __DIR__ . '/../core/system/InstallerGuard.php';
\Core\System\Env::bootstrap(realpath(__DIR__ . '/..'));
ini_set('display_errors', \Core\System\Env::isDebug() ? '1' : '0');
ini_set('display_startup_errors', '0');
error_reporting(E_ALL);

// Read requested step early
$requestedStep = (int)($_GET['step'] ?? 1);
if ($requestedStep < 1) $requestedStep = 1;
if ($requestedStep > 7) $requestedStep = 7;

// Allow final success page after installation without jumping early
$allowFinishedStep = ($requestedStep === 7 && \Core\System\InstallerGuard::isInstalled());

if (!empty($_GET['blocked'])) {
    // License suspended page — always allowed, handled below
} elseif (!$allowFinishedStep && !\Core\System\InstallerGuard::canRunInstaller()) {
    http_response_code(404);
    exit('Installer is disabled.');
}

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/* -------------------------------------------------------
   Paths
-------------------------------------------------------- */
define('INSTALL_PATH', __DIR__);
define('ROOT_PATH', realpath(__DIR__ . '/..'));
define('STORAGE_PATH', ROOT_PATH . '/storage');
define('LOCK_FILE', STORAGE_PATH . '/installed.lock');

/* -------------------------------------------------------
   Prevent re-install (skip for step=7 finish page)
-------------------------------------------------------- */
if (file_exists(LOCK_FILE) && $requestedStep !== 7) {
    http_response_code(404);
    exit('Installer is disabled.');
}


/* -------------------------------------------------------
   Autoloader for Installer classes (Fix: Class not found)
-------------------------------------------------------- */
spl_autoload_register(function ($class) {
    $prefix = 'Installer\\';
    $base_dir = INSTALL_PATH . '/core/';

    if (strpos($class, $prefix) !== 0) {
        return;
    }
    $relative_class = substr($class, strlen($prefix));
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

    if (file_exists($file)) {
        require_once $file;
    }
});

/* -------------------------------------------------------
   Safety requires (extra guarantee)
-------------------------------------------------------- */
if (!class_exists('\\Installer\\Installer')) {
    $f = INSTALL_PATH . '/core/Installer.php';
    if (file_exists($f)) require_once $f;
}
if (!class_exists('\\Installer\\SqlImporter')) {
    $f = INSTALL_PATH . '/core/SqlImporter.php';
    if (file_exists($f)) require_once $f;
}
if (!class_exists('\\Installer\\EnvWriter')) {
    $f = INSTALL_PATH . '/core/EnvWriter.php';
    if (file_exists($f)) require_once $f;
}

/* -------------------------------------------------------
   Helpers (Translations, DB helper etc.)
-------------------------------------------------------- */
$helpersPath = ROOT_PATH . '/core/app/Helpers/';
if (is_dir($helpersPath)) {
    foreach (glob($helpersPath . '*.php') as $file) {
        require_once $file;
    }
}

/* Load core systems used in activation + language */
require_once ROOT_PATH . '/core/system/Csrf.php';
require_once ROOT_PATH . '/core/system/Language.php';
require_once ROOT_PATH . '/core/system/License/Fingerprint.php';
require_once ROOT_PATH . '/core/system/License/LicenseClient.php';
require_once ROOT_PATH . '/core/system/License/LicenseStorage.php';

use Core\System\Csrf;
use Core\System\Language;
use Core\System\License\LicenseClient;
use Core\System\License\LicenseStorage;

use Installer\Installer;
use Installer\SqlImporter;
use Installer\EnvWriter;

/* -------------------------------------------------------
   Base URLs
-------------------------------------------------------- */
$base = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
if ($base === '' || $base === '.') $base = '';
$home = preg_replace('#/install$#', '', $base);
if ($home === '' || $home === '.') $home = '';

/* -------------------------------------------------------
   Step
-------------------------------------------------------- */
$step = (int)($_GET['step'] ?? 1);
if ($step < 1) $step = 1;
if ($step > 7) $step = 7;

/* -------------------------------------------------------
   Install session namespace
-------------------------------------------------------- */
if (!isset($_SESSION['install'])) {
    $_SESSION['install'] = [];
}

/* -------------------------------------------------------
   Language selection
-------------------------------------------------------- */
if ($step === 1 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::check();
    $lang = $_POST['lang'] ?? 'en';
    if ($lang !== 'ar' && $lang !== 'en') $lang = 'en';
    $_SESSION['install']['lang'] = $lang;

    // Optionally set app language for translation helper
    $_SESSION['lang'] = $lang;

    header("Location: index.php?step=2");
    exit;
}

$currentLang = $_SESSION['install']['lang'] ?? 'en';
$_SESSION['lang'] = $currentLang;

/* Determine RTL */
$isArabic = ($currentLang === 'ar');
$dir = $isArabic ? 'rtl' : 'ltr';

/* -------------------------------------------------------
   License suspended page (safe)
   - Only when app already installed (installed.lock exists)
   - Triggered by /install/index.php?blocked=1
   - No install steps executed
-------------------------------------------------------- */
if (file_exists(LOCK_FILE) && !empty($_GET['blocked'])) {
    $reasonKey = trim((string)($_GET['reason'] ?? ''));
    $reasonText = $reasonKey !== '' ? __("license.reason." . $reasonKey) : '';

    $retryUrl = '/';
    $logo = '/public/assets/img/logo.png';
    $recoveryError = '';

    $licenseKeyForRecovery = '';
    try {
        $pdo = db();
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ? LIMIT 1");
        $stmt->execute(['license_key']);
        $licenseKeyForRecovery = trim((string)$stmt->fetchColumn());
    } catch (Throwable $e) {
        $licenseKeyForRecovery = '';
    }

    if ($licenseKeyForRecovery === '') {
        $cached = LicenseStorage::get();
        if (is_array($cached)) {
            $licenseKeyForRecovery = trim((string)($cached['license_key'] ?? ''));
        }
    }

    if ($licenseKeyForRecovery !== '') {
        try {
            $client = new LicenseClient();
            $host = trim((string)($_SERVER['HTTP_HOST'] ?? ''));
            $fp = \Core\System\License\Fingerprint::generate();
            $res = $client->verify($licenseKeyForRecovery);

            if (!is_array($res) || (($res['status'] ?? '') === '' && ($res['action'] ?? '') === '')) {
                $res = $client->ping($licenseKeyForRecovery, $host, $fp);
            }

            if (is_array($res) && ($res['status'] ?? '') === 'active' && ($res['action'] ?? '') !== 'block') {
                LicenseStorage::save([
                    'license_key'     => $licenseKeyForRecovery,
                    'status'          => 'active',
                    'action'          => (string)($res['action'] ?? 'allow'),
                    'type'            => $res['type'] ?? null,
                    'type_original'   => $res['type_original'] ?? null,
                    'expires'         => $res['expires'] ?? null,
                    'domain_bound'    => $res['domain_bound'] ?? null,
                    'max_domains'     => (int)($res['max_domains'] ?? 0),
                    'domains_used'    => (int)($res['domains_used'] ?? 0),
                    'message'         => (string)($res['message'] ?? ''),
                    'checked_at'      => time(),
                    'last_ok_at'      => time(),
                    'ping_at'         => time(),
                    'ping_last_ok_at' => time(),
                    'ttl'             => 3600,
                    'failures'        => 0,
                ]);

                header('Location: ' . ($home === '' ? '/' : $home . '/'), true, 302);
                exit;
            }

            if (isset($_GET['retry_unlock'])) {
                $recoveryError = trim((string)($res['message'] ?? ''));
                if ($recoveryError === '') {
                    $recoveryError = __('license.suspended_subtitle');
                }
            }
        } catch (Throwable $e) {
            if (isset($_GET['retry_unlock'])) {
                $recoveryError = __('install.server_unreachable', 'Server unreachable. Please try again.');
            }
        }
    } elseif (isset($_GET['retry_unlock'])) {
        $recoveryError = __('install.license_required', 'License key is required.');
    }

    $recheckUrl = 'index.php?blocked=1';
    if ($reasonKey !== '') {
        $recheckUrl .= '&reason=' . rawurlencode($reasonKey);
    }
    $recheckUrl .= '&retry_unlock=1';

    ?><!doctype html>
    <html lang="<?= e($currentLang) ?>" dir="<?= e($dir) ?>" data-bs-theme="light">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title><?= e(__('license.suspended_title')) ?></title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
        <style>
            body{background:#f4f6fb !important;}
            .card{border:0;box-shadow:0 10px 35px rgba(0,0,0,.08);border-radius:18px;background:#ffffff !important;}
            .btn{border-radius:12px;}
        </style>
    </head>
    <body class="d-flex align-items-center" style="min-height:100vh;">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8 col-lg-6">
                <div class="card">
                    <div class="card-body p-4 p-md-5">
                        <div class="text-center mb-3">
                            <img src="<?= e($logo) ?>" alt="Logo" style="max-height:56px;" onerror="this.style.display='none'">
                        </div>

                        <h1 class="h4 fw-bold text-center mb-2"><?= e(__('license.suspended_title')) ?></h1>
                        <p class="text-muted text-center mb-4"><?= e(__('license.suspended_subtitle')) ?></p>

                        <?php if ($reasonText !== '' && $reasonText !== ('license.reason.' . $reasonKey)): ?>
                            <div class="alert alert-warning">
                                <strong><?= e(__('license.reason_label')) ?>:</strong>
                                <?= e($reasonText) ?>
                            </div>
                        <?php endif; ?>

                        <?php if ($recoveryError !== ''): ?>
                            <div class="alert alert-danger"><?= e($recoveryError) ?></div>
                        <?php endif; ?>

                        <div class="d-grid gap-2">
                            <a class="btn btn-primary btn-lg" href="<?= e($recheckUrl) ?>">إعادة التحقق وتشغيل الموقع</a>
                            <a class="btn btn-outline-secondary" href="<?= e($retryUrl) ?>"><?= e(__('license.retry')) ?></a>
                            <a class="btn btn-outline-secondary" href="mailto:support@ar-script.com"><?= e(__('license.contact_support')) ?></a>
                        </div>

                        <div class="small text-muted mt-4 text-center"><?= e(__('license.suspended_footer')) ?></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </body>
    </html><?php
    exit;
}

/* -------------------------------------------------------
   Block finishing without activation
-------------------------------------------------------- */
if ($step === 7 && empty($_SESSION['install']['activation_done'])) {
    header("Location: index.php?step=6");
    exit;
}

/* -------------------------------------------------------
   Utility: Requirements check
-------------------------------------------------------- */
function requirementsReport(): array
{
    $phpOk = version_compare(PHP_VERSION, '8.1.0', '>=');

    $ext = [
        'pdo' => extension_loaded('pdo'),
        'pdo_mysql' => extension_loaded('pdo_mysql'),
        'mbstring' => extension_loaded('mbstring'),
        'json' => extension_loaded('json'),
        'openssl' => extension_loaded('openssl'),
        'curl' => extension_loaded('curl'),
    ];

    $storageWritable = is_dir(STORAGE_PATH) && is_writable(STORAGE_PATH);

    return [
        'php_version' => PHP_VERSION,
        'php_ok' => $phpOk,
        'extensions' => $ext,
        'storage_writable' => $storageWritable,
    ];
}

/* -------------------------------------------------------
   Step handlers
-------------------------------------------------------- */
$errors = [];
$success = '';

/* STEP 3: Database save + test */
if ($step === 3 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::check();
    // Basic validation
    $db_host = trim((string)($_POST['db_host'] ?? 'localhost'));
    $db_port = trim((string)($_POST['db_port'] ?? '3306'));
    $db_name = trim((string)($_POST['db_name'] ?? ''));
    $db_user = trim((string)($_POST['db_user'] ?? ''));
    $db_pass = (string)($_POST['db_pass'] ?? '');

    if ($db_name === '' || $db_user === '') {
        $errors[] = $currentLang === 'ar' ? 'الرجاء إدخال اسم قاعدة البيانات واسم المستخدم.' : 'Please enter DB name and DB user.';
    } else {
        // Test connection
        try {
            // Connect without selecting a database first
            $pdo = new PDO(
                "mysql:host={$db_host};port={$db_port};charset=utf8mb4",
                $db_user,
                $db_pass,
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                ]
            );

            // Attempt to create the database — may fail on shared hosting where
            // the DB must be pre-created via cPanel. That is fine: we verify
            // access below and proceed regardless.
            try {
                $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$db_name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");
            } catch (Throwable $e) {
                // CREATE DATABASE privilege not granted (common on shared hosting).
                // The database must already exist — we will verify access next.
            }

            // Verify we can actually select and use the database
            $pdo->exec("USE `{$db_name}`");

            $_SESSION['install']['db'] = [
                'host' => $db_host,
                'port' => $db_port,
                'name' => $db_name,
                'user' => $db_user,
                'pass' => $db_pass,
            ];

            // Write .env
            try {
                $env = new EnvWriter(ROOT_PATH);
                $env->write([
                    'APP_LANG' => $currentLang,
                    'DB_HOST'  => $db_host,
                    'DB_PORT'  => $db_port,
                    'DB_NAME'  => $db_name,
                    'DB_USER'  => $db_user,
                    'DB_PASS'  => $db_pass,
                ]);
            } catch (Throwable $e) {
                $errors[] = "ENV write failed: " . $e->getMessage();
            }

            header("Location: index.php?step=4");
            exit;
        } catch (Throwable $e) {
            $errors[] = ($currentLang === 'ar' ? 'فشل الاتصال بقاعدة البيانات: ' : 'DB connection failed: ') . $e->getMessage();
        }
    }
}

/* STEP 4: Import SQL */
if ($step === 4 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (empty($_SESSION['install']['db'])) {
        header("Location: index.php?step=3");
        exit;
    }

    $sqlPath = ROOT_PATH . '/arscript_A.sql';
    if (!file_exists($sqlPath)) {
        // If SQL file not at root, try install folder
        $sqlPath = INSTALL_PATH . '/arscript_A.sql';
    }

    if (!file_exists($sqlPath)) {
        $errors[] = $currentLang === 'ar' ? 'ملف SQL غير موجود: arscript_A.sql' : 'SQL file not found: arscript_A.sql';
    } else {
        $db = $_SESSION['install']['db'];
        try {
            $pdo = new PDO(
                "mysql:host={$db['host']};port={$db['port']};dbname={$db['name']};charset=utf8mb4",
                $db['user'],
                $db['pass'],
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false,
                ]
            );

            $importer = new SqlImporter($pdo);
            $importer->importFromFile($sqlPath);

            $_SESSION['install']['db_imported'] = true;

            header("Location: index.php?step=5");
            exit;
        } catch (Throwable $e) {
            $errors[] = ($currentLang === 'ar' ? 'فشل استيراد قاعدة البيانات: ' : 'SQL import failed: ') . $e->getMessage();
        }
    }
}

/* STEP 5: Create Admin */
if ($step === 5 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::check();
    if (empty($_SESSION['install']['db_imported'])) {
        header("Location: index.php?step=4");
        exit;
    }

    $admin_user = trim((string)($_POST['admin_user'] ?? ''));
    $admin_pass = (string)($_POST['admin_pass'] ?? '');
    $admin_email = trim((string)($_POST['admin_email'] ?? ''));

    if ($admin_user === '' || $admin_pass === '') {
        $errors[] = $currentLang === 'ar' ? 'الرجاء إدخال اسم المستخدم وكلمة المرور.' : 'Please enter username and password.';
    } else {
        $db = $_SESSION['install']['db'];

        try {
            $pdo = new PDO(
                "mysql:host={$db['host']};port={$db['port']};dbname={$db['name']};charset=utf8mb4",
                $db['user'],
                $db['pass'],
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                ]
            );

            // Try insert/update in admins table
            $hash = password_hash($admin_pass, PASSWORD_DEFAULT);

            // Check if admins table exists
            $check = $pdo->query("SHOW TABLES LIKE 'admins'")->fetchColumn();
            if (!$check) {
                throw new Exception("admins table not found.");
            }

            // If first admin exists, update it; else insert
            $existingId = $pdo->query("SELECT id FROM admins ORDER BY id ASC LIMIT 1")->fetchColumn();

            if ($existingId) {
                $stmt = $pdo->prepare("UPDATE admins SET username = ?, password = ?, email = ? WHERE id = ? LIMIT 1");
                $stmt->execute([$admin_user, $hash, ($admin_email ?: null), $existingId]);
            } else {
                $stmt = $pdo->prepare("INSERT INTO admins (username, password, email) VALUES (?, ?, ?)");
                $stmt->execute([$admin_user, $hash, ($admin_email ?: null)]);
            }

            $_SESSION['install']['admin_done'] = true;

            header("Location: index.php?step=6");
            exit;
        } catch (Throwable $e) {
            $errors[] = ($currentLang === 'ar' ? 'فشل إنشاء الأدمن: ' : 'Admin creation failed: ') . $e->getMessage();
        }
    }
}

/* STEP 6: Activation (Required) */
if ($step === 6 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::check();
    Csrf::check();

    $licenseKey = trim((string)($_POST['license_key'] ?? ''));

    if ($licenseKey === '') {
        $errors[] = $currentLang === 'ar' ? 'مفتاح التفعيل مطلوب ولا يمكن إكمال التثبيت بدونه.' : 'License key is required.';
    } else {
        try {
            $client = new LicenseClient();
            $res = $client->verify($licenseKey);

            if (($res['status'] ?? '') !== 'active' || ($res['action'] ?? '') === 'block') {
                $msg = (string)($res['message'] ?? '');
                if ($msg === 'invalid_signature') {
                    $errors[] = $currentLang === 'ar'
                        ? 'فشل التحقق الأمني، يرجى التواصل مع الدعم.'
                        : 'Security validation failed. Please contact support.';
                } elseif ($msg !== '') {
                    $errors[] = $msg;
                } else {
                    $errors[] = $currentLang === 'ar' ? 'فشل التفعيل.' : 'Activation failed.';
                }
            } else {
                if (!empty($_SESSION['install']['db'])) {
                    $db = $_SESSION['install']['db'];
                    try {
                        $pdo = new PDO(
                            "mysql:host={$db['host']};port={$db['port']};dbname={$db['name']};charset=utf8mb4",
                            $db['user'],
                            $db['pass'],
                            [
                                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                            ]
                        );

                        $stmt = $pdo->prepare("SELECT id FROM settings WHERE setting_key = ? LIMIT 1");
                        $stmt->execute(['license_key']);
                        $exists = $stmt->fetchColumn();

                        if ($exists) {
                            $upd = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = ? LIMIT 1");
                            $upd->execute([$licenseKey, 'license_key']);
                        } else {
                            $ins = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?)");
                            $ins->execute(['license_key', $licenseKey]);
                        }
                    } catch (Throwable $e) {
                    }
                }

                LicenseStorage::save([
                    'license_key'   => $licenseKey,
                    'status'        => 'active',
                    'type'          => $res['type'] ?? null,
                    'expires'       => $res['expires'] ?? null,
                    'domain_bound'  => $res['domain_bound'] ?? null,
                    'max_domains'   => (int)($res['max_domains'] ?? 0),
                    'domains_used'  => (int)($res['domains_used'] ?? 0),
                    'checked_at'    => time(),
                    'last_ok_at'    => time(),
                    'ttl'           => 3600,
                    'failures'      => 0,
                ]);

                $_SESSION['install']['activation_done'] = true;
                $_SESSION['install']['license_key'] = $licenseKey;

                if (!is_dir(STORAGE_PATH)) {
                    @mkdir(STORAGE_PATH, 0755, true);
                }
                @file_put_contents(LOCK_FILE, 'installed=' . time());

                $cachePages = STORAGE_PATH . '/cache/pages';
                if (is_dir($cachePages)) {
                    $it = new RecursiveDirectoryIterator($cachePages, RecursiveDirectoryIterator::SKIP_DOTS);
                    $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);

                    foreach ($files as $file) {
                        if ($file->isDir()) {
                            @rmdir($file->getRealPath());
                        } else {
                            @unlink($file->getRealPath());
                        }
                    }

                    @rmdir($cachePages);
                }

                // NOTE: install/.htaccess is written at step=7 display time
                // (after the redirect) to avoid blocking access to step=7 itself.

                header("Location: index.php?step=7");
                exit;
            }
        } catch (Throwable $e) {
            $errors[] = $currentLang === 'ar'
                ? 'تعذر الاتصال بسيرفر التفعيل، حاول لاحقًا.'
                : 'Activation server unreachable. Please try again.';
        }
    }
}

/* -------------------------------------------------------
   HTML Helpers
-------------------------------------------------------- */
function h($s): string {
    return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}

function stepTitle(int $step, string $lang): string {
    $titlesAr = [
        1 => 'اختيار اللغة',
        2 => 'فحص المتطلبات',
        3 => 'إعداد قاعدة البيانات',
        4 => 'استيراد قاعدة البيانات',
        5 => 'إنشاء حساب الأدمن',
        6 => 'تفعيل المنتج',
        7 => 'اكتمال التثبيت',
    ];
    $titlesEn = [
        1 => 'Language',
        2 => 'Requirements',
        3 => 'Database',
        4 => 'Import SQL',
        5 => 'Create Admin',
        6 => 'Activation',
        7 => 'Finish',
    ];
    return ($lang === 'ar') ? ($titlesAr[$step] ?? '') : ($titlesEn[$step] ?? '');
}

?>
<?php show_installer_ui: ?>
<!doctype html>
<html lang="<?= $isArabic ? 'ar' : 'en' ?>" dir="<?= h($dir) ?>" data-bs-theme="light">
<head>
    <meta charset="utf-8">
    <title><?= htmlspecialchars(__('installer.page_title', 'Installer'), ENT_QUOTES, 'UTF-8') ?> - Step <?= (int)$step ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap 5 -->
    <!-- NOTE: The site theme CSS (style-generated.css) is intentionally NOT loaded here.
         Loading it caused the installer UI to inherit the storefront dark theme,
         making inputs unreadable and the page appear dimmed. -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

    <?php if ($isArabic): ?>
        <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap" rel="stylesheet">
        <style>
            body { font-family: "Cairo", sans-serif; }
        </style>
    <?php endif; ?>

    <style>
        /* Hardcoded colours — never use CSS vars here; the storefront theme
           defines --light as a dark hex and --dark as a light hex, which
           would invert the installer palette if those vars are cached in the
           browser from a previous visit to the storefront. */
        body{
            background: #f5f6f8 !important;
            color: #16161d !important;
        }
        .install-wrap{
            max-width: 980px;
            margin: 30px auto;
            padding: 0 12px;
        }
        .step-pill{
            font-size: 12px;
            padding: 6px 10px;
            border-radius: 999px;
            background: rgba(0,0,0,.06);
        }
        .progress{
            height: 10px;
            border-radius: 999px;
        }
        .progress-bar{
            border-radius: 999px;
        }
        .card{
            border-radius: 14px;
            background: #ffffff !important;
            color: #16161d !important;
        }
        .btn-lg{
            border-radius: 12px;
            padding: 12px 18px;
        }
        .form-control-lg{
            border-radius: 12px;
        }
        /* Force light theme on inputs — prevents dark theme CSS vars from
           making text invisible (white-on-white or dark-on-dark). */
        .form-control{
            background-color: #ffffff !important;
            color: #212529 !important;
            border-color: #ced4da !important;
        }
        .form-control:focus{
            background-color: #ffffff !important;
            color: #212529 !important;
        }
        .form-label{
            color: #212529 !important;
        }
    </style>
</head>
<body>

<div class="install-wrap">

    <div class="d-flex align-items-center justify-content-between mb-3">
        <div>
            <div class="step-pill mb-2">
                <?= $isArabic ? 'الخطوة' : 'Step' ?> <?= (int)$step ?> / 7
            </div>
            <h3 class="mb-0"><?= h(stepTitle($step, $currentLang)) ?></h3>
            <div class="text-muted"><?= $isArabic ? 'معالج تثبيت احترافي' : 'Professional Setup Wizard' ?></div>
        </div>
        <div class="text-muted small">
            <?= $isArabic ? 'الإصدار' : 'Version' ?>: 1.0
        </div>
    </div>

    <?php
    $percent = (int)round(($step / 7) * 100);
    ?>
    <div class="progress mb-4">
        <div class="progress-bar" role="progressbar" style="width: <?= $percent ?>%"></div>
    </div>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <ul class="mb-0">
                <?php foreach ($errors as $e): ?>
                    <li><?= h($e) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if ($step === 1): ?>
        <!-- Step 1: Language -->
        <div class="card shadow-sm border-0">
            <div class="card-body p-4">
                <h4 class="mb-2"><?= htmlspecialchars(__('installer.choose_language', 'Choose Language'), ENT_QUOTES, 'UTF-8') ?></h4>
                <p class="text-muted mb-4"><?= htmlspecialchars(__('installer.choose_language_desc', 'Select installer interface language.'), ENT_QUOTES, 'UTF-8') ?></p>

                <form method="post">
                    <div class="d-flex gap-3 flex-wrap">
                        <button class="btn btn-primary btn-lg" name="lang" value="ar" type="submit">
                            العربية
                        </button>
                        <button class="btn btn-outline-secondary btn-lg" name="lang" value="en" type="submit">
                            English
                        </button>
                    </div>
                </form>
            </div>
        </div>

    <?php elseif ($step === 2): ?>
        <!-- Step 2: Requirements -->
        <?php $rep = requirementsReport(); ?>
        <div class="card shadow-sm border-0">
            <div class="card-body p-4">
                <h4 class="mb-3"><?= $isArabic ? 'فحص المتطلبات' : 'Requirements Check' ?></h4>

                <div class="row g-3">
                    <div class="col-md-6">
                        <div class="p-3 rounded border bg-white">
                            <div class="fw-bold mb-1"><?= $isArabic ? 'إصدار PHP' : 'PHP Version' ?></div>
                            <div class="<?= $rep['php_ok'] ? 'text-success' : 'text-danger' ?>">
                                <?= h($rep['php_version']) ?> <?= $rep['php_ok'] ? '✓' : '✗' ?>
                            </div>
                            <div class="text-muted small">
                                <?= $isArabic ? 'مطلوب 8.1 أو أعلى' : 'Required 8.1 or higher' ?>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="p-3 rounded border bg-white">
                            <div class="fw-bold mb-1"><?= $isArabic ? 'صلاحية الكتابة' : 'Writable Storage' ?></div>
                            <div class="<?= $rep['storage_writable'] ? 'text-success' : 'text-danger' ?>">
                                <?= $rep['storage_writable'] ? '✓' : '✗' ?>
                            </div>
                            <div class="text-muted small">
                                <?= $isArabic ? 'المجلد: storage/' : 'Folder: storage/' ?>
                            </div>
                        </div>
                    </div>

                    <div class="col-12">
                        <div class="p-3 rounded border bg-white">
                            <div class="fw-bold mb-2"><?= $isArabic ? 'الإضافات المطلوبة' : 'Required Extensions' ?></div>

                            <div class="row g-2">
                                <?php foreach ($rep['extensions'] as $k => $ok): ?>
                                    <div class="col-md-4">
                                        <div class="d-flex align-items-center justify-content-between border rounded p-2 bg-light">
                                            <span><?= h($k) ?></span>
                                            <span class="<?= $ok ? 'text-success' : 'text-danger' ?> fw-bold">
                                                <?= $ok ? '✓' : '✗' ?>
                                            </span>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>

                        </div>
                    </div>
                </div>

                <div class="mt-4 d-flex gap-2">
                    <a class="btn btn-primary btn-lg"
                       href="index.php?step=3"
                       <?= (!$rep['php_ok'] || !$rep['storage_writable']) ? 'disabled' : '' ?>>
                        <?= $isArabic ? 'التالي' : 'Next' ?>
                    </a>
                    <a class="btn btn-outline-secondary btn-lg" href="index.php?step=2">
                        <?= $isArabic ? 'إعادة فحص' : 'Recheck' ?>
                    </a>
                </div>

                <?php if (!$rep['php_ok'] || !$rep['storage_writable']): ?>
                    <div class="alert alert-warning mt-3">
                        <?= $isArabic
                            ? 'لا يمكنك المتابعة قبل حل المتطلبات.'
                            : 'You cannot continue until requirements are met.' ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

    <?php elseif ($step === 3): ?>
        <!-- Step 3: Database -->
        <?php
        $dbSaved = $_SESSION['install']['db'] ?? [];
        ?>
        <div class="card shadow-sm border-0">
            <div class="card-body p-4">
                <h4 class="mb-2"><?= $isArabic ? 'إعداد قاعدة البيانات' : 'Database Setup' ?></h4>
                <p class="text-muted mb-4"><?= $isArabic ? 'أدخل بيانات الاتصال بقاعدة البيانات.' : 'Enter database credentials.' ?></p>

                <form method="post" class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label"><?= $isArabic ? 'DB Host' : 'DB Host' ?></label>
                        <input class="form-control form-control-lg" name="db_host" value="<?= h($dbSaved['host'] ?? 'localhost') ?>" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label"><?= $isArabic ? 'DB Port' : 'DB Port' ?></label>
                        <input class="form-control form-control-lg" name="db_port" value="<?= h($dbSaved['port'] ?? '3306') ?>" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label"><?= $isArabic ? 'اسم قاعدة البيانات' : 'Database Name' ?></label>
                        <input class="form-control form-control-lg" name="db_name" value="<?= h($dbSaved['name'] ?? '') ?>" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label"><?= $isArabic ? 'مستخدم قاعدة البيانات' : 'DB User' ?></label>
                        <input class="form-control form-control-lg" name="db_user" value="<?= h($dbSaved['user'] ?? '') ?>" required>
                    </div>
                    <div class="col-12">
                        <label class="form-label"><?= $isArabic ? 'كلمة المرور' : 'DB Password' ?></label>
                        <input type="password" class="form-control form-control-lg" name="db_pass" value="<?= h($dbSaved['pass'] ?? '') ?>">
                    </div>

                    <div class="col-12 d-flex gap-2 mt-2">
                        <button class="btn btn-primary btn-lg" type="submit">
                            <?= $isArabic ? 'حفظ واختبار' : 'Save & Test' ?>
                        </button>
                        <a class="btn btn-outline-secondary btn-lg" href="index.php?step=2">
                            <?= $isArabic ? 'رجوع' : 'Back' ?>
                        </a>
                    </div>
                </form>
            </div>
        </div>

    <?php elseif ($step === 4): ?>
        <!-- Step 4: Import SQL -->
        <div class="card shadow-sm border-0">
            <div class="card-body p-4">
                <h4 class="mb-2"><?= $isArabic ? 'استيراد قاعدة البيانات' : 'Import Database' ?></h4>
                <p class="text-muted mb-4">
                    <?= $isArabic
                        ? 'سيتم الآن إنشاء الجداول وإدخال البيانات الأساسية.'
                        : 'Tables and seed data will be imported now.' ?>
                </p>

                <form method="post">
                    <button class="btn btn-primary btn-lg" type="submit">
                        <?= $isArabic ? 'بدء الاستيراد' : 'Start Import' ?>
                    </button>
                    <a class="btn btn-outline-secondary btn-lg" href="index.php?step=3">
                        <?= $isArabic ? 'رجوع' : 'Back' ?>
                    </a>
                </form>

                <div class="alert alert-info mt-3">
                    <?= $isArabic ? 'تأكد من وجود ملف arscript_A.sql في جذر المشروع.' : 'Make sure arscript_A.sql exists in project root.' ?>
                </div>
            </div>
        </div>

    <?php elseif ($step === 5): ?>
        <!-- Step 5: Create Admin -->
        <div class="card shadow-sm border-0">
            <div class="card-body p-4">
                <h4 class="mb-2"><?= $isArabic ? 'إنشاء حساب الأدمن' : 'Create Admin Account' ?></h4>
                <p class="text-muted mb-4"><?= $isArabic ? 'أدخل بيانات المدير لحساب لوحة التحكم.' : 'Enter administrator credentials.' ?></p>

                <form method="post" class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label"><?= $isArabic ? 'اسم المستخدم' : 'Username' ?></label>
                        <input class="form-control form-control-lg" name="admin_user" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label"><?= $isArabic ? 'البريد الإلكتروني (اختياري)' : 'Email (optional)' ?></label>
                        <input class="form-control form-control-lg" name="admin_email" type="email">
                    </div>
                    <div class="col-12">
                        <label class="form-label"><?= $isArabic ? 'كلمة المرور' : 'Password' ?></label>
                        <input class="form-control form-control-lg" name="admin_pass" type="password" required>
                    </div>

                    <div class="col-12 d-flex gap-2 mt-2">
                        <button class="btn btn-primary btn-lg" type="submit">
                            <?= $isArabic ? 'إنشاء ومتابعة' : 'Create & Continue' ?>
                        </button>
                        <a class="btn btn-outline-secondary btn-lg" href="index.php?step=4">
                            <?= $isArabic ? 'رجوع' : 'Back' ?>
                        </a>
                    </div>
                </form>
            </div>
        </div>

    <?php elseif ($step === 6): ?>
        <!-- Step 6: Activation (Required) — all styles are inline to prevent any
             Bootstrap dark-mode or theme CSS from making the form look/behave disabled -->
        <div style="background:#ffffff;border-radius:14px;box-shadow:0 4px 20px rgba(0,0,0,.08);padding:2rem;">

            <h4 style="margin:0 0 .5rem;color:#111827;font-size:1.25rem;font-weight:700;">
                <?= $isArabic ? 'تفعيل المنتج' : 'Activate Product' ?>
            </h4>
            <p style="color:#6b7280;margin:0 0 1.5rem;font-size:.95rem;">
                <?= $isArabic
                    ? 'هذه الخطوة إلزامية ولا يمكن إكمال التثبيت بدون التفعيل.'
                    : 'This step is required. Installation cannot continue without activation.' ?>
            </p>

            <form method="post" id="activate-form">
                <?= Csrf::field() ?>

                <div style="margin-bottom:1.2rem;">
                    <label for="license_key_input" style="display:block;margin-bottom:.4rem;color:#374151;font-weight:600;font-size:.95rem;">
                        <?= $isArabic ? 'مفتاح التفعيل' : 'License Key' ?>
                    </label>
                    <input
                        type="text"
                        id="license_key_input"
                        name="license_key"
                        autocomplete="off"
                        placeholder="<?= $isArabic ? 'أدخل مفتاح الترخيص هنا' : 'Enter your license key here' ?>"
                        style="display:block;width:100%;box-sizing:border-box;padding:.75rem 1rem;font-size:1rem;line-height:1.5;color:#111827;background-color:#ffffff;border:2px solid #d1d5db;border-radius:10px;outline:none;font-family:inherit;-webkit-appearance:none;appearance:none;"
                        onfocus="this.style.borderColor='#3b82f6';"
                        onblur="this.style.borderColor='#d1d5db';"
                    >
                    <span id="lk-error" style="display:none;color:#dc2626;font-size:.875rem;margin-top:.35rem;"></span>
                </div>

                <div style="display:flex;gap:.75rem;flex-wrap:wrap;">
                    <button type="submit" style="background:#2563eb;color:#ffffff;border:none;border-radius:10px;padding:.75rem 1.5rem;font-size:1rem;font-weight:600;cursor:pointer;font-family:inherit;" onmouseover="this.style.background='#1d4ed8'" onmouseout="this.style.background='#2563eb'">
                        <?= $isArabic ? 'تفعيل وإكمال' : 'Activate & Finish' ?>
                    </button>
                    <a href="index.php?step=5" style="background:#f3f4f6;color:#374151;border:none;border-radius:10px;padding:.75rem 1.5rem;font-size:1rem;font-weight:600;text-decoration:none;display:inline-flex;align-items:center;">
                        <?= $isArabic ? 'رجوع' : 'Back' ?>
                    </a>
                </div>
            </form>
        </div>

        <script>
        document.getElementById('activate-form').addEventListener('submit', function(e) {
            var val = document.getElementById('license_key_input').value.trim();
            var err = document.getElementById('lk-error');
            if (val === '') {
                e.preventDefault();
                err.textContent = <?= json_encode($isArabic ? 'مفتاح التفعيل مطلوب.' : 'License key is required.') ?>;
                err.style.display = 'block';
                document.getElementById('license_key_input').style.borderColor = '#dc2626';
            } else {
                err.style.display = 'none';
            }
        });
        </script>

    <?php elseif ($step === 7): ?>
        <?php
        // Lock the installer — write/overwrite .htaccess with correct rules
        $ht = INSTALL_PATH . '/.htaccess';
        $htContent = implode("\n", [
            'RewriteEngine On',
            '# Allow license-suspended page',
            'RewriteCond %{QUERY_STRING} blocked=1 [NC]',
            'RewriteRule ^ - [L]',
            '# Allow blocked.php directly',
            'RewriteRule ^blocked\.php$ - [L]',
            '# Allow step=7 finish page',
            'RewriteCond %{QUERY_STRING} step=7 [NC]',
            'RewriteRule ^ - [L]',
            '# Block everything else after installation',
            'RewriteCond %{DOCUMENT_ROOT}/storage/installed.lock -f',
            'RewriteRule ^ - [F,L]',
        ]) . "\n";
        @file_put_contents($ht, $htContent);

        $siteUrl  = ($home === '' ? '' : $home) . '/';
        $adminUrl = ($home === '' ? '' : $home) . '/admin/';
        ?>
        <!-- Step 7: Professional Welcome Page -->
        <div class="card shadow border-0" style="border-radius:20px;overflow:hidden;">

            <!-- Green success banner -->
            <div style="background:linear-gradient(135deg,#10b981,#059669);padding:2.5rem 2rem;text-align:center;color:#fff;">
                <div style="width:80px;height:80px;background:rgba(255,255,255,.2);border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 1rem;font-size:2.5rem;">
                    ✅
                </div>
                <h2 style="font-weight:800;margin:0 0 .5rem;">
                    <?= $isArabic ? 'تم التثبيت بنجاح!' : 'Installation Complete!' ?>
                </h2>
                <p style="opacity:.85;margin:0;font-size:.95rem;">
                    <?= $isArabic
                        ? 'تم تثبيت وتفعيل متجرك بنجاح وهو جاهز للعمل'
                        : 'Your store has been installed and activated successfully.' ?>
                </p>
            </div>

            <div class="card-body p-4 p-md-5">

                <!-- Two action buttons -->
                <div class="row g-3 mb-4">
                    <div class="col-12 col-md-6">
                        <a href="<?= h($adminUrl) ?>"
                           target="_blank" rel="noopener"
                           class="btn btn-primary btn-lg w-100 py-3"
                           style="border-radius:14px;font-weight:700;font-size:1rem;">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor"
                                 class="<?= $isArabic ? 'ms-2' : 'me-2' ?>" viewBox="0 0 16 16">
                                <path d="M0 1.5A1.5 1.5 0 0 1 1.5 0h13A1.5 1.5 0 0 1 16 1.5V13a1.5 1.5 0 0 1-1.5 1.5H9v1h1.5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1 0-1H7v-1H1.5A1.5 1.5 0 0 1 0 13V1.5zM1.5 1a.5.5 0 0 0-.5.5V9h14V1.5a.5.5 0 0 0-.5-.5h-13zM1 10v3a.5.5 0 0 0 .5.5h13a.5.5 0 0 0 .5-.5v-3H1z"/>
                            </svg>
                            <?= $isArabic ? 'الدخول إلى لوحة التحكم' : 'Go to Admin Panel' ?>
                        </a>
                    </div>
                    <div class="col-12 col-md-6">
                        <a href="<?= h($siteUrl) ?>"
                           target="_blank" rel="noopener"
                           class="btn btn-outline-success btn-lg w-100 py-3"
                           style="border-radius:14px;font-weight:700;font-size:1rem;">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor"
                                 class="<?= $isArabic ? 'ms-2' : 'me-2' ?>" viewBox="0 0 16 16">
                                <path d="M0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8zm7.5-6.923c-.67.204-1.335.82-1.887 1.855-.143.268-.276.56-.395.872.705.157 1.472.257 2.282.287V1.077zM4.249 3.539c.142-.384.304-.744.481-1.078a6.7 6.7 0 0 1 .597-.933A7.01 7.01 0 0 0 3.051 3.05c.362.184.763.349 1.198.49zM3.509 7.5c.036-1.07.188-2.087.436-3.008a9.124 9.124 0 0 1-1.565-.667A6.964 6.964 0 0 0 1.018 7.5h2.49zm1.4-2.741a12.344 12.344 0 0 0-.4 2.741H7.5V5.091c-.91-.03-1.783-.145-2.591-.332zM8.5 5.09V7.5h2.99a12.342 12.342 0 0 0-.399-2.741c-.808.187-1.681.301-2.591.332zM4.51 8.5c.035.987.176 1.914.399 2.741A13.612 13.612 0 0 1 7.5 10.91V8.5H4.51zm3.99 0v2.409c.91.03 1.783.145 2.591.332.223-.827.364-1.754.4-2.741H8.5zm-3.282 3.696c.12.312.252.604.395.872.552 1.035 1.218 1.65 1.887 1.855V11.91c-.81.03-1.577.13-2.282.287zm.11.233c.007.058.014.117.024.175.19 1.152.46 2.058.755 2.557.133.221.267.38.396.499a8.001 8.001 0 0 1-2.15-1.028 9.358 9.358 0 0 0 .975-2.203zM9.75 11.99v2.166a8 8 0 0 1-2.5 0V11.99a13.5 13.5 0 0 0 2.5 0zM10.373 14.43c.296-.5.565-1.406.756-2.557.01-.058.017-.117.024-.175a9.36 9.36 0 0 0 .975 2.203 8.001 8.001 0 0 1-1.755.53zm.887-3.431a13.61 13.61 0 0 1 2.282-.287V11.91c-.81-.03-1.577-.13-2.282-.287zM11.49 8.5c-.036.987-.176 1.914-.4 2.741.808-.187 1.682-.301 2.591-.332V8.5h-2.99z"/>
                            </svg>
                            <?= $isArabic ? 'عرض الموقع' : 'Visit Website' ?>
                        </a>
                    </div>
                </div>

                <!-- Quick info cards -->
                <div class="row g-3 mb-4">
                    <div class="col-12 col-sm-4">
                        <div class="text-center p-3 rounded-3" style="background:#f0fdf4;border:1px solid #bbf7d0;">
                            <div style="font-size:1.5rem;margin-bottom:.4rem;">🔒</div>
                            <div class="small fw-semibold text-success">
                                <?= htmlspecialchars(__('installer.locked', 'Installer Locked'), ENT_QUOTES, 'UTF-8') ?>
                            </div>
                            <div class="small text-muted mt-1">
                                <?= htmlspecialchars(__('installer.access_disabled', 'Access disabled'), ENT_QUOTES, 'UTF-8') ?>
                            </div>
                        </div>
                    </div>
                    <div class="col-12 col-sm-4">
                        <div class="text-center p-3 rounded-3" style="background:#eff6ff;border:1px solid #bfdbfe;">
                            <div style="font-size:1.5rem;margin-bottom:.4rem;">✔️</div>
                            <div class="small fw-semibold text-primary">
                                <?= htmlspecialchars(__('installer.license_active', 'License Active'), ENT_QUOTES, 'UTF-8') ?>
                            </div>
                            <div class="small text-muted mt-1">
                                <?= htmlspecialchars(__('installer.license_valid', 'Valid license'), ENT_QUOTES, 'UTF-8') ?>
                            </div>
                        </div>
                    </div>
                    <div class="col-12 col-sm-4">
                        <div class="text-center p-3 rounded-3" style="background:#fefce8;border:1px solid #fde68a;">
                            <div style="font-size:1.5rem;margin-bottom:.4rem;">⚙️</div>
                            <div class="small fw-semibold text-warning">
                                <?= htmlspecialchars(__('installer.ready', 'Ready to Use'), ENT_QUOTES, 'UTF-8') ?>
                            </div>
                            <div class="small text-muted mt-1">
                                <?= htmlspecialchars(__('installer.start_setup', 'Start setting up'), ENT_QUOTES, 'UTF-8') ?>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="text-center small text-muted">
                    <?= $isArabic
                        ? 'لأي مساعدة تقنية تواصل مع فريق الدعم: support@ar-script.com'
                        : 'For technical support contact: support@ar-script.com' ?>
                </div>
            </div>
        </div>

    <?php endif; ?>

    <div class="text-center mt-4 text-muted small">
        © <?= date('Y') ?> AR-Script
    </div>

</div>

</body>
</html>
