<?php
$base_url = $this->base_url();
$current_step = isset($step) ? (int)$step : 1;
$steps = array(
    1 => array('Requirements', 'Server readiness'),
    2 => array('License', 'Purchase verification'),
    3 => array('Database', 'Connection and app config'),
    4 => array('Account', 'Admin and company setup'),
);

function installer_e($value)
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function installer_post($key, $default = '')
{
    return isset($_POST[$key]) ? installer_e($_POST[$key]) : installer_e($default);
}

function installer_requirement($label, $passed, $message)
{
    return array('label' => $label, 'passed' => (bool)$passed, 'message' => $message, 'required' => true);
}

function installer_optional_requirement($label, $passed, $message)
{
    return array('label' => $label, 'passed' => (bool)$passed, 'message' => $message, 'required' => false);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>Zisco ERP Installer</title>
    <link rel="stylesheet" href="../assets/plugins/select2/dist/css/select2.min.css">
    <style>
        :root {
            --bg: #f4f7fb;
            --panel: #ffffff;
            --text: #172033;
            --muted: #667085;
            --line: #d9e2ef;
            --primary: #0f766e;
            --primary-dark: #115e59;
            --danger: #b42318;
            --danger-bg: #fff1f0;
            --success: #067647;
            --success-bg: #ecfdf3;
            --soft: #eef6f5;
            --focus: rgba(15, 118, 110, .22);
        }

        * { box-sizing: border-box; }

        body {
            margin: 0;
            background: var(--bg);
            color: var(--text);
            font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif;
        }

        a { color: var(--primary); text-decoration: none; }
        a:hover { text-decoration: underline; }

        .shell {
            min-height: 100vh;
            padding: 28px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .installer {
            width: min(1120px, 100%);
            display: grid;
            grid-template-columns: 320px minmax(0, 1fr);
            background: var(--panel);
            border: 1px solid var(--line);
            border-radius: 18px;
            overflow: hidden;
            box-shadow: 0 24px 70px rgba(23, 32, 51, .12);
        }

        .side {
            background: #123c3a;
            color: #fff;
            padding: 34px 28px;
            display: flex;
            flex-direction: column;
            gap: 30px;
        }

        .brand-mark {
            width: 44px;
            height: 44px;
            border-radius: 10px;
            background: #f6c85f;
            color: #123c3a;
            display: grid;
            place-items: center;
            font-weight: 800;
            letter-spacing: .02em;
        }

        .side h1 {
            margin: 14px 0 8px;
            font-size: 28px;
            line-height: 1.1;
            letter-spacing: 0;
        }

        .side p {
            margin: 0;
            color: rgba(255, 255, 255, .76);
        }

        .steps {
            display: grid;
            gap: 12px;
            margin: 0;
            padding: 0;
            list-style: none;
        }

        .step {
            display: grid;
            grid-template-columns: 34px 1fr;
            gap: 12px;
            align-items: center;
            padding: 12px;
            border-radius: 12px;
            color: rgba(255, 255, 255, .72);
        }

        .step.is-active,
        .step.is-done {
            background: rgba(255, 255, 255, .10);
            color: #fff;
        }

        .step-number {
            width: 34px;
            height: 34px;
            border-radius: 9px;
            display: grid;
            place-items: center;
            background: rgba(255, 255, 255, .13);
            font-weight: 700;
        }

        .step.is-active .step-number,
        .step.is-done .step-number {
            background: #f6c85f;
            color: #123c3a;
        }

        .step-title {
            display: block;
            font-weight: 700;
            line-height: 1.2;
        }

        .step-subtitle {
            display: block;
            margin-top: 2px;
            color: rgba(255, 255, 255, .58);
            font-size: 12px;
        }

        .content {
            padding: 34px;
            min-width: 0;
        }

        .topline {
            display: flex;
            justify-content: space-between;
            gap: 20px;
            margin-bottom: 24px;
        }

        .topline h2 {
            margin: 0 0 6px;
            font-size: 24px;
            letter-spacing: 0;
        }

        .topline p {
            margin: 0;
            color: var(--muted);
        }

        .badge {
            align-self: flex-start;
            border: 1px solid var(--line);
            border-radius: 999px;
            padding: 7px 12px;
            color: var(--muted);
            font-weight: 700;
            white-space: nowrap;
            background: #fff;
        }

        .notice {
            border-radius: 12px;
            padding: 13px 15px;
            margin-bottom: 18px;
            border: 1px solid var(--line);
            background: #f8fafc;
        }

        .notice.success {
            color: var(--success);
            background: var(--success-bg);
            border-color: #abefc6;
        }

        .notice.danger {
            color: var(--danger);
            background: var(--danger-bg);
            border-color: #fecdca;
        }

        .requirements {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 12px;
        }

        .check-card {
            border: 1px solid var(--line);
            border-radius: 12px;
            padding: 14px;
            display: flex;
            gap: 12px;
            min-height: 92px;
            background: #fff;
        }

        .check-dot {
            width: 28px;
            height: 28px;
            flex: 0 0 28px;
            border-radius: 8px;
            display: grid;
            place-items: center;
            font-weight: 800;
        }

        .check-card.pass .check-dot {
            background: var(--success-bg);
            color: var(--success);
        }

        .check-card.fail .check-dot {
            background: var(--danger-bg);
            color: var(--danger);
        }

        .check-card strong {
            display: block;
            margin-bottom: 3px;
        }

        .check-card span {
            color: var(--muted);
            font-size: 13px;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 18px;
        }

        .field.full,
        .actions,
        details.full {
            grid-column: 1 / -1;
        }

        label {
            display: block;
            font-weight: 700;
            margin-bottom: 7px;
        }

        input,
        select,
        textarea {
            width: 100%;
            min-height: 44px;
            border: 1px solid var(--line);
            border-radius: 10px;
            padding: 10px 12px;
            color: var(--text);
            background: #fff;
            outline: none;
            transition: border-color .15s ease, box-shadow .15s ease;
        }

        textarea {
            min-height: 94px;
            resize: vertical;
        }

        input:focus,
        select:focus,
        textarea:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 4px var(--focus);
        }

        .hint {
            margin-top: 6px;
            color: var(--muted);
            font-size: 12px;
        }

        details {
            border: 1px solid var(--line);
            border-radius: 12px;
            padding: 14px;
            background: #fbfdff;
        }

        summary {
            cursor: pointer;
            font-weight: 800;
            color: var(--primary-dark);
        }

        .details-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 18px;
            margin-top: 16px;
        }

        .actions {
            display: flex;
            justify-content: flex-end;
            gap: 12px;
            margin-top: 6px;
        }

        .btn {
            border: 0;
            border-radius: 10px;
            min-height: 44px;
            padding: 11px 18px;
            font-weight: 800;
            cursor: pointer;
            background: var(--primary);
            color: #fff;
        }

        .btn:hover {
            background: var(--primary-dark);
        }

        .btn.secondary {
            color: var(--primary-dark);
            background: var(--soft);
        }

        .success-panel {
            border: 1px solid #abefc6;
            background: var(--success-bg);
            border-radius: 16px;
            padding: 26px;
        }

        .success-panel h3 {
            margin: 0 0 8px;
            font-size: 24px;
        }

        .success-panel p {
            color: #075e3f;
            margin: 0 0 18px;
        }

        .select2-container--default .select2-selection--single {
            border: 1px solid var(--line);
            border-radius: 10px;
            height: 44px;
        }

        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 42px;
            padding-left: 12px;
        }

        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 42px;
        }

        @media (max-width: 860px) {
            .shell { padding: 14px; align-items: flex-start; }
            .installer { grid-template-columns: 1fr; }
            .side { padding: 24px; }
            .steps { grid-template-columns: repeat(2, minmax(0, 1fr)); }
            .content { padding: 24px; }
            .requirements,
            .form-grid,
            .details-grid { grid-template-columns: 1fr; }
            .topline { flex-direction: column; }
        }
    </style>
