<?php
declare(strict_types=1);
require_once __DIR__ . '/Includes.php';

$pdo->exec("CREATE TABLE IF NOT EXISTS users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(150) NOT NULL UNIQUE,
  password_hash VARCHAR(255) NOT NULL,
  must_change_password TINYINT(1) NOT NULL DEFAULT 0,
  role ENUM('admin', 'teacher', 'hop', 'accountant', 'ancillary', 'parent') NOT NULL DEFAULT 'teacher',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");
$pdo->exec("CREATE TABLE IF NOT EXISTS app_settings (
  setting_key VARCHAR(120) NOT NULL PRIMARY KEY,
  setting_value TEXT NOT NULL,
  updated_by INT NULL,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)");

if ((int)$pdo->query("SELECT COUNT(*) FROM users")->fetchColumn() > 0) {
  header('Location: index.php');
  exit;
}

$error = '';
$values = [
  'school_name' => trim((string)($_POST['school_name'] ?? 'MAVELA GOVERNMENT HIGH SCHOOL')),
  'school_address' => trim((string)($_POST['school_address'] ?? '')),
  'admin_name' => trim((string)($_POST['admin_name'] ?? '')),
  'admin_email' => trim((string)($_POST['admin_email'] ?? '')),
];

if (isset($_POST['complete_setup'])) {
  $password = (string)($_POST['admin_password'] ?? '');
  $confirmPassword = (string)($_POST['confirm_password'] ?? '');

  if ($values['school_name'] === '' || $values['admin_name'] === '' || $values['admin_email'] === '') {
    $error = 'School name, administrator name, and administrator email are required.';
  } elseif (!filter_var($values['admin_email'], FILTER_VALIDATE_EMAIL)) {
    $error = 'Enter a valid administrator email address.';
  } elseif (!mavela_password_is_strong($password)) {
    $error = 'Use at least 10 characters with uppercase, lowercase, and a number.';
  } elseif ($password !== $confirmPassword) {
    $error = 'The password confirmation does not match.';
  } else {
    try {
      $pdo->beginTransaction();
      $createAdmin = $pdo->prepare("INSERT INTO users
        (name, email, password_hash, must_change_password, role)
        VALUES (?, ?, ?, 0, 'admin')");
      $createAdmin->execute([
        $values['admin_name'],
        $values['admin_email'],
        password_hash($password, PASSWORD_DEFAULT),
      ]);
      $adminId = (int)$pdo->lastInsertId();

      $settingStmt = $pdo->prepare("INSERT INTO app_settings (setting_key, setting_value, updated_by)
        VALUES (?, ?, ?)
        ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_by = VALUES(updated_by)");
      $settingStmt->execute(['school_name', $values['school_name'], $adminId]);
      $settingStmt->execute(['school_address', $values['school_address'], $adminId]);
      $pdo->commit();

      $user = [
        'id' => $adminId,
        'name' => $values['admin_name'],
        'role' => 'admin',
        'must_change_password' => 0,
      ];
      append_system_log($pdo, 'system_setup_completed', 'Initial administrator created.', $adminId, 'admin', 'user', $adminId);
      login_user($user);
      header('Location: admin.php');
      exit;
    } catch (Throwable $e) {
      if ($pdo->inTransaction()) {
        $pdo->rollBack();
      }
      error_log('Mavela first-run setup failed: ' . $e->getMessage());
      $error = 'Setup could not be completed. Check the database permissions and try again.';
    }
  }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Mavela First-time Setup</title>
  <style>
    :root { --brand:#1d6a33; --brand-soft:#eef7ef; --ink:#173122; --muted:#596c60; --line:#dbe8de; }
    * { box-sizing:border-box; }
    body { margin:0; min-height:100vh; display:grid; place-items:center; padding:24px; font-family:system-ui,sans-serif; color:var(--ink); background:linear-gradient(145deg,#f7fbf7,#e4f0e7); }
    main { width:min(760px,100%); padding:clamp(24px,5vw,48px); background:#fff; border:1px solid var(--line); border-radius:24px; box-shadow:0 24px 70px rgba(19,66,36,.13); }
    .eyebrow { color:var(--brand); font-weight:800; text-transform:uppercase; letter-spacing:.08em; font-size:.78rem; }
    h1 { margin:8px 0; font-size:clamp(1.8rem,4vw,2.7rem); }
    .intro { margin:0 0 26px; color:var(--muted); line-height:1.65; }
    .grid { display:grid; grid-template-columns:1fr 1fr; gap:16px; }
    label { display:grid; gap:7px; font-weight:700; }
    label.full { grid-column:1/-1; }
    input { width:100%; padding:11px 12px; border:1px solid var(--line); }
    small { color:var(--muted); font-weight:500; }
    .error { margin:0 0 18px; padding:12px 14px; color:#8f1231; background:#fff0f3; border:1px solid #fecdd3; border-radius:12px; }
    button { margin-top:22px; width:100%; padding:12px 18px; color:#fff; background:var(--brand); border:0; border-radius:12px; font-weight:800; cursor:pointer; }
    @media (max-width:620px) { .grid { grid-template-columns:1fr; } label.full { grid-column:auto; } }
  </style>
</head>
<body>
  <main>
    <div class="eyebrow">Secure first-time setup</div>
    <h1>Prepare your school portal</h1>
    <p class="intro">Create the first administrator without using a shared default password. This page automatically closes after the administrator is created.</p>
    <?php if ($error !== ''): ?><div class="error"><?= h($error) ?></div><?php endif; ?>
    <form method="post">
      <div class="grid">
        <label class="full">School name
          <input name="school_name" value="<?= h($values['school_name']) ?>" maxlength="150" required>
        </label>
        <label class="full">School address
          <input name="school_address" value="<?= h($values['school_address']) ?>" maxlength="255">
        </label>
        <label>Administrator name
          <input name="admin_name" value="<?= h($values['admin_name']) ?>" autocomplete="name" maxlength="100" required>
        </label>
        <label>Administrator email
          <input type="email" name="admin_email" value="<?= h($values['admin_email']) ?>" autocomplete="email" maxlength="150" required>
        </label>
        <label>Administrator password
          <input type="password" name="admin_password" minlength="10" autocomplete="new-password" required>
          <small>10+ characters with uppercase, lowercase, and a number.</small>
        </label>
        <label>Confirm password
          <input type="password" name="confirm_password" minlength="10" autocomplete="new-password" required>
        </label>
      </div>
      <button type="submit" name="complete_setup">Create administrator and continue</button>
    </form>
  </main>
</body>
</html>
