<?= $this->extend('install/_layout') ?>
<?php $currentStep = 8; ?>

<?= $this->section('content') ?>
<h5 class="mb-3">Step 8 — Install Application</h5>
<p class="text-muted">This will create the database tables, seed default data, create your admin account, and finalize the installation. This usually takes under a minute.</p>

<div class="progress mb-3" style="height: 24px;">
    <div id="progressBar" class="progress-bar" role="progressbar" style="width: 0%">0%</div>
</div>

<ul id="stepList" class="list-group mb-4">
    <?php $i = 0; foreach ($steps as $key => $label): $i++; ?>
        <li class="list-group-item d-flex justify-content-between align-items-center" data-step="<?= esc($key) ?>">
            <span><?= esc($label) ?></span>
            <span class="status text-muted">Pending</span>
        </li>
    <?php endforeach; ?>
</ul>

<div id="finalActions" class="d-none">
    <div class="alert alert-success">Installation complete! 🎉</div>
    <a href="<?= base_url('login') ?>" class="btn btn-primary w-100">Go to Admin Login →</a>
</div>

<div id="errorBox" class="alert alert-danger d-none"></div>
<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
const steps = <?= json_encode(array_keys($steps)) ?>;
const bar = document.getElementById('progressBar');
const errorBox = document.getElementById('errorBox');

async function runSteps() {
    for (let i = 0; i < steps.length; i++) {
        const key = steps[i];
        const row = document.querySelector(`li[data-step="${key}"] .status`);
        row.textContent = 'Running…';
        row.className = 'status text-primary';

        try {
            const res = await fetch(`<?= base_url('install/run') ?>/${key}`, { method: 'POST', headers: {'X-Requested-With':'XMLHttpRequest'} });
            const json = await res.json();

            if (!json.success) {
                row.textContent = 'Failed';
                row.className = 'status text-danger';
                errorBox.textContent = json.errors[0].message;
                errorBox.classList.remove('d-none');
                return; // stop — safe to retry by refreshing, steps are idempotent
            }

            row.textContent = 'Done ✅';
            row.className = 'status text-success';
            bar.style.width = Math.round(((i + 1) / steps.length) * 100) + '%';
            bar.textContent = bar.style.width;
        } catch (err) {
            row.textContent = 'Failed';
            row.className = 'status text-danger';
            errorBox.textContent = 'Network error: ' + err.message;
            errorBox.classList.remove('d-none');
            return;
        }
    }

    document.getElementById('finalActions').classList.remove('d-none');
}

runSteps();
</script>
<?= $this->endSection() ?>
