<?php
// /elms/auth/seed_first_staff.php
if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); }
define('APP_ROOT', dirname(__DIR__)); // .../elms
require_once APP_ROOT.'/includes/auth.php';
require_once APP_ROOT.'/includes/db.php';

$created = null; $error = null;

// create table if missing
$mysqli->query("
  CREATE TABLE IF NOT EXISTS elms_users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(100) NOT NULL UNIQUE,
    full_name VARCHAR(191) NOT NULL,
    role_slug VARCHAR(50) NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $username = trim($_POST['username'] ?? '');
  $full     = trim($_POST['full_name'] ?? '');
  $role     = role_slug($_POST['role'] ?? 'lecturer');
  $pass     = (string)($_POST['password'] ?? '');
  $pass2    = (string)($_POST['password2'] ?? '');

  if ($username === '' || $full === '' || $pass === '' || $pass2 === '') {
    $error = 'All fields are required.';
  } elseif ($pass !== $pass2) {
    $error = 'Passwords do not match.';
  } elseif (!in_array($role, ['lecturer','coordinator','course_coordinator','admin','branch_admin','super_admin'], true)) {
    $error = 'Invalid role.';
  } else {
    // check exists
    $st = $mysqli->prepare("SELECT id FROM elms_users WHERE username=? LIMIT 1");
    $st->bind_param('s',$username); $st->execute(); $st->bind_result($id);
    if ($st->fetch()) { $error = 'Username already exists.'; }
    $st->close();

    if (!$error) {
      $hash = password_hash($pass, PASSWORD_BCRYPT);
      $st = $mysqli->prepare("INSERT INTO elms_users(username, full_name, role_slug, password_hash) VALUES (?,?,?,?)");
      $st->bind_param('ssss',$username,$full,$role,$hash);
      if ($st->execute()) {
        $created = ['username'=>$username,'role'=>$role];
      } else {
        $error = 'Insert failed: '.$mysqli->error;
      }
      $st->close();
    }
  }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Seed First Staff User</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="<?= url_for('/assets/bootstrap.min.css') ?>" rel="stylesheet">
<style>body{max-width:560px;margin:40px auto}</style>
</head>
<body>
<h3>Seed First Staff User</h3>
<?php if ($created): ?>
  <div class="alert alert-success">
    Created <strong><?= htmlspecialchars($created['username']) ?></strong> (role: <?= htmlspecialchars($created['role']) ?>).
    You can now <a href="<?= url_for('/auth/login.php') ?>">log in</a>. Please delete this file.
  </div>
<?php elseif ($error): ?>
  <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<form method="post" class="vstack gap-3">
  <div>
    <label class="form-label">Username</label>
    <input class="form-control" name="username" value="lect1">
  </div>
  <div>
    <label class="form-label">Full name</label>
    <input class="form-control" name="full_name" value="Lecturer One">
  </div>
  <div>
    <label class="form-label">Role</label>
    <select class="form-select" name="role">
      <option value="lecturer" selected>lecturer</option>
      <option value="coordinator">coordinator</option>
      <option value="course_coordinator">course_coordinator</option>
      <option value="admin">admin</option>
      <option value="branch_admin">branch_admin</option>
      <option value="super_admin">super_admin</option>
    </select>
  </div>
  <div>
    <label class="form-label">Password</label>
    <input class="form-control" type="password" name="password" value="Lecturer@123">
  </div>
  <div>
    <label class="form-label">Confirm Password</label>
    <input class="form-control" type="password" name="password2" value="Lecturer@123">
  </div>

  <button class="btn btn-primary">Create user</button>
</form>
</body>
</html>