</head>
<body>
<main class="shell">
    <section class="installer">
        <aside class="side">
            <div>
                <div class="brand-mark">ZE</div>
                <h1>Zisco ERP Setup</h1>
                <p>Install the application, verify the environment, and generate the app configuration from one guided flow.</p>
            </div>
            <ol class="steps">
                <?php foreach ($steps as $number => $item) {
                    $class = $number === $current_step ? 'is-active' : ($number < $current_step ? 'is-done' : '');
                    ?>
                    <li class="step <?php echo $class; ?>">
                        <span class="step-number"><?php echo $number; ?></span>
                        <span>
                            <span class="step-title"><?php echo installer_e($item[0]); ?></span>
                            <span class="step-subtitle"><?php echo installer_e($item[1]); ?></span>
                        </span>
                    </li>
                <?php } ?>
            </ol>
        </aside>

        <section class="content">
            <div class="topline">
                <div>
                    <h2><?php echo $current_step === 5 ? 'Installation Complete' : installer_e($steps[min($current_step, 4)][0]); ?></h2>
                    <p><?php echo $current_step === 5 ? 'Your application is ready to use.' : installer_e($steps[min($current_step, 4)][1]); ?></p>
                </div>
                <div class="badge">Step <?php echo min($current_step, 4); ?> of 4</div>
            </div>

            <?php if (!empty($debug)) { ?>
                <div class="notice success sql-debug-alert"><?php echo nl2br(installer_e($debug)); ?></div>
            <?php } ?>

            <?php if (!empty($bug_error)) { ?>
                <div class="notice danger"><?php echo nl2br(installer_e($bug_error)); ?></div>
            <?php } ?>

            <?php if ($current_step === 1) {
                $database_file = "../application/config/database.php";
                $app_config_file = "../application/config/app-config.php";
                $config_dir = "../application/config";
                $htaccess_file = "../.htaccess";
                $requirements = array(
                    installer_requirement('PHP version', version_compare(PHP_VERSION, '8.4', '>='), 'Running PHP ' . PHP_VERSION . '. PHP 8.4 or newer is required.'),
                    installer_requirement('MySQLi extension', extension_loaded('mysqli'), 'Required for database connection checks and installation.'),
                    installer_requirement('IMAP extension', extension_loaded('imap'), 'Required for mailbox features.'),
                    installer_requirement('MBString extension', extension_loaded('mbstring'), 'Required for multi-byte text handling.'),
                    installer_requirement('ZIP extension', extension_loaded('zip'), 'Required for archive exports and package handling.'),
                    installer_requirement('GD extension', extension_loaded('gd'), 'Required for image processing.'),
                    installer_requirement('PDO extension', extension_loaded('pdo'), 'Required by several framework components.'),
                    installer_requirement('CURL extension', extension_loaded('curl'), 'Required for purchase verification and remote updates.'),
                    installer_requirement('OpenSSL extension', extension_loaded('openssl'), 'Required for secure transport and encryption helpers.'),
                    installer_requirement('allow_url_fopen', in_array(ini_get('allow_url_fopen'), array('1', 'On', 'on'), true), 'Required by legacy remote checks.'),
                    installer_requirement('Config directory', is_writable($config_dir), 'application/config must be writable so app-config.php can be generated.'),
                    installer_requirement('App config file', !file_exists($app_config_file) || is_writable($app_config_file), 'application/config/app-config.php must be writable when it already exists.'),
                    installer_requirement('Database config file', is_readable($database_file), 'application/config/database.php should remain readable and constants-based.'),
                    installer_optional_requirement('HTACCESS file', is_writable($htaccess_file), '.htaccess is optional. Keep it writable only if this installer should manage clean URL rules.'),
                );
                $has_error = false;
                foreach ($requirements as $requirement) {
                    if ($requirement['required'] && !$requirement['passed']) {
                        $has_error = true;
                    }
                }
                ?>
                <div class="requirements">
                    <?php foreach ($requirements as $requirement) { ?>
                        <div class="check-card <?php echo $requirement['passed'] || !$requirement['required'] ? 'pass' : 'fail'; ?>">
                            <div class="check-dot"><?php echo $requirement['passed'] ? '✓' : ($requirement['required'] ? '!' : 'i'); ?></div>
                            <div>
                                <strong><?php echo installer_e($requirement['label']); ?></strong>
                                <span><?php echo installer_e($requirement['message']); ?></span>
                            </div>
                        </div>
                    <?php } ?>
                </div>
                <form action="" method="post" class="actions">
                    <input type="hidden" name="permissions_success" value="true">
                    <button type="submit" class="btn" <?php echo $has_error ? 'disabled' : ''; ?>>Continue</button>
                </form>
            <?php } ?>

            <?php if ($current_step === 2) { ?>
                <form action="" id="verify" class="form-grid" method="post" accept-charset="utf-8">
                    <input type="hidden" name="step" value="2">
                    <div class="field">
                        <label for="envato_username">Envato Username</label>
                        <input id="envato_username" type="text" name="envato_username" value="<?php echo installer_post('envato_username'); ?>" autocomplete="username">
                    </div>
                    <div class="field">
                        <label for="support_email">Support Email</label>
                        <input id="support_email" type="email" name="support_email" value="<?php echo installer_post('support_email'); ?>">
                    </div>
                    <div class="field full">
                        <label for="purchase_code">Purchase Code</label>
                        <input id="purchase_code" type="text" name="purchase_code" value="<?php echo installer_post('purchase_code'); ?>" placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">
                        <div class="hint">Use the purchase code from your Envato downloads page.</div>
                    </div>
                    <div class="actions">
                        <button type="submit" class="btn">Verify Purchase</button>
                    </div>
                </form>
            <?php } ?>

            <?php if ($current_step === 3) { ?>
                <form action="" id="database" class="form-grid" method="post" accept-charset="utf-8">
                    <input type="hidden" name="step" value="3">
                    <input type="hidden" name="envato_username" value="<?php echo installer_post('envato_username'); ?>">
                    <input type="hidden" name="support_email" value="<?php echo installer_post('support_email'); ?>">
                    <input type="hidden" name="purchase_code" value="<?php echo installer_post('purchase_code'); ?>">

                    <div class="field">
                        <label for="hostname">Database Host</label>
                        <input id="hostname" type="text" name="hostname" value="<?php echo installer_post('hostname', 'localhost'); ?>">
                    </div>
                    <div class="field">
                        <label for="database_name">Database Name</label>
                        <input id="database_name" type="text" name="database" value="<?php echo installer_post('database'); ?>" placeholder="db_ziscoerp">
                    </div>
                    <div class="field">
                        <label for="db_username">Database Username</label>
                        <input id="db_username" type="text" name="db_username" value="<?php echo installer_post('db_username'); ?>" autocomplete="username">
                    </div>
                    <div class="field">
                        <label for="db_password">Database Password</label>
                        <input id="db_password" type="password" name="db_password" value="<?php echo installer_post('db_password'); ?>" autocomplete="current-password">
                    </div>

                    <details class="full" open>
                        <summary>Application configuration</summary>
                        <div class="details-grid">
                            <div class="field">
                                <label for="app_base_url">Application URL</label>
                                <input id="app_base_url" type="url" name="app_base_url" value="<?php echo installer_post('app_base_url', $base_url); ?>">
                            </div>
                            <div class="field">
                                <label for="app_enc_key">Encryption Key</label>
                                <input id="app_enc_key" type="text" name="app_enc_key" value="<?php echo installer_post('app_enc_key', $this->encryption_key()); ?>">
                            </div>
                        </div>
                    </details>

                    <div class="actions">
                        <button type="submit" class="btn">Check Database</button>
                    </div>
                </form>
            <?php } ?>

            <?php if ($current_step === 4) { ?>
                <form action="" id="complete" class="form-grid" method="post" accept-charset="utf-8">
                    <input type="hidden" name="step" value="4">
                    <input type="hidden" name="hostname" value="<?php echo installer_post('hostname'); ?>">
                    <input type="hidden" name="database" value="<?php echo installer_post('database'); ?>">
                    <input type="hidden" name="db_username" value="<?php echo installer_post('db_username'); ?>">
                    <input type="hidden" name="db_password" value="<?php echo installer_post('db_password'); ?>">
                    <input type="hidden" name="app_base_url" value="<?php echo installer_post('app_base_url', $base_url); ?>">
                    <input type="hidden" name="app_enc_key" value="<?php echo installer_post('app_enc_key'); ?>">
                    <input type="hidden" name="envato_username" value="<?php echo installer_post('envato_username'); ?>">
                    <input type="hidden" name="support_email" value="<?php echo installer_post('support_email'); ?>">
                    <input type="hidden" name="purchase_code" value="<?php echo installer_post('purchase_code'); ?>">

                    <div class="field">
                        <label for="admin_fullname">Full Name</label>
                        <input id="admin_fullname" type="text" name="admin_fullname" value="<?php echo installer_post('admin_fullname'); ?>" placeholder="John Doe">
                    </div>
                    <div class="field">
                        <label for="admin_username">Username</label>
                        <input id="admin_username" type="text" name="admin_username" value="<?php echo installer_post('admin_username'); ?>" placeholder="johndoe" autocomplete="username">
                    </div>
                    <div class="field">
                        <label for="admin_password">Password</label>
                        <input id="admin_password" type="password" name="admin_password" autocomplete="new-password">
                    </div>
                    <div class="field">
                        <label for="confirm_password">Confirm Password</label>
                        <input id="confirm_password" type="password" name="confirm_password" autocomplete="new-password">
                    </div>
                    <div class="field">
                        <label for="admin_email">Admin Email</label>
                        <input id="admin_email" type="email" name="admin_email" value="<?php echo installer_post('admin_email', isset($_POST['support_email']) ? $_POST['support_email'] : ''); ?>">
                    </div>
                    <div class="field">
                        <label for="company_name">Company Name</label>
                        <input id="company_name" type="text" name="company_name" value="<?php echo installer_post('company_name'); ?>">
                    </div>
                    <div class="field">
                        <label for="company_email">Company Email</label>
                        <input id="company_email" type="email" name="company_email" value="<?php echo installer_post('company_email'); ?>">
                    </div>
                    <div class="field">
                        <label for="timezone">Timezone</label>
                        <select id="timezone" name="timezone" class="select_box" required>
                            <?php foreach ($this->get_timezones_list() as $timezone => $description) { ?>
                                <option value="<?php echo installer_e($timezone); ?>" <?php echo (isset($_POST['timezone']) && $_POST['timezone'] === $timezone) ? 'selected' : ''; ?>>
                                    <?php echo installer_e($description); ?>
                                </option>
                            <?php } ?>
                        </select>
                    </div>
                    <div class="actions">
                        <button type="submit" id="finish" class="btn">Complete Installation</button>
                    </div>
                </form>
            <?php } ?>

            <?php if ($current_step === 5) { ?>
                <div class="success-panel">
                    <h3>Installation successful</h3>
                    <p>The installer generated application configuration and created the administrator account.</p>
                    <a class="btn" href="<?php echo installer_e($base_url); ?>login">Go to Login</a>
                </div>
            <?php } ?>
        </section>
    </section>
