<?php
require_once '../includes/config.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireAdminLogin();
requireSuperAdmin();

$error = ''; $success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verify_csrf()) {
    $action = $_POST['action'] ?? '';
    if ($action === 'add') {
        $username = trim($_POST['username'] ?? '');
        $email    = trim($_POST['email'] ?? '');
        $pass     = $_POST['password'] ?? '';
        $name     = trim($_POST['display_name'] ?? '');
        $role     = $_POST['role'] ?? 'admin';
        if (!$username || !$email || !$pass) { $error = 'All fields required.'; goto done; }
        $chk = $pdo->prepare("SELECT id FROM admin_users WHERE username=? OR email=? LIMIT 1");
        $chk->execute([$username,$email]);
        if ($chk->fetch()) { $error = 'Username or email already exists.'; goto done; }
        $pdo->prepare("INSERT INTO admin_users (username,email,password,display_name,role,status) VALUES (?,?,?,?,?,'active')")->execute([$username,$email,password_hash($pass,PASSWORD_DEFAULT),$name,$role]);
        logActivity($pdo,null,(int)$_SESSION['admin_id'],'add_sub_admin',"Created sub-admin: $username");
        flash('success',"Sub-admin $username created.");
        header('Location: /admin/sub-admins.php'); exit;
    }
    if ($action === 'toggle') {
        $aid = (int)$_POST['admin_id'];
        if ($aid !== (int)$_SESSION['admin_id']) {
            $cur = $pdo->prepare("SELECT status FROM admin_users WHERE id=? LIMIT 1"); $cur->execute([$aid]); $cs=$cur->fetchColumn();
            $ns = $cs==='active' ? 'suspended' : 'active';
            $pdo->prepare("UPDATE admin_users SET status=? WHERE id=?")->execute([$ns,$aid]);
            flash('success',"Admin status changed to $ns.");
        }
        header('Location: /admin/sub-admins.php'); exit;
    }
    if ($action === 'delete') {
        $aid = (int)$_POST['admin_id'];
        if ($aid !== (int)$_SESSION['admin_id']) {
            $pdo->prepare("DELETE FROM admin_users WHERE id=?")->execute([$aid]);
            flash('success','Admin deleted.');
        }
        header('Location: /admin/sub-admins.php'); exit;
    }
}
done:

$admins = $pdo->query("SELECT * FROM admin_users ORDER BY id ASC")->fetchAll();
$pageTitle = 'Sub-Admins';
?>
<?php include '../includes/header.php'; ?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div class="page-title mb-0"><i class="fa fa-user-shield me-2 text-danger"></i>Sub-Admin Management</div>
  <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addAdminModal"><i class="fa fa-plus me-1"></i>Add Admin</button>
</div>
<?php if ($error): ?><div class="alert alert-danger"><?= sanitize($error) ?></div><?php endif; ?>

<div class="card">
  <div class="table-responsive">
    <table class="table table-hover mb-0">
      <thead><tr><th>#</th><th>Username</th><th>Name</th><th>Email</th><th>Role</th><th>Status</th><th>Last Login</th><th>Actions</th></tr></thead>
      <tbody>
      <?php foreach ($admins as $a): ?>
      <tr>
        <td><?= $a['id'] ?></td>
        <td class="fw-bold"><?= sanitize($a['username']) ?></td>
        <td><?= sanitize($a['display_name']??'—') ?></td>
        <td><?= sanitize($a['email']) ?></td>
        <td><?= statusBadge($a['role']) ?></td>
        <td><?= statusBadge($a['status']) ?></td>
        <td class="small text-muted"><?= $a['last_login'] ? timeAgo($a['last_login']) : 'Never' ?></td>
        <td>
          <?php if ($a['id'] !== (int)$_SESSION['admin_id']): ?>
          <form method="POST" class="d-flex gap-1 align-items-center">
            <?= csrf_field() ?><input type="hidden" name="admin_id" value="<?= $a['id'] ?>">
            <button name="action" value="toggle" class="btn btn-xs btn-outline-warning"><?= $a['status']==='active'?'Suspend':'Activate' ?></button>
            <button name="action" value="delete" class="btn btn-xs btn-outline-danger" data-confirm="Delete this admin permanently?"><i class="fa fa-trash"></i></button>
          </form>
          <?php else: ?>
          <span class="badge bg-success">You</span>
          <?php endif; ?>
        </td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php include '../includes/footer.php'; ?>
<!-- Add Admin Modal -->
<div class="modal fade" id="addAdminModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title">Add Sub-Admin</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
  <form method="POST"><div class="modal-body">
    <?= csrf_field() ?><input type="hidden" name="action" value="add">
    <div class="row g-3">
      <div class="col-12"><label class="form-label">Display Name</label><input type="text" name="display_name" class="form-control"></div>
      <div class="col-md-6"><label class="form-label">Username *</label><input type="text" name="username" class="form-control" required></div>
      <div class="col-md-6"><label class="form-label">Email *</label><input type="email" name="email" class="form-control" required></div>
      <div class="col-md-6"><label class="form-label">Password *</label><input type="password" name="password" class="form-control" minlength="8" required></div>
      <div class="col-md-6"><label class="form-label">Role</label>
        <select name="role" class="form-select">
          <option value="admin">Admin</option>
          <option value="support">Support</option>
          <option value="super_admin">Super Admin</option>
        </select>
      </div>
    </div>
  </div>
  <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary fw-bold">Create Admin</button></div>
  </form>
</div></div></div>
