<?php
/**
 * Debrieft — Setup Wizard
 * Run once after uploading files to configure the app.
 * Delete or rename this file after setup is complete.
 */

define('SETUP_MODE', true);
define('CONFIG_PATH', __DIR__ . '/../config.php');
define('SCHEMA_PATH', __DIR__ . '/../schema_full.sql');
define('LOCK_FILE',   __DIR__ . '/../.setup_complete');

// Block re-running if already installed
if (file_exists(LOCK_FILE)) {
    die(renderBlocked());
}

session_start();
if (empty($_SESSION['setup_step'])) $_SESSION['setup_step'] = 1;

$step  = (int)($_GET['step'] ?? $_SESSION['setup_step']);
$error = '';
$info  = '';

// ── Step handlers ─────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $posted = $_POST['step'] ?? 0;

    // STEP 1 — Requirements check (just advance)
    if ($posted == 1) {
        $_SESSION['setup_step'] = 2;
        header('Location: setup.php?step=2'); exit;
    }

    // STEP 2 — Database config
    if ($posted == 2) {
        $dbHost = trim($_POST['db_host'] ?? 'localhost');
        $dbName = trim($_POST['db_name'] ?? '');
        $dbUser = trim($_POST['db_user'] ?? '');
        $dbPass = $_POST['db_pass'] ?? '';
        $appUrl = rtrim(trim($_POST['app_url'] ?? ''), '/');

        if (!$dbName || !$dbUser) { $error = 'Database name and username are required.'; $step = 2; goto render; }

        // Test connection
        try {
            $pdo = new PDO("mysql:host=$dbHost;charset=utf8mb4", $dbUser, $dbPass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
        } catch (PDOException $e) {
            $error = 'Database connection failed: ' . $e->getMessage(); $step = 2; goto render;
        }

        // Create DB if it doesn't exist
        $pdo->exec("CREATE DATABASE IF NOT EXISTS `$dbName` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
        $pdo->exec("USE `$dbName`");

        // Import schema
        $sql = file_get_contents(SCHEMA_PATH);
        // Remove the USE statement and CREATE DATABASE (we already did those)
        $sql = preg_replace('/^CREATE DATABASE.*?;\s*/im', '', $sql);
        $sql = preg_replace('/^USE .*?;\s*/im', '', $sql);
        // Remove the demo user insert — we'll create admin in step 3
        $sql = preg_replace('/^INSERT INTO users.*?;/ims', '', $sql);

        foreach (array_filter(array_map('trim', explode(';', $sql))) as $stmt) {
            if ($stmt) { try { $pdo->exec($stmt); } catch (PDOException $e) { /* ignore duplicate table errors */ } }
        }

        $_SESSION['setup_db']  = compact('dbHost','dbName','dbUser','dbPass');
        $_SESSION['setup_url'] = $appUrl;
        $_SESSION['setup_step'] = 3;
        header('Location: setup.php?step=3'); exit;
    }

    // STEP 3 — Admin account
    if ($posted == 3) {
        $name    = trim($_POST['admin_name']    ?? '');
        $email   = trim($_POST['admin_email']   ?? '');
        $pass    = $_POST['admin_pass']          ?? '';
        $company = trim($_POST['admin_company'] ?? '');
        $apiKey  = trim($_POST['api_key']        ?? '');

        if (!$name || !$email || !$pass) { $error = 'Name, email, and password are required.'; $step = 3; goto render; }
        if (strlen($pass) < 8) { $error = 'Password must be at least 8 characters.'; $step = 3; goto render; }

        $_SESSION['setup_admin'] = compact('name','email','pass','company','apiKey');
        $_SESSION['setup_step']  = 4;
        header('Location: setup.php?step=4'); exit;
    }

    // STEP 4 — Write config & finish
    if ($posted == 4) {
        $db     = $_SESSION['setup_db']    ?? [];
        $url    = $_SESSION['setup_url']   ?? '';
        $admin  = $_SESSION['setup_admin'] ?? [];

        if (!$db || !$admin) { $error = 'Session expired. Please start over.'; $step = 1; goto render; }

        $appKey = bin2hex(random_bytes(16));
        $generatedAt = date('Y-m-d H:i:s');

        $config = <<<PHP
<?php
// config.php — generated by setup wizard on $generatedAt

define('DB_HOST',    '{$db['dbHost']}');
define('DB_NAME',    '{$db['dbName']}');
define('DB_USER',    '{$db['dbUser']}');
define('DB_PASS',    '{$db['dbPass']}');
define('DB_CHARSET', 'utf8mb4');

define('APP_NAME', 'Debrieft');
define('APP_URL',  '$url');
define('APP_KEY',  '$appKey');

define('ANTHROPIC_API_KEY', '{$admin['apiKey']}');
define('ANTHROPIC_MODEL',   'claude-sonnet-4-20250514');

ini_set('session.cookie_httponly', 1);
ini_set('session.use_strict_mode', 1);
session_name('debrieft_session');
PHP;

        // Write config
        if (file_put_contents(CONFIG_PATH, $config) === false) {
            $error = 'Could not write config.php — check file permissions (chmod 755 the root folder).';
            $step = 4; goto render;
        }

        // Create admin user in DB
        try {
            $pdo = new PDO(
                "mysql:host={$db['dbHost']};dbname={$db['dbName']};charset=utf8mb4",
                $db['dbUser'], $db['dbPass'],
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
            );
            $hash = password_hash($admin['pass'], PASSWORD_BCRYPT);
            $pdo->prepare("INSERT INTO users (name, email, password, role, company, anthropic_api_key) VALUES (?,?,?,'admin',?,?)")
                ->execute([$admin['name'], $admin['email'], $hash, $admin['company'], $admin['apiKey']]);
        } catch (PDOException $e) {
            $error = 'Could not create admin user: ' . $e->getMessage(); $step = 4; goto render;
        }

        // Write lock file
        file_put_contents(LOCK_FILE, date('Y-m-d H:i:s'));

        $_SESSION['setup_step'] = 5;
        header('Location: setup.php?step=5'); exit;
    }
}

$step = max(1, min(5, $step));

// ── Requirements check ────────────────────────────────────────────────────────
$checks = [
    ['PHP Version ≥ 8.1',       version_compare(PHP_VERSION, '8.1.0', '>='),     PHP_VERSION],
    ['PDO Extension',            extension_loaded('pdo'),                          'required'],
    ['PDO MySQL Driver',         extension_loaded('pdo_mysql'),                    'required'],
    ['cURL Extension',           extension_loaded('curl'),                         'for AI briefs'],
    ['config.php writable',      is_writable(dirname(CONFIG_PATH)),                'directory writable'],
    ['schema_full.sql exists',        file_exists(SCHEMA_PATH),                         'found'],
    ['OpenSSL Extension',        extension_loaded('openssl'),                      'for CSRF tokens'],
];

$allPassed = !in_array(false, array_column($checks, 1));

render:
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Debrieft Setup Wizard</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@400;600;700;800&family=DM+Sans:ital,opsz,wght@0,9..40,300;0,9..40,400;0,9..40,500;1,9..40,300&display=swap" rel="stylesheet">
<style>
  :root {
    --bg:      #080a0f;
    --bg2:     #0f1117;
    --bg3:     #171b24;
    --border:  #1f2433;
    --text:    #e4e8f0;
    --text2:   #7a809a;
    --accent:  #5b5ef4;
    --accent2: #818cf8;
    --green:   #22d3a0;
    --red:     #f87171;
    --yellow:  #fbbf24;
    --r:       12px;
  }
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

  body {
    font-family: 'DM Sans', sans-serif;
    background: var(--bg);
    color: var(--text);
    min-height: 100vh;
    display: flex;
    align-items: stretch;
  }

  /* ── Left panel ── */
  .left-panel {
    width: 320px;
    flex-shrink: 0;
    background: var(--bg2);
    border-right: 1px solid var(--border);
    display: flex;
    flex-direction: column;
    padding: 48px 32px;
    position: relative;
    overflow: hidden;
  }

  .left-panel::before {
    content: '';
    position: absolute;
    bottom: -80px; left: -80px;
    width: 320px; height: 320px;
    background: radial-gradient(circle, rgba(91,94,244,.18) 0%, transparent 70%);
    pointer-events: none;
  }

  .brand {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 56px;
  }

  .brand-mark {
    width: 38px; height: 38px;
    background: var(--accent);
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-family: 'Syne', sans-serif;
    font-weight: 800; font-size: 18px;
    color: #fff;
    flex-shrink: 0;
  }

  .brand-name {
    font-family: 'Syne', sans-serif;
    font-weight: 700; font-size: 20px;
    letter-spacing: -.5px;
  }

  .steps-nav {
    display: flex;
    flex-direction: column;
    gap: 4px;
    flex: 1;
  }

  .step-item {
    display: flex;
    align-items: center;
    gap: 14px;
    padding: 12px 14px;
    border-radius: 10px;
    transition: background .2s;
  }

  .step-item.active   { background: var(--bg3); }
  .step-item.complete { opacity: .7; }

  .step-num {
    width: 28px; height: 28px;
    border-radius: 50%;
    border: 2px solid var(--border);
    display: flex; align-items: center; justify-content: center;
    font-size: 12px; font-weight: 700;
    flex-shrink: 0;
    color: var(--text2);
    transition: all .3s;
  }

  .step-item.active   .step-num { border-color: var(--accent); color: var(--accent); background: rgba(91,94,244,.12); }
  .step-item.complete .step-num { border-color: var(--green);  background: rgba(34,211,160,.12); color: var(--green); }

  .step-label { font-size: 14px; font-weight: 500; color: var(--text2); }
  .step-item.active   .step-label { color: var(--text); }
  .step-item.complete .step-label { color: var(--text2); }

  .step-sublabel { font-size: 11px; color: var(--text2); margin-top: 1px; }

  .panel-footer {
    font-size: 12px;
    color: var(--text2);
    margin-top: auto;
    padding-top: 32px;
  }

  /* ── Right panel ── */
  .right-panel {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 48px 40px;
    overflow-y: auto;
  }

  .wizard-card {
    width: 100%;
    max-width: 560px;
  }

  .wizard-step-tag {
    font-size: 11px;
    font-weight: 700;
    letter-spacing: 1.5px;
    text-transform: uppercase;
    color: var(--accent2);
    margin-bottom: 10px;
  }

  .wizard-title {
    font-family: 'Syne', sans-serif;
    font-size: 28px;
    font-weight: 800;
    line-height: 1.2;
    margin-bottom: 8px;
  }

  .wizard-sub {
    color: var(--text2);
    font-size: 15px;
    margin-bottom: 36px;
    line-height: 1.6;
  }

  /* ── Form ── */
  .form-group { margin-bottom: 20px; }

  label {
    display: block;
    font-size: 13px;
    font-weight: 500;
    color: var(--text2);
    margin-bottom: 6px;
  }

  label span.req { color: var(--accent2); margin-left: 2px; }
  label small { font-weight: 400; color: var(--text2); margin-left: 6px; font-size: 11px; }

  input[type=text], input[type=email], input[type=password], input[type=url] {
    width: 100%;
    background: var(--bg3);
    border: 1px solid var(--border);
    border-radius: var(--r);
    padding: 11px 14px;
    color: var(--text);
    font-family: 'DM Sans', sans-serif;
    font-size: 14px;
    outline: none;
    transition: border-color .15s, box-shadow .15s;
  }

  input:focus {
    border-color: var(--accent);
    box-shadow: 0 0 0 3px rgba(91,94,244,.15);
  }

  input::placeholder { color: #3a3f52; }

  .field-hint {
    font-size: 12px;
    color: var(--text2);
    margin-top: 5px;
  }

  .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }

  /* ── Buttons ── */
  .btn-row { display: flex; gap: 10px; margin-top: 32px; }

  .btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 11px 22px;
    border-radius: var(--r);
    font-family: 'DM Sans', sans-serif;
    font-size: 14px; font-weight: 600;
    cursor: pointer;
    border: none;
    transition: all .15s;
    text-decoration: none;
  }

  .btn-primary { background: var(--accent); color: #fff; }
  .btn-primary:hover { background: #4a4de0; transform: translateY(-1px); box-shadow: 0 4px 20px rgba(91,94,244,.4); }
  .btn-ghost   { background: var(--bg3); color: var(--text2); border: 1px solid var(--border); }
  .btn-ghost:hover { color: var(--text); }
  .btn-success { background: var(--green); color: #000; font-weight: 700; }
  .btn-success:hover { opacity: .9; transform: translateY(-1px); }

  /* ── Alerts ── */
  .alert {
    padding: 12px 16px;
    border-radius: var(--r);
    font-size: 14px;
    margin-bottom: 24px;
    display: flex;
    align-items: flex-start;
    gap: 10px;
  }
  .alert-error   { background: rgba(248,113,113,.08); border: 1px solid rgba(248,113,113,.2); color: var(--red); }
  .alert-success { background: rgba(34,211,160,.08);  border: 1px solid rgba(34,211,160,.2);  color: var(--green); }
  .alert-info    { background: rgba(129,140,248,.08); border: 1px solid rgba(129,140,248,.2); color: var(--accent2); }

  /* ── Requirements list ── */
  .req-list { display: flex; flex-direction: column; gap: 10px; margin-bottom: 28px; }

  .req-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 16px;
    background: var(--bg3);
    border: 1px solid var(--border);
    border-radius: 10px;
    font-size: 14px;
  }

  .req-icon {
    width: 24px; height: 24px;
    border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    font-size: 13px;
    flex-shrink: 0;
  }

  .req-ok   { background: rgba(34,211,160,.15); color: var(--green); }
  .req-fail { background: rgba(248,113,113,.15); color: var(--red); }
  .req-warn { background: rgba(251,191,36,.15);  color: var(--yellow); }

  .req-name  { flex: 1; font-weight: 500; }
  .req-value { font-size: 12px; color: var(--text2); font-family: monospace; }

  /* ── Section divider ── */
  .section-divider {
    border: none;
    border-top: 1px solid var(--border);
    margin: 28px 0;
  }

  .section-title {
    font-size: 11px;
    font-weight: 700;
    letter-spacing: 1.2px;
    text-transform: uppercase;
    color: var(--text2);
    margin-bottom: 18px;
  }

  /* ── Success screen ── */
  .success-icon {
    width: 72px; height: 72px;
    background: rgba(34,211,160,.12);
    border: 2px solid rgba(34,211,160,.3);
    border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    font-size: 32px;
    margin-bottom: 28px;
    animation: pop .4s cubic-bezier(.34,1.56,.64,1);
  }

  @keyframes pop {
    from { transform: scale(0); opacity: 0; }
    to   { transform: scale(1); opacity: 1; }
  }

  .checklist { list-style: none; display: flex; flex-direction: column; gap: 8px; margin: 20px 0 32px; }
  .checklist li {
    display: flex; align-items: center; gap: 10px;
    font-size: 14px; color: var(--text2);
  }
  .checklist li::before { content: '✓'; color: var(--green); font-weight: 700; font-size: 14px; }

  /* ── Config preview ── */
  .config-preview {
    background: var(--bg3);
    border: 1px solid var(--border);
    border-radius: var(--r);
    padding: 18px;
    font-family: 'Courier New', monospace;
    font-size: 12px;
    color: var(--text2);
    line-height: 1.7;
    max-height: 200px;
    overflow-y: auto;
    margin-bottom: 24px;
  }

  .config-preview .kw  { color: var(--accent2); }
  .config-preview .str { color: var(--green); }
  .config-preview .fn  { color: #fb923c; }

  /* Progress bar */
  .progress-bar {
    height: 3px;
    background: var(--border);
    border-radius: 99px;
    margin-bottom: 36px;
    overflow: hidden;
  }
  .progress-fill {
    height: 100%;
    background: linear-gradient(90deg, var(--accent), var(--accent2));
    border-radius: 99px;
    transition: width .4s cubic-bezier(.4,0,.2,1);
  }

  @media (max-width: 760px) {
    body { flex-direction: column; }
    .left-panel { width: 100%; border-right: none; border-bottom: 1px solid var(--border); padding: 28px 24px; }
    .steps-nav { flex-direction: row; flex-wrap: wrap; gap: 8px; }
    .step-sublabel { display: none; }
    .right-panel { padding: 32px 20px; }
    .form-row { grid-template-columns: 1fr; }
  }
</style>
</head>
<body>

<!-- Left sidebar -->
<div class="left-panel">
  <div class="brand">
    <div class="brand-mark">D</div>
    <div class="brand-name">debrieft</div>
  </div>

  <nav class="steps-nav">
    <?php
    $stepDefs = [
      1 => ['Requirements', 'Check server compatibility'],
      2 => ['Database',     'Connect MySQL database'],
      3 => ['Admin Account','Create your login'],
      4 => ['Review',       'Confirm & install'],
      5 => ['Complete',     'You\'re all set!'],
    ];
    foreach ($stepDefs as $num => [$label, $sub]):
      $cls = $num < $step ? 'complete' : ($num === $step ? 'active' : '');
      $icon = $num < $step ? '✓' : $num;
    ?>
    <div class="step-item <?= $cls ?>">
      <div class="step-num"><?= $icon ?></div>
      <div>
        <div class="step-label"><?= $label ?></div>
        <div class="step-sublabel"><?= $sub ?></div>
      </div>
    </div>
    <?php endforeach; ?>
  </nav>

  <div class="panel-footer">
    Debrieft Setup Wizard<br>
    Delete <code>setup.php</code> after install
  </div>
</div>

<!-- Right content -->
<div class="right-panel">
  <div class="wizard-card">

    <!-- Progress bar -->
    <div class="progress-bar">
      <div class="progress-fill" style="width: <?= (($step-1)/4)*100 ?>%"></div>
    </div>

    <?php if ($error): ?>
    <div class="alert alert-error">⚠ <?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <!-- ═══════════════════════════════════════════════════════════════
         STEP 1 — Requirements
    ═══════════════════════════════════════════════════════════════ -->
    <?php if ($step === 1): ?>
    <div class="wizard-step-tag">Step 1 of 4</div>
    <h1 class="wizard-title">Server Requirements</h1>
    <p class="wizard-sub">Let's make sure your server is ready to run Debrieft.</p>

    <div class="req-list">
      <?php foreach ($checks as [$name, $pass, $value]): ?>
      <div class="req-item">
        <div class="req-icon <?= $pass ? 'req-ok' : 'req-fail' ?>"><?= $pass ? '✓' : '✕' ?></div>
        <span class="req-name"><?= htmlspecialchars($name) ?></span>
        <span class="req-value"><?= htmlspecialchars($value) ?></span>
      </div>
      <?php endforeach; ?>
    </div>

    <?php if (!$allPassed): ?>
    <div class="alert alert-error">Some requirements are not met. Please fix the issues above before continuing.</div>
    <?php else: ?>
    <div class="alert alert-success">✓ All requirements passed! Ready to install.</div>
    <?php endif; ?>

    <form method="POST">
      <input type="hidden" name="step" value="1">
      <div class="btn-row">
        <button class="btn btn-primary" type="submit" <?= !$allPassed ? 'disabled style="opacity:.4;cursor:not-allowed"' : '' ?>>
          Continue →
        </button>
      </div>
    </form>

    <!-- ═══════════════════════════════════════════════════════════════
         STEP 2 — Database
    ═══════════════════════════════════════════════════════════════ -->
    <?php elseif ($step === 2): ?>
    <div class="wizard-step-tag">Step 2 of 4</div>
    <h1 class="wizard-title">Database Setup</h1>
    <p class="wizard-sub">Enter your MySQL credentials. The wizard will create the database and import the schema automatically.</p>

    <form method="POST">
      <input type="hidden" name="step" value="2">

      <p class="section-title">Database Connection</p>

      <div class="form-row">
        <div class="form-group">
          <label>Database Host<span class="req">*</span></label>
          <input type="text" name="db_host" value="<?= htmlspecialchars($_POST['db_host'] ?? 'localhost') ?>" required>
          <div class="field-hint">Usually <code>localhost</code></div>
        </div>
        <div class="form-group">
          <label>Database Name<span class="req">*</span></label>
          <input type="text" name="db_name" value="<?= htmlspecialchars($_POST['db_name'] ?? 'debrieft') ?>" required placeholder="debrieft">
        </div>
      </div>
      <div class="form-row">
        <div class="form-group">
          <label>Username<span class="req">*</span></label>
          <input type="text" name="db_user" value="<?= htmlspecialchars($_POST['db_user'] ?? '') ?>" required placeholder="db_user">
        </div>
        <div class="form-group">
          <label>Password</label>
          <input type="password" name="db_pass" value="" placeholder="••••••••">
        </div>
      </div>

      <hr class="section-divider">
      <p class="section-title">Application URL</p>

      <div class="form-group">
        <label>App URL<span class="req">*</span><small>no trailing slash</small></label>
        <input type="url" name="app_url" value="<?= htmlspecialchars($_POST['app_url'] ?? 'https://rakibhasaan.com/quote/public') ?>" required>
        <div class="field-hint">The full URL to your <code>public/</code> directory</div>
      </div>

      <div class="btn-row">
        <a href="setup.php?step=1" class="btn btn-ghost">← Back</a>
        <button class="btn btn-primary" type="submit">Test & Continue →</button>
      </div>
    </form>

    <!-- ═══════════════════════════════════════════════════════════════
         STEP 3 — Admin Account
    ═══════════════════════════════════════════════════════════════ -->
    <?php elseif ($step === 3): ?>
    <div class="wizard-step-tag">Step 3 of 4</div>
    <h1 class="wizard-title">Your Admin Account</h1>
    <p class="wizard-sub">Create your designer account. You'll use these credentials to log in.</p>

    <form method="POST">
      <input type="hidden" name="step" value="3">

      <p class="section-title">Account Details</p>

      <div class="form-row">
        <div class="form-group">
          <label>Full Name<span class="req">*</span></label>
          <input type="text" name="admin_name" value="<?= htmlspecialchars($_POST['admin_name'] ?? '') ?>" required placeholder="Jane Smith">
        </div>
        <div class="form-group">
          <label>Studio / Company</label>
          <input type="text" name="admin_company" value="<?= htmlspecialchars($_POST['admin_company'] ?? '') ?>" placeholder="Smith Studio">
        </div>
      </div>
      <div class="form-group">
        <label>Email<span class="req">*</span></label>
        <input type="email" name="admin_email" value="<?= htmlspecialchars($_POST['admin_email'] ?? '') ?>" required placeholder="jane@studio.com">
      </div>
      <div class="form-group">
        <label>Password<span class="req">*</span><small>min 8 characters</small></label>
        <input type="password" name="admin_pass" required minlength="8" placeholder="Choose a strong password">
      </div>

      <hr class="section-divider">
      <p class="section-title">AI Integration <span style="color:var(--text2);font-weight:400;text-transform:none;letter-spacing:0;font-size:12px">(optional — can add later)</span></p>

      <div class="form-group">
        <label>Anthropic API Key</label>
        <input type="text" name="api_key" value="<?= htmlspecialchars($_POST['api_key'] ?? '') ?>" placeholder="sk-ant-api03-...">
        <div class="field-hint">Powers AI Brief generation. Get yours at <a href="https://console.anthropic.com" target="_blank" style="color:var(--accent2)">console.anthropic.com</a></div>
      </div>

      <div class="btn-row">
        <a href="setup.php?step=2" class="btn btn-ghost">← Back</a>
        <button class="btn btn-primary" type="submit">Review & Install →</button>
      </div>
    </form>

    <!-- ═══════════════════════════════════════════════════════════════
         STEP 4 — Review & Install
    ═══════════════════════════════════════════════════════════════ -->
    <?php elseif ($step === 4): ?>
    <?php
      $db    = $_SESSION['setup_db']    ?? [];
      $url   = $_SESSION['setup_url']   ?? '';
      $admin = $_SESSION['setup_admin'] ?? [];
    ?>
    <div class="wizard-step-tag">Step 4 of 4</div>
    <h1 class="wizard-title">Review & Install</h1>
    <p class="wizard-sub">Everything looks good. Review your settings below and click <strong>Install Debrieft</strong> to complete setup.</p>

    <div class="config-preview">
<span class="fn">define</span>(<span class="str">'DB_HOST'</span>, <span class="str">'<?= htmlspecialchars($db['dbHost'] ?? '') ?>'</span>);<br>
<span class="fn">define</span>(<span class="str">'DB_NAME'</span>, <span class="str">'<?= htmlspecialchars($db['dbName'] ?? '') ?>'</span>);<br>
<span class="fn">define</span>(<span class="str">'DB_USER'</span>, <span class="str">'<?= htmlspecialchars($db['dbUser'] ?? '') ?>'</span>);<br>
<span class="fn">define</span>(<span class="str">'DB_PASS'</span>, <span class="str">'[hidden]'</span>);<br>
<span class="fn">define</span>(<span class="str">'APP_URL'</span>, <span class="str">'<?= htmlspecialchars($url) ?>'</span>);<br>
<span class="fn">define</span>(<span class="str">'APP_KEY'</span>, <span class="str">'[auto-generated]'</span>);<br>
<?php if (!empty($admin['apiKey'])): ?><span class="fn">define</span>(<span class="str">'ANTHROPIC_API_KEY'</span>, <span class="str">'<?= substr(htmlspecialchars($admin['apiKey']), 0, 12) ?>...'</span>);<br><?php endif; ?>
    </div>

    <p class="section-title">Admin Account</p>
    <div class="req-list" style="margin-bottom:28px">
      <div class="req-item">
        <div class="req-icon req-ok">👤</div>
        <span class="req-name"><?= htmlspecialchars($admin['name'] ?? '') ?></span>
        <span class="req-value"><?= htmlspecialchars($admin['email'] ?? '') ?></span>
      </div>
    </div>

    <div class="alert alert-info">
      ⚡ This will write <code>config.php</code>, import the database schema, and create your admin account.
    </div>

    <form method="POST">
      <input type="hidden" name="step" value="4">
      <div class="btn-row">
        <a href="setup.php?step=3" class="btn btn-ghost">← Back</a>
        <button class="btn btn-primary" type="submit" style="background:linear-gradient(135deg,#5b5ef4,#818cf8)">
          🚀 Install Debrieft
        </button>
      </div>
    </form>

    <!-- ═══════════════════════════════════════════════════════════════
         STEP 5 — Complete!
    ═══════════════════════════════════════════════════════════════ -->
    <?php elseif ($step === 5): ?>
    <div class="success-icon">🎉</div>
    <h1 class="wizard-title">Installation Complete!</h1>
    <p class="wizard-sub">Debrieft is installed and ready to use. Here's what was set up:</p>

    <ul class="checklist">
      <li>Database schema imported successfully</li>
      <li>config.php written with your settings</li>
      <li>Admin account created</li>
      <li>App key generated for session security</li>
      <li>Lock file created — setup wizard is now disabled</li>
    </ul>

    <div class="alert alert-info" style="margin-bottom:28px">
      🔒 <strong>Security reminder:</strong> Delete or rename <code>setup.php</code> from your server now that installation is complete.
    </div>

    <?php $loginUrl = ($_SESSION['setup_url'] ?? '') . '/login.php'; ?>
    <div class="btn-row">
      <a href="<?= htmlspecialchars($loginUrl) ?>" class="btn btn-success">
        Go to Login →
      </a>
    </div>
    <?php endif; ?>

  </div>
</div>
</body>
</html>
<?php

// ── Blocked screen (already installed) ───────────────────────────────────────
function renderBlocked(): string {
    return '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8">
<title>Setup Locked</title>
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@700;800&family=DM+Sans:wght@400;500&display=swap" rel="stylesheet">
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:"DM Sans",sans-serif;background:#080a0f;color:#e4e8f0;min-height:100vh;display:flex;align-items:center;justify-content:center}
.card{max-width:420px;background:#0f1117;border:1px solid #1f2433;border-radius:16px;padding:40px;text-align:center}
.icon{font-size:48px;margin-bottom:20px}
h1{font-family:"Syne",sans-serif;font-size:22px;font-weight:800;margin-bottom:10px}
p{color:#7a809a;font-size:14px;line-height:1.6;margin-bottom:24px}
a{display:inline-flex;align-items:center;padding:11px 24px;background:#5b5ef4;color:#fff;border-radius:10px;text-decoration:none;font-weight:600;font-size:14px}
</style></head><body>
<div class="card">
  <div class="icon">🔒</div>
  <h1>Setup Already Complete</h1>
  <p>Debrieft has already been installed. This wizard is disabled for security.<br><br>
  Delete <code>setup.php</code> from your server.</p>
  <a href="login.php">Go to Login →</a>
</div></body></html>';
}
?>
