<?php
include('../config/db.php');
include('../includes/auth.php');
require_once '../includes/csrf.php';
require_admin_role();
include('partials/header.php');

$flash = '';
$flashType = 'success';
$currentAdminId = (int)($_SESSION['admin']['id'] ?? 0);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    csrf_verify();

    if ($_POST['action'] === 'add') {
        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        $role     = ($_POST['role'] ?? 'staff') === 'admin' ? 'admin' : 'staff';

        if ($username === '' || strlen($username) > 50) {
            $flash = 'Username must be 1-50 characters.';
            $flashType = 'error';
        } elseif (strlen($password) < 6) {
            $flash = 'Password must be at least 6 characters.';
            $flashType = 'error';
        } else {
            $chk = $conn->prepare('SELECT id FROM admins WHERE username=? LIMIT 1');
            $chk->bind_param('s', $username);
            $chk->execute();
            if ($chk->get_result()->num_rows > 0) {
                $flash = 'That username is already taken.';
                $flashType = 'error';
            } else {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $ins = $conn->prepare('INSERT INTO admins (username, password, role) VALUES (?, ?, ?)');
                $ins->bind_param('sss', $username, $hash, $role);
                if ($ins->execute()) {
                    $flash = 'Account created (' . $role . ').';
                } else {
                    $flash = 'Could not create account.';
                    $flashType = 'error';
                }
                $ins->close();
            }
            $chk->close();
        }
    }

    if ($_POST['action'] === 'delete') {
        $targetId = (int)($_POST['admin_id'] ?? 0);

        if ($targetId <= 0) {
            $flash = 'Invalid account.';
            $flashType = 'error';
        } elseif ($targetId === $currentAdminId) {
            $flash = 'You cannot delete your own account while logged in.';
            $flashType = 'error';
        } else {
            $row = $conn->prepare('SELECT id, username, role FROM admins WHERE id=? LIMIT 1');
            $row->bind_param('i', $targetId);
            $row->execute();
            $target = $row->get_result()->fetch_assoc();
            $row->close();

            if (!$target) {
                $flash = 'Account not found.';
                $flashType = 'error';
            } else {
                $adminCount = (int)$conn->query("SELECT COUNT(*) c FROM admins WHERE role='admin'")->fetch_assoc()['c'];
                if ($target['role'] === 'admin' && $adminCount <= 1) {
                    $flash = 'Cannot delete the only admin account.';
                    $flashType = 'error';
                } else {
                    $del = $conn->prepare('DELETE FROM admins WHERE id=? LIMIT 1');
                    $del->bind_param('i', $targetId);
                    $del->execute();
                    $flash = $del->affected_rows > 0 ? 'Account deleted.' : 'Could not delete account.';
                    if ($del->affected_rows === 0) {
                        $flashType = 'error';
                    }
                    $del->close();
                }
            }
        }
    }
}

$staffList = [];
$res = $conn->query('SELECT id, username, role FROM admins ORDER BY role DESC, username ASC');
while ($row = $res->fetch_assoc()) {
    $staffList[] = $row;
}
?>

<?php if ($flash): ?>
<div class="adm-alert adm-alert-<?= $flashType === 'error' ? 'danger' : 'success' ?>" style="margin-bottom:18px">
  <i class="bi bi-<?= $flashType === 'error' ? 'exclamation-circle-fill' : 'check-circle-fill' ?>"></i>
  <?= htmlspecialchars($flash) ?>
</div>
<?php endif; ?>

<div class="pg-title">Staff and Admins</div>
<div class="pg-sub">Create staff (scan only) or admin (full access) accounts.</div>

<div class="row g-4">
  <div class="col-lg-5">
    <div class="adm-card" style="padding:0;overflow:hidden">
      <div class="adm-card-header"><span><i class="bi bi-person-plus-fill"></i> Add account</span></div>
      <form method="POST" style="padding:18px">
        <?php csrf_field(); ?>
        <input type="hidden" name="action" value="add">
        <label class="frm-label">Username</label>
        <input type="text" name="username" class="frm-ctrl" required maxlength="50" autocomplete="off" style="margin-bottom:12px">
        <label class="frm-label">Password</label>
        <input type="password" name="password" class="frm-ctrl" required minlength="6" autocomplete="new-password" style="margin-bottom:12px">
        <label class="frm-label">Role</label>
        <select name="role" class="frm-ctrl" style="margin-bottom:16px">
          <option value="staff">Staff - scan and view only</option>
          <option value="admin">Admin - full access</option>
        </select>
        <button type="submit" class="btn-accent" style="width:100%"><i class="bi bi-check2"></i> Create account</button>
      </form>
    </div>
  </div>

  <div class="col-lg-7">
    <div class="adm-card" style="padding:0;overflow:hidden">
      <div class="adm-card-header"><span><i class="bi bi-people-fill"></i> Accounts (<?= count($staffList) ?>)</span></div>
      <div class="table-responsive">
        <table class="adm-table">
          <thead>
            <tr><th>Username</th><th>Role</th><th style="width:100px">Action</th></tr>
          </thead>
          <tbody>
          <?php foreach ($staffList as $a): ?>
          <tr>
            <td style="font-weight:600">
              <?= htmlspecialchars($a['username']) ?>
              <?php if ((int)$a['id'] === $currentAdminId): ?>
              <span style="font-size:10px;color:var(--accent);margin-left:6px">(you)</span>
              <?php endif; ?>
            </td>
            <td>
              <?php if ($a['role'] === 'admin'): ?>
              <span class="badge-active"><i class="bi bi-shield-fill"></i> Admin</span>
              <?php else: ?>
              <span class="badge-pending"><i class="bi bi-qr-code-scan"></i> Staff</span>
              <?php endif; ?>
            </td>
            <td>
              <?php if ((int)$a['id'] !== $currentAdminId): ?>
              <form method="POST" style="margin:0" onsubmit="return confirm('Delete this account?');">
                <?php csrf_field(); ?>
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="admin_id" value="<?= (int)$a['id'] ?>">
                <button type="submit" class="btn-danger" style="padding:5px 10px;font-size:11px"><i class="bi bi-trash"></i></button>
              </form>
              <?php else: ?>
              <span style="font-size:11px;color:var(--muted)">-</span>
              <?php endif; ?>
            </td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<?php include('partials/footer.php'); ?>
