<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
$u = require_superadmin();
$pdo = get_db();

$error = '';
$msg = $_GET['msg'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    csrf_check();
    $name = trim($_POST['name'] ?? '');
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $role = ($_POST['role'] ?? 'admin') === 'superadmin' ? 'superadmin' : 'admin';

    if (strlen($name) < 2 || strlen($username) < 3) {
        $error = 'Please provide a valid name and username (min 3 characters).';
    } elseif (strlen($password) < 8) {
        $error = 'Password must be at least 8 characters.';
    } else {
        try {
            $stmt = $pdo->prepare('INSERT INTO users (name, username, email, password_hash, role, active) VALUES (?,?,?,?,?,1)');
            $stmt->execute([$name, $username, $email, password_hash($password, PASSWORD_DEFAULT), $role]);
            header('Location: users.php?msg=' . urlencode('Account created for ' . $username));
            exit;
        } catch (PDOException $e) {
            $error = 'That username is already taken.';
        }
    }
}

if (isset($_GET['toggle'])) {
    $tid = (int)$_GET['toggle'];
    if ($tid !== (int)$u['id']) { // can't deactivate yourself
        $pdo->prepare('UPDATE users SET active = 1 - active WHERE id = ?')->execute([$tid]);
    }
    header('Location: users.php');
    exit;
}

$users = $pdo->query('SELECT * FROM users ORDER BY created_at DESC')->fetchAll(PDO::FETCH_ASSOC);
$csrf = csrf_token();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Manage Accounts — Delmas Careers Admin</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<link href="assets/admin.css" rel="stylesheet">
</head>
<body>
<?php include __DIR__ . '/includes/topbar.php'; ?>
<div class="admin-wrap">
  <h5 class="mb-3">Manage Accounts</h5>
  <?php if ($msg): ?><div class="alert alert-success py-2"><?= h($msg) ?></div><?php endif; ?>
  <?php if ($error): ?><div class="alert alert-danger py-2"><?= h($error) ?></div><?php endif; ?>

  <div class="row g-4">
    <div class="col-md-5">
      <div class="card-plain p-3">
        <h6>Create New Account</h6>
        <p class="small text-muted">Give this login to a colleague so they can sign in and post job listings.</p>
        <form method="post">
          <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
          <input type="hidden" name="action" value="create">
          <div class="mb-2"><label class="form-label small">Full Name</label><input class="form-control form-control-sm" name="name" required></div>
          <div class="mb-2"><label class="form-label small">Username</label><input class="form-control form-control-sm" name="username" required></div>
          <div class="mb-2"><label class="form-label small">Email (optional)</label><input class="form-control form-control-sm" type="email" name="email"></div>
          <div class="mb-2"><label class="form-label small">Password</label><input class="form-control form-control-sm" type="password" name="password" minlength="8" required></div>
          <div class="mb-2"><label class="form-label small">Role</label>
            <select class="form-select form-select-sm" name="role">
              <option value="admin">Admin (can post &amp; manage jobs)</option>
              <option value="superadmin">Super Admin (can also manage accounts)</option>
            </select>
          </div>
          <button class="btn btn-gold btn-sm w-100 mt-2" type="submit">Create Account</button>
        </form>
      </div>
    </div>
    <div class="col-md-7">
      <div class="card-plain p-3">
        <h6>Existing Accounts</h6>
        <table class="admin-table">
          <thead><tr><th>Name</th><th>Username</th><th>Role</th><th>Status</th><th></th></tr></thead>
          <tbody>
          <?php foreach ($users as $ux): ?>
            <tr>
              <td><?= h($ux['name']) ?></td>
              <td><?= h($ux['username']) ?></td>
              <td class="small"><?= h($ux['role']) ?></td>
              <td><?= $ux['active'] ? '<span class="badge badge-open">Active</span>' : '<span class="badge badge-closed">Disabled</span>' ?></td>
              <td>
                <a class="btn btn-sm btn-outline-gold" href="user-edit.php?id=<?= (int)$ux['id'] ?>">Edit</a>
                <?php if ((int)$ux['id'] !== (int)$u['id']): ?>
                  <a class="btn btn-sm btn-outline-gold" href="users.php?toggle=<?= (int)$ux['id'] ?>"><?= $ux['active'] ? 'Disable' : 'Enable' ?></a>
                <?php else: ?>
                  <span class="text-muted small">(you)</span>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
</body>
</html>