</main>
<script src="../assets/plugins/install/jquery-2.2.4.min.js"></script>
<script src="../assets/plugins/install/jquery.validate.min.js"></script>
<script src="../assets/plugins/select2/dist/js/select2.min.js"></script>
<script>
    $(function () {
        $('.select_box').select2({ width: '100%' });

        setTimeout(function () {
            $('.sql-debug-alert').slideUp();
        }, 3500);

        $('#finish').on('click', function () {
            var button = $(this);
            if ($('#complete').valid()) {
                button.text('Installing...');
                button.prop('disabled', true);
                button.closest('form').submit();
            }
        });

        $('#database').validate({
            rules: {
                hostname: 'required',
                database: 'required',
                db_username: 'required',
                app_base_url: { required: true, url: true },
                app_enc_key: 'required'
            }
        });

        $('#verify').validate({
            rules: {
                envato_username: 'required',
                support_email: { required: true, email: true },
                purchase_code: 'required'
            }
        });

        $('#complete').validate({
            rules: {
                admin_username: 'required',
                admin_fullname: 'required',
                admin_password: 'required',
                confirm_password: {
                    required: true,
                    equalTo: '#admin_password'
                },
                admin_email: {
                    required: true,
                    email: true
                },
                company_name: 'required',
                company_email: {
                    required: true,
                    email: true
                },
                timezone: 'required'
            }
        });
    });
</script>
</body>
</html>
