<?php
declare(strict_types=1);

require_once __DIR__ . '/../app/storage.php';
require_once __DIR__ . '/installer_lib.php';

session_start();

$baseUrl = eaq_install_base_url();

function eaq_flash(string $msg, string $type = 'notice'): void {
  $_SESSION['eaq_flash'] = ['msg' => $msg, 'type' => $type];
}

function eaq_pop_flash(): ?array {
  $v = $_SESSION['eaq_flash'] ?? null;
  unset($_SESSION['eaq_flash']);
  return $v;
}

if (eaq_is_installed() && empty($_GET['reset'])) {
  $flash = eaq_pop_flash();
  ?>
  <!doctype html>
  <html lang="pt-BR">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Instalação - Bloqueada</title>
    <style>
      body { font-family: Arial, sans-serif; background:#0b1220; color:#e8eefc; margin:0; }
      .wrap { max-width: 900px; margin: 0 auto; padding: 28px 18px; }
      .card { background:#111a2e; border:1px solid #223053; border-radius: 14px; padding: 18px; }
      a { color:#7cc0ff; text-decoration:none; }
      .notice { background:#1f3b2f; border:1px solid #2c6a49; color:#bff2d6; padding:10px 12px; border-radius: 10px; margin-top: 12px; }
      .muted { color:#b7c8f0; font-size: 13px; }
    </style>
  </head>
  <body>
    <div class="wrap">
      <div class="card">
        <h2 style="margin:0 0 10px 0;">Instalação concluída</h2>
        <p class="muted">A rota <code>/install</code> está bloqueada para evitar reinstalação acidental.</p>
        <div class="notice">
          Sistema pronto. Acesse: <a href="<?php echo htmlspecialchars($baseUrl . '/app/', ENT_QUOTES); ?>"><?php echo htmlspecialchars($baseUrl . '/app/', ENT_QUOTES); ?></a>
        </div>
        <p class="muted" style="margin-top:14px;">
          Para reabrir a instalação (apenas para teste): use <code>/install?reset=1</code> (isso remove o flag local e remove o arquivo de bloqueio se existir).
        </p>
      </div>
    </div>
  </body>
  </html>
  <?php
  exit;
}

// reset manual (apenas para teste)
if (!empty($_GET['reset'])) {
  @unlink(__DIR__ . '/../config/installed.flag');
  $ht = __DIR__ . '/.htaccess';
  // não removemos automaticamente se você não quiser; mas removemos se existir para reabilitar.
  @unlink($ht);
}

$step = (int)($_GET['step'] ?? 1);
if ($step < 1 || $step > 5) $step = 1;

$flash = eaq_pop_flash();

// DB config in progress
if (!isset($_SESSION['eaq_install'])) $_SESSION['eaq_install'] = [];
$installState =& $_SESSION['eaq_install'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!isset($_POST['ea_action'])) {
    $step = 1;
  } else {
    $action = (string)$_POST['ea_action'];
    if ($action === 'step1_next') {
      $step = 2;
    } elseif ($action === 'test_db') {
      $db = eaq_detect_db_mode($_POST);
      $test = eaq_test_db_connection($db);
      $installState['db'] = $db;
      $installState['db_test'] = $test;
      $step = 2;
    } elseif ($action === 'step2_next') {
      $db = eaq_detect_db_mode($_POST);
      $test = eaq_test_db_connection($db);
      if (($db['mode'] ?? 'mock') === 'mysql' && empty($test['ok'])) {
        $installState['db'] = $db;
        $installState['db_test'] = $test;
        $step = 2;
        $error = $test['message'] ?? 'Falha ao validar banco.';
      } else {
        $installState['db'] = $db;
        $installState['db_test'] = $test;
        $step = 3;
      }
    } elseif ($action === 'step3_next') {
      // 1) write config (parcial)
      $db = $installState['db'] ?? ['mode'=>'mock'];
      $cfg = [
        'app_name' => 'EventsAppQuest Web (setup)',
        'lang' => 'pt-BR',
        'base_url' => $baseUrl,
        'db' => $db,
        'enable_admin_actions' => true,
      ];
      eaq_write_config($cfg);

      // 2) create SQL tables if mysql mode
      $sql = __DIR__ . '/../database/schema.sql';
      if (($db['mode'] ?? 'mock') === 'mysql') {
        $apply = eaq_run_sql($db, $sql);
        if (empty($apply['ok'])) {
          $error = $apply['message'] ?? 'Erro ao aplicar SQL.';
          $step = 3;
        } else {
          $installState['sql_applied'] = true;
          $step = 4;
        }
      } else {
        // mock mode: no SQL required.
        $installState['sql_applied'] = true;
        $step = 4;
      }

      // seed CRM snapshot immediately (para garantir app funcional)
      if (eaq_read_json('mock_crm.json', null) === null) {
        require_once __DIR__ . '/../app/mock_data.php';
        $data = eaq_seed_mock_crm();
        eaq_write_json('mock_crm.json', $data);
      }
    } elseif ($action === 'step4_next') {
      $db = $installState['db'] ?? ['mode'=>'mock'];
      $appName = trim((string)($_POST['app_name'] ?? 'EventsAppQuest Web'));
      $lang = trim((string)($_POST['lang'] ?? 'pt-BR'));
      $adminUsername = trim((string)($_POST['admin_username'] ?? 'admin'));
      $adminPassword = (string)($_POST['admin_password'] ?? '');
      $adminPassword2 = (string)($_POST['admin_password2'] ?? '');
      $appUrl = trim((string)($_POST['app_url'] ?? $baseUrl));

      if ($adminUsername === '' || $adminPassword === '') {
        $error = 'Informe usuário e senha do admin.';
        $step = 4;
      } elseif ($adminPassword !== $adminPassword2) {
        $error = 'Senhas do admin não coincidem.';
        $step = 4;
      } else {
        $cfg = [
          'app_name' => $appName,
          'lang' => $lang,
          'base_url' => $appUrl,
          'db' => $db,
          'enable_admin_actions' => true,
        ];
        eaq_write_config($cfg);
        eaq_seed_admin_and_data($cfg, $adminUsername, $adminPassword);
        $installState['final_cfg'] = $cfg;
        $step = 5;
      }
    } elseif ($action === 'finish') {
      // finalize (flag + optional htaccess)
      $disableInstall = !empty($_POST['disable_install']);
      if ($disableInstall) {
        eaq_finish_installation();
      } else {
        // still mark installed without disabling htaccess
        file_put_contents(eaq_installed_flag_path(), (string)time(), LOCK_EX);
      }
      eaq_redirect($baseUrl . '/app/');
    }
  }
}

// Render UI
?>
<!doctype html>
<html lang="pt-BR">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Instalação - Wizard</title>
  <style>
    body { font-family: Arial, sans-serif; background:#0b1220; color:#e8eefc; margin:0; }
    .wrap { max-width: 980px; margin: 0 auto; padding: 28px 18px; }
    .card { background:#111a2e; border:1px solid #223053; border-radius: 14px; padding: 18px; }
    .steps { display:flex; gap:10px; flex-wrap:wrap; margin-bottom: 14px; }
    .step { padding: 8px 12px; border-radius: 999px; border:1px solid #223053; font-size: 13px; color:#cfe0ff; }
    .step.active { background:#2454ff; border-color:#2454ff; }
    label { display:block; margin-top: 10px; font-size: 13px; color:#cfe0ff; }
    input, select { width:100%; padding:10px 12px; border-radius:10px; border:1px solid #2a3b63; background:#0b1220; color:#e8eefc; }
    button { padding: 10px 14px; border-radius: 10px; border:1px solid #2a3b63; background:#2454ff; color:#fff; cursor:pointer; }
    .row { display:flex; gap:12px; }
    .row > div { flex:1; }
    .notice { background:#1f3b2f; border:1px solid #2c6a49; color:#bff2d6; padding:10px 12px; border-radius: 10px; margin-bottom: 12px; }
    .error { background:#3b0f0f; border:1px solid #6a1f1f; color:#ffd2d2; padding:10px 12px; border-radius: 10px; margin-bottom: 12px; }
    .muted { color:#b7c8f0; font-size: 13px; }
    a { color:#7cc0ff; text-decoration:none; }
    .small { font-size: 12px; color:#b7c8f0; }
  </style>
</head>
<body>
  <div class="wrap">
    <div class="card">
      <h2 style="margin:0 0 10px 0;">Wizard de Instalação</h2>
      <div class="steps">
        <?php for($i=1;$i<=5;$i++): ?>
          <div class="step <?php echo $i===$step ? 'active' : ''; ?>">ETAPA <?php echo $i; ?></div>
        <?php endfor; ?>
      </div>
      <?php if (!empty($flash)): ?><div class="<?php echo htmlspecialchars($flash['type'], ENT_QUOTES); ?>"><?php echo htmlspecialchars($flash['msg'], ENT_QUOTES); ?></div><?php endif; ?>
      <?php if (!empty($error)): ?><div class="error"><?php echo htmlspecialchars((string)$error, ENT_QUOTES); ?></div><?php endif; ?>

      <?php if ($step === 1): ?>
        <h3 style="margin:12px 0 10px 0; font-size:15px;">ETAPA 1 — Verificação do ambiente</h3>
        <?php
          $sum = '';
          $env = eaq_verify_environment($sum);
        ?>
        <p class="muted"><?php echo htmlspecialchars($sum, ENT_QUOTES); ?></p>
        <div style="margin-top: 10px;">
          <?php foreach ($env as $r): ?>
            <div class="small" style="padding:8px 10px; border:1px solid #223053; border-radius:10px; margin-bottom:8px;">
              <strong><?php echo htmlspecialchars($r['label'], ENT_QUOTES); ?>:</strong>
              <span style="color:<?php echo ($r['type']==='ok') ? '#9be7b7' : (($r['type']==='error') ? '#ffd2d2' : '#ffd89b'); ?>">
                <?php echo htmlspecialchars((string)$r['value'], ENT_QUOTES); ?>
              </span>
            </div>
          <?php endforeach; ?>
        </div>

        <form method="post" action="?step=1" style="margin-top:12px;">
          <input type="hidden" name="ea_action" value="step1_next">
          <button type="submit" <?php echo 'disabled'; ?>></button>
        </form>
        <p class="muted">
          Para prosseguir, corrija erros de ambiente (PHP/extension/write). Quando estiver tudo “OK”, reabra a página e clique em “Seguinte”.
        </p>

        <?php
          $allOk = true;
          foreach ($env as $r) { if (($r['type'] ?? '') !== 'ok') $allOk = false; }
          if ($allOk):
        ?>
          <form method="post" action="?step=2" style="margin-top:12px;">
            <input type="hidden" name="ea_action" value="step1_next">
            <button type="submit">Seguinte →</button>
          </form>
        <?php endif; ?>

      <?php elseif ($step === 2): ?>
        <?php $db = $installState['db'] ?? ['mode'=>'mock']; $dbTest = $installState['db_test'] ?? null; ?>
        <h3 style="margin:12px 0 10px 0; font-size:15px;">ETAPA 2 — Configuração do banco de dados</h3>
        <p class="muted">Você pode deixar <strong>host</strong> e <strong>database</strong> em branco para usar modo mock/local (recomendado para teste visual).</p>
        <form method="post" action="?step=2">
          <input type="hidden" name="ea_action" value="test_db">
          <div class="row">
            <div>
              <label>DB_HOST</label>
              <input name="db_host" value="<?php echo htmlspecialchars((string)($db['host'] ?? '')); ?>" placeholder="localhost">
            </div>
            <div>
              <label>DB_PORT</label>
              <input name="db_port" value="<?php echo htmlspecialchars((string)($db['port'] ?? '3306')); ?>" placeholder="3306">
            </div>
          </div>
          <div class="row">
            <div>
              <label>DB_DATABASE</label>
              <input name="db_database" value="<?php echo htmlspecialchars((string)($db['database'] ?? '')); ?>" placeholder="eventsapp_web">
            </div>
            <div>
              <label>DB_USERNAME</label>
              <input name="db_username" value="<?php echo htmlspecialchars((string)($db['username'] ?? '')); ?>" placeholder="root">
            </div>
          </div>
          <label>DB_PASSWORD</label>
          <input type="password" name="db_password" value="<?php echo htmlspecialchars((string)($db['password'] ?? '')); ?>" placeholder="">

          <div style="margin-top:14px;" class="form-inline">
            <button type="submit">Testar conexão</button>
          </div>
        </form>

        <?php if ($dbTest): ?>
          <div class="<?php echo !empty($dbTest['ok']) ? 'notice' : 'error'; ?>" style="margin-top:12px;">
            <?php echo htmlspecialchars((string)$dbTest['message'], ENT_QUOTES); ?>
          </div>
        <?php endif; ?>

        <form method="post" action="?step=3" style="margin-top:12px;">
          <input type="hidden" name="ea_action" value="step2_next">
          <input type="hidden" name="db_host" value="<?php echo htmlspecialchars((string)($db['host'] ?? '')); ?>">
          <input type="hidden" name="db_port" value="<?php echo htmlspecialchars((string)($db['port'] ?? '3306')); ?>">
          <input type="hidden" name="db_database" value="<?php echo htmlspecialchars((string)($db['database'] ?? '')); ?>">
          <input type="hidden" name="db_username" value="<?php echo htmlspecialchars((string)($db['username'] ?? '')); ?>">
          <input type="hidden" name="db_password" value="<?php echo htmlspecialchars((string)($db['password'] ?? '')); ?>">
          <button type="submit">Continuar →</button>
        </form>

      <?php elseif ($step === 3): ?>
        <h3 style="margin:12px 0 10px 0; font-size:15px;">ETAPA 3 — Instalação da estrutura</h3>
        <p class="muted">Isso cria/atualiza arquivos de configuração e (se DB estiver configurada) aplica SQL para criar tabelas.</p>
        <p class="muted">Modo atual: <strong><?php echo htmlspecialchars((string)($installState['db']['mode'] ?? 'mock'), ENT_QUOTES); ?></strong></p>

        <form method="post" action="?step=3" style="margin-top:12px;">
          <input type="hidden" name="ea_action" value="step3_next">
          <button type="submit">Executar instalação →</button>
        </form>

      <?php elseif ($step === 4): ?>
        <h3 style="margin:12px 0 10px 0; font-size:15px;">ETAPA 4 — Configuração inicial</h3>
        <?php $db = $installState['db'] ?? ['mode'=>'mock']; ?>

        <form method="post" action="?step=4">
          <input type="hidden" name="ea_action" value="step4_next">

          <label>URL da aplicação (base)</label>
          <input name="app_url" value="<?php echo htmlspecialchars($baseUrl, ENT_QUOTES); ?>" placeholder="/eventsappquest">

          <label>Nome da aplicação</label>
          <input name="app_name" value="EventsAppQuest Web" placeholder="EventsAppQuest Web">

          <div class="row">
            <div>
              <label>Idioma padrão</label>
              <input name="lang" value="pt-BR" placeholder="pt-BR">
            </div>
            <div>
              <label>Admin username</label>
              <input name="admin_username" value="admin" placeholder="admin">
            </div>
          </div>

          <label>Admin password</label>
          <input type="password" name="admin_password" value="" placeholder="Defina uma senha">

          <label>Confirmar admin password</label>
          <input type="password" name="admin_password2" value="" placeholder="Repita a senha">

          <div style="margin-top:14px;">
            <button type="submit">Salvar & continuar →</button>
          </div>
        </form>

      <?php elseif ($step === 5): ?>
        <h3 style="margin:12px 0 10px 0; font-size:15px;">ETAPA 5 — Finalização</h3>
        <p class="muted">Clique em concluir para marcar a instalação como finalizada e bloquear reinstalação automática.</p>

        <form method="post" action="?step=5">
          <input type="hidden" name="ea_action" value="finish">
          <label style="display:flex; gap:10px; align-items:center; margin-top:12px;">
            <input type="checkbox" name="disable_install" value="1" checked>
            <span>Desabilitar acesso a <code>/install</code> via <code>.htaccess</code> após concluir</span>
          </label>
          <div style="margin-top:14px;">
            <button type="submit">Concluir</button>
          </div>
        </form>

        <p class="muted" style="margin-top:14px;">
          Após concluir, você será redirecionado para: <a href="<?php echo htmlspecialchars($baseUrl . '/app/', ENT_QUOTES); ?>"><?php echo htmlspecialchars($baseUrl . '/app/', ENT_QUOTES); ?></a>
        </p>
      <?php endif; ?>

      <div style="margin-top:16px;" class="muted">
        <div><strong>Importante:</strong> mantenha os diretórios de <code>config/</code> e <code>storage/</code> graváveis no cPanel.</div>
      </div>
    </div>
  </div>
</body>
</html>

