<?php
require_once __DIR__ . '/lib/core.php';

$done = false;
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $key = isset($_POST['setup_key']) ? $_POST['setup_key'] : '';
    $username = trim(isset($_POST['username']) ? $_POST['username'] : '');
    $password = isset($_POST['password']) ? $_POST['password'] : '';

    if (!hash_equals(DC_SETUP_KEY, $key) || DC_SETUP_KEY === 'change-this-setup-key') {
        $error = 'Invalid setup key. Change DC_SETUP_KEY in config.php first.';
    } elseif ($username === '' || strlen($password) < 8) {
        $error = 'Enter a username and a password of at least 8 characters.';
    } else {
        $sql = file_get_contents(__DIR__ . '/install.sql');
        dc_db()->exec($sql);
        $stmt = dc_db()->prepare('SELECT COUNT(*) FROM door_cert_admins');
        $stmt->execute();
        if ((int)$stmt->fetchColumn() === 0) {
            $stmt = dc_db()->prepare('INSERT INTO door_cert_admins (username, password_hash) VALUES (?, ?)');
            $stmt->execute(array($username, password_hash($password, PASSWORD_DEFAULT)));
        }
        $done = true;
    }
}

dc_public_header('Door Certificate Setup');
?>
<div class="dc-card">
  <h1>Door Certificate Setup</h1>
  <?php if ($error): ?><div class="dc-alert error"><?php echo dc_h($error); ?></div><?php endif; ?>
  <?php if ($done): ?>
    <div class="dc-alert success">Setup complete. Delete setup.php from the server now, then login to admin.</div>
    <p><a class="dc-btn" href="admin/login.php">Open Admin Login</a></p>
  <?php else: ?>
    <form method="post">
      <label>Setup Key</label>
      <input name="setup_key" required>
      <label>Admin Username</label>
      <input name="username" required>
      <label>Admin Password</label>
      <input name="password" type="password" required minlength="8">
      <p><button type="submit">Install Tables and Create Admin</button></p>
    </form>
  <?php endif; ?>
</div>
<?php dc_footer(); ?>
