<?php
// ============================================================
//  admins.php — Manage Admin Accounts (Super Admin Only)
//  Place in: /admin/admins.php
// ============================================================
require_once 'includes/auth_check.php';
require_super_admin(); // Only super admins can access this page

$page_title = 'Manage Admins';

// ── Flash ─────────────────────────────────────────────────────
$flash_success = $_SESSION['flash_success'] ?? '';
$flash_error   = $_SESSION['flash_error']   ?? '';
unset($_SESSION['flash_success'], $_SESSION['flash_error']);

// ── CSRF ──────────────────────────────────────────────────────
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

$errors       = [];
$modal_open   = '';   // which modal to re-open on validation fail
$edit_admin   = null; // admin being edited

// ============================================================
//  HANDLE ALL POST ACTIONS
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (($_POST['csrf_token'] ?? '') !== $csrf) {
        $errors[] = 'Security token mismatch. Refresh and try again.';
    } else {

        $action = $_POST['action'] ?? '';

        // ── ADD NEW ADMIN ─────────────────────────────────────
        if ($action === 'add_admin') {
            $full_name = trim($_POST['full_name'] ?? '');
            $username  = trim($_POST['username']  ?? '');
            $email     = trim($_POST['email']     ?? '');
            $phone     = trim($_POST['phone']     ?? '');
            $role      = in_array($_POST['role'] ?? '', ['admin','super_admin']) ? $_POST['role'] : 'admin';
            $password  = $_POST['password']  ?? '';
            $confirm   = $_POST['confirm_password'] ?? '';

            if (empty($full_name))                              $errors[] = 'Full name is required.';
            if (empty($username))                              $errors[] = 'Username is required.';
            if (!filter_var($email, FILTER_VALIDATE_EMAIL))    $errors[] = 'Valid email is required.';
            if (strlen($password) < 8)                         $errors[] = 'Password must be at least 8 characters.';
            if (!preg_match('/[A-Z]/', $password))             $errors[] = 'Password needs an uppercase letter.';
            if (!preg_match('/[0-9]/', $password))             $errors[] = 'Password needs a number.';
            if (!preg_match('/[^A-Za-z0-9]/', $password))     $errors[] = 'Password needs a special character.';
            if ($password !== $confirm)                         $errors[] = 'Passwords do not match.';

            if (empty($errors)) {
                $dup_u = db_fetch_one("SELECT id FROM admins WHERE username=?", [$username]);
                $dup_e = db_fetch_one("SELECT id FROM admins WHERE email=?",    [$email]);
                if ($dup_u) $errors[] = "Username '@{$username}' is already taken.";
                if ($dup_e) $errors[] = "Email '{$email}' is already in use.";
            }

            if (empty($errors)) {
                $hash = password_hash($password, PASSWORD_BCRYPT);
                db_execute(
                    "INSERT INTO admins (full_name, username, email, phone, password_hash, role, status)
                     VALUES (?, ?, ?, ?, ?, ?, 'active')",
                    [$full_name, $username, $email, $phone ?: null, $hash, $role]
                );
                $new_id = db_last_id();
                db_execute(
                    "INSERT INTO activity_log (admin_id, action, target_type, target_id, target_name, details, ip_address)
                     VALUES (?, 'created_admin', 'admin', ?, ?, ?, ?)",
                    [$current_admin['id'], $new_id, $full_name,
                     "Created {$role} account for {$full_name} ({$email})",
                     $_SERVER['REMOTE_ADDR']]
                );
                $_SESSION['flash_success'] = "Admin account created for {$full_name}.";
                header('Location: admins.php');
                exit;
            }
            $modal_open = 'addModal';
        }

        // ── EDIT ADMIN ────────────────────────────────────────
        if ($action === 'edit_admin') {
            $target_id = (int)($_POST['admin_id'] ?? 0);
            $full_name = trim($_POST['full_name'] ?? '');
            $username  = trim($_POST['username']  ?? '');
            $email     = trim($_POST['email']     ?? '');
            $phone     = trim($_POST['phone']     ?? '');
            $role      = in_array($_POST['role'] ?? '', ['admin','super_admin']) ? $_POST['role'] : 'admin';
            $status    = in_array($_POST['status'] ?? '', ['active','inactive']) ? $_POST['status'] : 'active';

            // Cannot demote yourself or change your own role
            if ($target_id === $current_admin['id'] && $role !== $current_admin['role']) {
                $errors[] = 'You cannot change your own role.';
            }

            if (empty($full_name)) $errors[] = 'Full name is required.';
            if (empty($username))  $errors[] = 'Username is required.';
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Valid email is required.';

            if (empty($errors)) {
                $dup_u = db_fetch_one("SELECT id FROM admins WHERE username=? AND id!=?", [$username, $target_id]);
                $dup_e = db_fetch_one("SELECT id FROM admins WHERE email=? AND id!=?",    [$email,    $target_id]);
                if ($dup_u) $errors[] = "Username '@{$username}' is already taken.";
                if ($dup_e) $errors[] = "Email '{$email}' is already in use.";
            }

            if (empty($errors)) {
                $target = db_fetch_one("SELECT * FROM admins WHERE id=?", [$target_id]);
                db_execute(
                    "UPDATE admins SET full_name=?, username=?, email=?, phone=?, role=?, status=? WHERE id=?",
                    [$full_name, $username, $email, $phone ?: null, $role, $status, $target_id]
                );
                db_execute(
                    "INSERT INTO activity_log (admin_id, action, target_type, target_id, target_name, details, ip_address)
                     VALUES (?, 'edited_admin', 'admin', ?, ?, ?, ?)",
                    [$current_admin['id'], $target_id, $full_name,
                     "Updated admin account: role={$role}, status={$status}",
                     $_SERVER['REMOTE_ADDR']]
                );
                // Update own session if editing self
                if ($target_id === $current_admin['id']) {
                    $_SESSION['admin_name']     = $full_name;
                    $_SESSION['admin_username'] = $username;
                }
                $_SESSION['flash_success'] = "Admin '{$full_name}' updated successfully.";
                header('Location: admins.php');
                exit;
            }
            $modal_open = 'editModal';
            $edit_admin = db_fetch_one("SELECT * FROM admins WHERE id=?", [$target_id]);
        }

        // ── RESET ADMIN PASSWORD ──────────────────────────────
        if ($action === 'reset_admin_password') {
            $target_id  = (int)($_POST['admin_id'] ?? 0);
            $new_pw     = $_POST['new_password']      ?? '';
            $confirm_pw = $_POST['confirm_password']  ?? '';

            if ($target_id === $current_admin['id']) {
                // Use the profile page for self
                $_SESSION['flash_error'] = 'Use the Profile page to change your own password.';
                header('Location: admins.php');
                exit;
            }

            if (strlen($new_pw) < 8)                    $errors[] = 'Password must be at least 8 characters.';
            if (!preg_match('/[A-Z]/', $new_pw))         $errors[] = 'Needs an uppercase letter.';
            if (!preg_match('/[0-9]/', $new_pw))         $errors[] = 'Needs a number.';
            if ($new_pw !== $confirm_pw)                  $errors[] = 'Passwords do not match.';

            if (empty($errors)) {
                $hash   = password_hash($new_pw, PASSWORD_BCRYPT);
                $target = db_fetch_one("SELECT full_name FROM admins WHERE id=?", [$target_id]);
                db_execute("UPDATE admins SET password_hash=? WHERE id=?", [$hash, $target_id]);
                db_execute(
                    "INSERT INTO activity_log (admin_id, action, target_type, target_id, target_name, details, ip_address)
                     VALUES (?, 'reset_admin_password', 'admin', ?, ?, ?, ?)",
                    [$current_admin['id'], $target_id, $target['full_name'],
                     "Super admin reset password for {$target['full_name']}",
                     $_SERVER['REMOTE_ADDR']]
                );
                $_SESSION['flash_success'] = "Password reset for {$target['full_name']}.";
                header('Location: admins.php');
                exit;
            }
            $modal_open = 'pwModal';
            $edit_admin = db_fetch_one("SELECT * FROM admins WHERE id=?", [$target_id]);
        }

        // ── TOGGLE STATUS ─────────────────────────────────────
        if ($action === 'toggle_status') {
            $target_id = (int)($_POST['admin_id'] ?? 0);

            if ($target_id === $current_admin['id']) {
                $_SESSION['flash_error'] = 'You cannot deactivate your own account.';
                header('Location: admins.php'); exit;
            }

            $target     = db_fetch_one("SELECT * FROM admins WHERE id=?", [$target_id]);
            $new_status = $target['status'] === 'active' ? 'inactive' : 'active';

            db_execute("UPDATE admins SET status=? WHERE id=?", [$new_status, $target_id]);
            db_execute(
                "INSERT INTO activity_log (admin_id, action, target_type, target_id, target_name, details, ip_address)
                 VALUES (?, 'toggled_admin_status', 'admin', ?, ?, ?, ?)",
                [$current_admin['id'], $target_id, $target['full_name'],
                 "Status changed to {$new_status}", $_SERVER['REMOTE_ADDR']]
            );
            $_SESSION['flash_success'] = "{$target['full_name']} is now {$new_status}.";
            header('Location: admins.php'); exit;
        }

        // ── DELETE ADMIN ──────────────────────────────────────
        if ($action === 'delete_admin') {
            $target_id = (int)($_POST['admin_id'] ?? 0);

            if ($target_id === $current_admin['id']) {
                $_SESSION['flash_error'] = 'You cannot delete your own account.';
                header('Location: admins.php'); exit;
            }

            // Must keep at least one super admin
            $super_count = db_fetch_one(
                "SELECT COUNT(*) AS c FROM admins WHERE role='super_admin' AND id!=?",
                [$target_id]
            )['c'];
            $target = db_fetch_one("SELECT * FROM admins WHERE id=?", [$target_id]);

            if ($target['role'] === 'super_admin' && $super_count < 1) {
                $_SESSION['flash_error'] = 'Cannot delete the last Super Admin account.';
                header('Location: admins.php'); exit;
            }

            db_execute("DELETE FROM admins WHERE id=?", [$target_id]);
            db_execute(
                "INSERT INTO activity_log (admin_id, action, target_type, target_id, target_name, details, ip_address)
                 VALUES (?, 'deleted_admin', 'admin', ?, ?, ?, ?)",
                [$current_admin['id'], $target_id, $target['full_name'],
                 "Deleted admin account: {$target['full_name']} ({$target['email']})",
                 $_SERVER['REMOTE_ADDR']]
            );
            $_SESSION['flash_success'] = "Admin '{$target['full_name']}' deleted.";
            header('Location: admins.php'); exit;
        }
    }
}

// ── Fetch all admins ──────────────────────────────────────────
$all_admins = db_fetch_all(
    "SELECT a.*,
            (SELECT COUNT(*) FROM activity_log al WHERE al.admin_id = a.id) AS action_count
     FROM admins a
     ORDER BY
       FIELD(a.role, 'super_admin', 'admin'),
       a.created_at ASC"
);

$total_admins  = count($all_admins);
$super_count   = count(array_filter($all_admins, fn($a) => $a['role'] === 'super_admin'));
$active_count  = count(array_filter($all_admins, fn($a) => $a['status'] === 'active'));

require_once 'includes/header.php';
?>

<style>
/* ════════════════════════════════════════════════
   ADMINS PAGE STYLES
════════════════════════════════════════════════ */

/* ── Admin Cards Grid ──────────────────────────────────────── */
.admins-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 28px;
}

.admin-card {
  background: var(--glass-bg);
  border: 1px solid var(--glass-border);
  border-radius: var(--radius-lg);
  overflow: hidden;
  position: relative;
  transition: transform var(--transition), border-color var(--transition), box-shadow var(--transition);
  animation: fadeUp .5s ease both;
}

.admin-card:hover {
  transform: translateY(-4px);
  border-color: var(--glass-border-lg);
  box-shadow: 0 12px 40px rgba(0,0,0,.35);
}

/* Glowing left border by role */
.admin-card.super::before {
  content: '';
  position: absolute;
  left: 0; top: 0; bottom: 0;
  width: 3px;
  background: linear-gradient(to bottom, var(--pink), var(--accent-2));
  border-radius: 3px 0 0 3px;
}

.admin-card.regular::before {
  content: '';
  position: absolute;
  left: 0; top: 0; bottom: 0;
  width: 3px;
  background: linear-gradient(to bottom, var(--accent), var(--teal));
  border-radius: 3px 0 0 3px;
}

.admin-card.inactive { opacity: .6; filter: grayscale(.3); }

/* Card top section */
.ac-top {
  padding: 22px 22px 16px;
  display: flex;
  align-items: flex-start;
  gap: 14px;
}

.ac-avatar-wrap { position: relative; flex-shrink: 0; }

.ac-avatar {
  width: 56px; height: 56px;
  border-radius: 50%;
  object-fit: cover;
  border: 2.5px solid var(--glass-border-lg);
  display: block;
}

.ac-status-dot {
  position: absolute;
  bottom: 1px; right: 1px;
  width: 12px; height: 12px;
  border-radius: 50%;
  border: 2px solid var(--bg-deep);
}
.ac-status-dot.active   { background: var(--success); }
.ac-status-dot.inactive { background: var(--text-muted); }

.ac-info { flex: 1; min-width: 0; }
.ac-name {
  font-family: 'Syne', sans-serif;
  font-size: 15px; font-weight: 700;
  color: var(--text-primary);
  white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.ac-username { font-size: 12px; color: var(--accent-2); margin-top: 1px; }
.ac-email    { font-size: 11.5px; color: var(--text-muted); margin-top: 4px;
               white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

.ac-role-badge {
  flex-shrink: 0;
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 10.5px;
  font-weight: 700;
  letter-spacing: .4px;
}
.role-super { background:linear-gradient(135deg,rgba(244,114,182,.2),rgba(167,139,250,.2)); border:1px solid rgba(244,114,182,.35); color:var(--pink); }
.role-admin { background:rgba(108,99,255,.15); border:1px solid rgba(108,99,255,.3); color:var(--accent-2); }

/* Stats strip inside card */
.ac-stats {
  display: flex;
  border-top: 1px solid var(--glass-border);
  border-bottom: 1px solid var(--glass-border);
}
.ac-stat {
  flex: 1;
  text-align: center;
  padding: 10px 8px;
  border-right: 1px solid var(--glass-border);
}
.ac-stat:last-child { border-right: none; }
.ac-stat-val  { font-family:'Syne',sans-serif; font-size:16px; font-weight:800; color:var(--text-primary); line-height:1; }
.ac-stat-lbl  { font-size:10px; color:var(--text-muted); margin-top:3px; font-weight:500; }

/* Card actions */
.ac-actions {
  display: flex;
  gap: 6px;
  padding: 14px 18px;
  flex-wrap: wrap;
}

/* YOU badge */
.you-badge {
  position: absolute;
  top: 14px; right: 14px;
  background: rgba(108,99,255,.25);
  border: 1px solid rgba(108,99,255,.4);
  color: var(--accent-2);
  font-size: 10px;
  font-weight: 700;
  letter-spacing: 1px;
  padding: 2px 8px;
  border-radius: 20px;
}

/* ── Modals ────────────────────────────────────────────────── */
.modal-overlay {
  position: fixed; inset: 0; z-index: 300;
  background: rgba(0,0,0,.7);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  display: none;
  align-items: center;
  justify-content: center;
  padding: 20px;
  animation: fadeIn .2s ease;
}
.modal-overlay.open { display: flex; }

.modal {
  width: 100%;
  max-width: 520px;
  max-height: 90vh;
  overflow-y: auto;
  background: rgba(10,12,32,.97);
  border: 1px solid var(--glass-border-lg);
  border-radius: var(--radius-xl);
  backdrop-filter: blur(32px);
  -webkit-backdrop-filter: blur(32px);
  box-shadow: 0 40px 100px rgba(0,0,0,.7), 0 0 0 1px rgba(255,255,255,.04) inset;
  animation: modalIn .3s cubic-bezier(.22,1,.36,1) both;
  scrollbar-width: thin;
  scrollbar-color: rgba(108,99,255,.3) transparent;
}

@keyframes modalIn {
  from { opacity:0; transform:scale(.94) translateY(20px); }
  to   { opacity:1; transform:scale(1)   translateY(0); }
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 22px 24px 18px;
  border-bottom: 1px solid var(--glass-border);
  position: sticky; top: 0;
  background: rgba(10,12,32,.98);
  z-index: 10;
  border-radius: var(--radius-xl) var(--radius-xl) 0 0;
}

.modal-title-wrap { display:flex; align-items:center; gap:12px; }
.modal-icon {
  width: 40px; height: 40px;
  border-radius: 12px;
  display: grid; place-items: center;
  font-size: 16px;
  flex-shrink: 0;
}
.modal-title    { font-family:'Syne',sans-serif; font-size:17px; font-weight:800; color:var(--text-primary); }
.modal-subtitle { font-size:12px; color:var(--text-muted); margin-top:1px; }

.modal-close {
  width: 34px; height: 34px;
  border-radius: 10px;
  background: var(--glass-bg);
  border: 1px solid var(--glass-border);
  color: var(--text-secondary);
  font-size: 14px;
  display: grid; place-items: center;
  cursor: pointer;
  transition: all var(--transition);
  flex-shrink: 0;
}
.modal-close:hover { background:var(--danger-bg); border-color:var(--danger-border); color:var(--danger); }

.modal-body   { padding: 22px 24px; }
.modal-footer {
  display: flex; align-items:center; justify-content:flex-end; gap:10px;
  padding: 16px 24px 22px;
  border-top: 1px solid var(--glass-border);
}

/* Form inside modal */
.modal .form-row-2 { display:grid; grid-template-columns:1fr 1fr; gap:14px; }
.modal .form-group { margin-bottom:16px; }
.modal .form-group:last-child { margin-bottom:0; }

/* Password strength */
.pw-strength { height:4px; background:rgba(255,255,255,.06); border-radius:10px; overflow:hidden; margin-top:8px; }
.pw-bar      { height:100%; border-radius:10px; width:0; transition:width .3s,background .3s; }
.pw-rules    { display:grid; grid-template-columns:1fr 1fr; gap:5px; margin-top:10px; }
.pw-rule     { display:flex; align-items:center; gap:6px; font-size:11.5px; color:var(--text-muted); transition:color .2s; }
.pw-rule.pass{ color:var(--success); }
.pw-rule i   { font-size:10px; width:12px; text-align:center; }

/* Ptoggle */
.ptoggle {
  position:absolute; right:12px; top:50%; transform:translateY(-50%);
  background:none; border:none; color:var(--text-secondary);
  cursor:pointer; font-size:13px; padding:4px; transition:color .2s;
}
.ptoggle:hover { color:var(--accent-2); }

/* ── Empty state ───────────────────────────────────────────── */
.empty-admins {
  text-align:center; padding:60px 20px;
}
.empty-admins i { font-size:48px; opacity:.2; color:var(--text-muted); display:block; margin-bottom:16px; }
.empty-admins h3{ font-family:'Syne',sans-serif; font-size:20px; color:var(--text-secondary); }

/* ── Stats mini cards ──────────────────────────────────────── */
.admin-overview {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 28px;
}

.ov-card {
  background: var(--glass-bg);
  border: 1px solid var(--glass-border);
  border-radius: var(--radius-lg);
  padding: 18px 20px;
  display: flex;
  align-items: center;
  gap: 14px;
  animation: fadeUp .5s ease both;
  transition: transform var(--transition);
}
.ov-card:hover { transform: translateY(-2px); }

.ov-icon {
  width: 44px; height: 44px;
  border-radius: 13px;
  display: grid; place-items: center;
  font-size: 18px;
  flex-shrink: 0;
}

.ov-val   { font-family:'Syne',sans-serif; font-size:28px; font-weight:800; color:var(--text-primary); letter-spacing:-1px; line-height:1; }
.ov-label { font-size:12px; color:var(--text-muted); margin-top:3px; font-weight:500; }

@media (max-width:900px) {
  .admins-grid    { grid-template-columns:1fr; }
  .admin-overview { grid-template-columns:1fr 1fr 1fr; }
  .modal .form-row-2 { grid-template-columns:1fr; }
}
@media (max-width:600px) {
  .admin-overview { grid-template-columns:1fr; }
  .pw-rules       { grid-template-columns:1fr; }
}
</style>

<!-- Flash -->
<?php if ($flash_success): ?>
  <div class="flash-alert flash-success">
    <i class="fas fa-circle-check"></i><span><?= htmlspecialchars($flash_success) ?></span>
  </div>
<?php endif; ?>
<?php if ($flash_error): ?>
  <div class="flash-alert flash-error">
    <i class="fas fa-circle-exclamation"></i><span><?= htmlspecialchars($flash_error) ?></span>
  </div>
<?php endif; ?>

<?php if (!empty($errors)): ?>
  <div class="flash-alert flash-error" style="flex-direction:column;align-items:flex-start;gap:4px;">
    <div style="display:flex;gap:10px;align-items:center;font-weight:600;">
      <i class="fas fa-circle-exclamation"></i> Please fix the following:
    </div>
    <ul style="list-style:none;padding-left:24px;margin-top:4px;">
      <?php foreach ($errors as $e): ?>
        <li style="font-size:13px;color:#fca5a5;padding:2px 0;">· <?= htmlspecialchars($e) ?></li>
      <?php endforeach; ?>
    </ul>
  </div>
<?php endif; ?>

<!-- Page Header -->
<div class="page-header">
  <div class="page-header-left">
    <h1>Manage <span style="color:var(--accent-2)">Admins</span></h1>
    <p>Add, edit, and control all admin accounts. Super Admin access only.</p>
  </div>
  <div class="page-header-right">
    <button class="btn btn-primary" onclick="openModal('addModal')">
      <i class="fas fa-user-plus"></i> Add New Admin
    </button>
  </div>
</div>

<!-- Overview Strip -->
<div class="admin-overview">
  <div class="ov-card anim-delay-1">
    <div class="ov-icon" style="background:rgba(108,99,255,.15);color:var(--accent-2);">
      <i class="fas fa-users-gear"></i>
    </div>
    <div>
      <div class="ov-val"><?= $total_admins ?></div>
      <div class="ov-label">Total Admins</div>
    </div>
  </div>
  <div class="ov-card anim-delay-2">
    <div class="ov-icon" style="background:rgba(244,114,182,.12);color:var(--pink);">
      <i class="fas fa-crown"></i>
    </div>
    <div>
      <div class="ov-val"><?= $super_count ?></div>
      <div class="ov-label">Super Admins</div>
    </div>
  </div>
  <div class="ov-card anim-delay-3">
    <div class="ov-icon" style="background:rgba(52,211,153,.12);color:var(--success);">
      <i class="fas fa-circle-check"></i>
    </div>
    <div>
      <div class="ov-val"><?= $active_count ?></div>
      <div class="ov-label">Active Admins</div>
    </div>
  </div>
</div>

<!-- ── Admin Cards ──────────────────────────────────────────── -->
<?php if (empty($all_admins)): ?>
  <div class="glass-card empty-admins">
    <i class="fas fa-users-gear"></i>
    <h3>No admin accounts found</h3>
  </div>
<?php else: ?>
<div class="admins-grid">
  <?php foreach ($all_admins as $i => $adm): ?>
  <?php $is_self = ($adm['id'] == $current_admin['id']); ?>
  <div class="admin-card <?= $adm['role']==='super_admin'?'super':'regular' ?> <?= $adm['status']==='inactive'?'inactive':'' ?>"
       style="animation-delay:<?= $i * 0.06 ?>s;">

    <?php if ($is_self): ?>
      <span class="you-badge">YOU</span>
    <?php endif; ?>

    <!-- Top -->
    <div class="ac-top">
      <div class="ac-avatar-wrap">
        <img src="assets/images/avatars/<?= htmlspecialchars($adm['avatar'] ?? 'logo.png') ?>"
             onerror="this.src='assets/images/logo.png'"
             class="ac-avatar" alt="" />
        <span class="ac-status-dot <?= $adm['status'] ?>"></span>
      </div>
      <div class="ac-info">
        <div class="ac-name"><?= htmlspecialchars($adm['full_name']) ?></div>
        <div class="ac-username">@<?= htmlspecialchars($adm['username']) ?></div>
        <div class="ac-email"><?= htmlspecialchars($adm['email']) ?></div>
      </div>
      <span class="ac-role-badge <?= $adm['role']==='super_admin'?'role-super':'role-admin' ?>">
        <i class="fas fa-<?= $adm['role']==='super_admin'?'crown':'shield-halved' ?>"></i>
        <?= $adm['role']==='super_admin'?'Super':'Admin' ?>
      </span>
    </div>

    <!-- Stats -->
    <div class="ac-stats">
      <div class="ac-stat">
        <div class="ac-stat-val"><?= number_format($adm['action_count']) ?></div>
        <div class="ac-stat-lbl">Actions</div>
      </div>
      <div class="ac-stat">
        <div class="ac-stat-val">
          <?= $adm['last_login'] ? date('d M', strtotime($adm['last_login'])) : '—' ?>
        </div>
        <div class="ac-stat-lbl">Last Login</div>
      </div>
      <div class="ac-stat">
        <div class="ac-stat-val">
          <?= floor((time()-strtotime($adm['created_at']))/86400) ?>d
        </div>
        <div class="ac-stat-lbl">Member</div>
      </div>
    </div>

    <!-- Actions -->
    <div class="ac-actions">
      <!-- Edit -->
      <button class="btn btn-glass btn-sm"
              onclick='openEditModal(<?= json_encode($adm) ?>)'
              title="Edit admin">
        <i class="fas fa-pen-to-square"></i> Edit
      </button>

      <!-- Reset PW (not for self) -->
      <?php if (!$is_self): ?>
        <button class="btn btn-glass btn-sm"
                onclick='openPwModal(<?= json_encode($adm) ?>)'
                title="Reset password">
          <i class="fas fa-key"></i>
        </button>
      <?php endif; ?>

      <!-- Toggle status (not for self) -->
      <?php if (!$is_self): ?>
        <form method="POST" action="" style="display:inline;">
          <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
          <input type="hidden" name="action"   value="toggle_status">
          <input type="hidden" name="admin_id" value="<?= $adm['id'] ?>">
          <button type="submit" class="btn btn-sm <?= $adm['status']==='active'?'btn-glass':'btn-success' ?>"
                  onclick="return confirm('<?= $adm['status']==='active'?'Deactivate':'Activate' ?> <?= addslashes(htmlspecialchars($adm['full_name'])) ?>?')"
                  title="<?= $adm['status']==='active'?'Deactivate':'Activate' ?>">
            <i class="fas fa-<?= $adm['status']==='active'?'toggle-off':'toggle-on' ?>"></i>
          </button>
        </form>
      <?php endif; ?>

      <!-- Delete (not for self) -->
      <?php if (!$is_self): ?>
        <form method="POST" action="" style="display:inline;margin-left:auto;">
          <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
          <input type="hidden" name="action"   value="delete_admin">
          <input type="hidden" name="admin_id" value="<?= $adm['id'] ?>">
          <button type="submit" class="btn btn-danger btn-sm btn-icon"
                  onclick="return confirm('Permanently delete admin \'<?= addslashes(htmlspecialchars($adm['full_name'])) ?>\'?\n\nThis cannot be undone.')"
                  title="Delete admin">
            <i class="fas fa-trash"></i>
          </button>
        </form>
      <?php endif; ?>
    </div>

  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>


<!-- ══════════════════════════════════════════════════════════
     MODAL: ADD NEW ADMIN
══════════════════════════════════════════════════════════ -->
<div class="modal-overlay <?= $modal_open==='addModal'?'open':'' ?>" id="addModal">
  <div class="modal">
    <div class="modal-header">
      <div class="modal-title-wrap">
        <div class="modal-icon" style="background:rgba(108,99,255,.15);color:var(--accent-2);">
          <i class="fas fa-user-plus"></i>
        </div>
        <div>
          <div class="modal-title">Add New Admin</div>
          <div class="modal-subtitle">Create a new admin or super admin account</div>
        </div>
      </div>
      <button class="modal-close" onclick="closeModal('addModal')">
        <i class="fas fa-xmark"></i>
      </button>
    </div>

    <form method="POST" action="" novalidate>
      <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
      <input type="hidden" name="action" value="add_admin">

      <div class="modal-body">
        <div class="form-row-2">
          <div class="form-group">
            <label class="form-label">Full Name *</label>
            <input type="text" name="full_name" class="form-control"
                   value="<?= $modal_open==='addModal'?htmlspecialchars($_POST['full_name']??''):'' ?>"
                   placeholder="Jane Smith" required />
          </div>
          <div class="form-group">
            <label class="form-label">Username *</label>
            <div style="position:relative;">
              <span style="position:absolute;left:14px;top:50%;transform:translateY(-50%);color:var(--text-muted);">@</span>
              <input type="text" name="username" class="form-control" style="padding-left:28px;"
                     value="<?= $modal_open==='addModal'?htmlspecialchars($_POST['username']??''):'' ?>"
                     placeholder="janesmith" required />
            </div>
          </div>
        </div>

        <div class="form-row-2">
          <div class="form-group">
            <label class="form-label">Email Address *</label>
            <input type="email" name="email" class="form-control"
                   value="<?= $modal_open==='addModal'?htmlspecialchars($_POST['email']??''):'' ?>"
                   placeholder="jane@admin.com" required />
          </div>
          <div class="form-group">
            <label class="form-label">Phone</label>
            <input type="tel" name="phone" class="form-control"
                   value="<?= $modal_open==='addModal'?htmlspecialchars($_POST['phone']??''):'' ?>"
                   placeholder="+1 555 000 0000" />
          </div>
        </div>

        <div class="form-group">
          <label class="form-label">Role *</label>
          <select name="role" class="form-control">
            <option value="admin"       <?= ($modal_open==='addModal'&&($_POST['role']??'')==='admin')?'selected':'' ?>>
              Admin — standard access
            </option>
            <option value="super_admin" <?= ($modal_open==='addModal'&&($_POST['role']??'')==='super_admin')?'selected':'' ?>>
              Super Admin — full access
            </option>
          </select>
          <div style="font-size:11px;color:var(--text-muted);margin-top:5px;">
            <i class="fas fa-triangle-exclamation" style="color:var(--warning);"></i>
            Super Admins can manage other admins and access all settings.
          </div>
        </div>

        <div style="height:1px;background:var(--glass-border);margin:4px 0 16px;"></div>

        <div class="form-group">
          <label class="form-label">Password *</label>
          <div style="position:relative;">
            <input type="password" name="password" id="addPw" class="form-control"
                   style="padding-right:44px;" placeholder="Min 8 chars + uppercase + number + symbol" />
            <button type="button" class="ptoggle" onclick="togglePw('addPw',this)">
              <i class="fas fa-eye"></i>
            </button>
          </div>
          <div class="pw-strength"><div class="pw-bar" id="addPwBar"></div></div>
          <div class="pw-rules">
            <div class="pw-rule" id="a-len">  <i class="fas fa-circle"></i> Min 8 chars</div>
            <div class="pw-rule" id="a-up">   <i class="fas fa-circle"></i> Uppercase</div>
            <div class="pw-rule" id="a-num">  <i class="fas fa-circle"></i> Number</div>
            <div class="pw-rule" id="a-spec"> <i class="fas fa-circle"></i> Special char</div>
          </div>
        </div>

        <div class="form-group">
          <label class="form-label">Confirm Password *</label>
          <div style="position:relative;">
            <input type="password" name="confirm_password" id="addPwConfirm" class="form-control"
                   style="padding-right:44px;" placeholder="Repeat password" />
            <button type="button" class="ptoggle" onclick="togglePw('addPwConfirm',this)">
              <i class="fas fa-eye"></i>
            </button>
          </div>
          <div id="addMatchMsg" style="font-size:12px;margin-top:6px;min-height:16px;"></div>
        </div>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-glass" onclick="closeModal('addModal')">Cancel</button>
        <button type="submit" class="btn btn-primary">
          <i class="fas fa-user-plus"></i> Create Admin
        </button>
      </div>
    </form>
  </div>
</div>


<!-- ══════════════════════════════════════════════════════════
     MODAL: EDIT ADMIN
══════════════════════════════════════════════════════════ -->
<div class="modal-overlay <?= $modal_open==='editModal'?'open':'' ?>" id="editModal">
  <div class="modal">
    <div class="modal-header">
      <div class="modal-title-wrap">
        <div class="modal-icon" style="background:rgba(45,212,191,.15);color:var(--teal);">
          <i class="fas fa-pen-to-square"></i>
        </div>
        <div>
          <div class="modal-title">Edit Admin</div>
          <div class="modal-subtitle" id="editModalSubtitle">Update admin account details</div>
        </div>
      </div>
      <button class="modal-close" onclick="closeModal('editModal')">
        <i class="fas fa-xmark"></i>
      </button>
    </div>

    <form method="POST" action="" novalidate>
      <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
      <input type="hidden" name="action"   value="edit_admin">
      <input type="hidden" name="admin_id" id="editAdminId" value="<?= $modal_open==='editModal'?htmlspecialchars($_POST['admin_id']??''):'' ?>">

      <div class="modal-body">
        <div class="form-row-2">
          <div class="form-group">
            <label class="form-label">Full Name *</label>
            <input type="text" name="full_name" id="editFullName" class="form-control"
                   value="<?= $modal_open==='editModal'?htmlspecialchars($_POST['full_name']??''):'' ?>"
                   placeholder="Jane Smith" required />
          </div>
          <div class="form-group">
            <label class="form-label">Username *</label>
            <div style="position:relative;">
              <span style="position:absolute;left:14px;top:50%;transform:translateY(-50%);color:var(--text-muted);">@</span>
              <input type="text" name="username" id="editUsername" class="form-control" style="padding-left:28px;"
                     value="<?= $modal_open==='editModal'?htmlspecialchars($_POST['username']??''):'' ?>"
                     placeholder="janesmith" required />
            </div>
          </div>
        </div>

        <div class="form-row-2">
          <div class="form-group">
            <label class="form-label">Email Address *</label>
            <input type="email" name="email" id="editEmail" class="form-control"
                   value="<?= $modal_open==='editModal'?htmlspecialchars($_POST['email']??''):'' ?>"
                   placeholder="jane@admin.com" required />
          </div>
          <div class="form-group">
            <label class="form-label">Phone</label>
            <input type="tel" name="phone" id="editPhone" class="form-control"
                   value="<?= $modal_open==='editModal'?htmlspecialchars($_POST['phone']??''):'' ?>"
                   placeholder="+1 555 000 0000" />
          </div>
        </div>

        <div class="form-row-2">
          <div class="form-group">
            <label class="form-label">Role *</label>
            <select name="role" id="editRole" class="form-control">
              <option value="admin">Admin</option>
              <option value="super_admin">Super Admin</option>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">Status *</label>
            <select name="status" id="editStatus" class="form-control">
              <option value="active">Active</option>
              <option value="inactive">Inactive</option>
            </select>
          </div>
        </div>

        <div id="editSelfNote" style="display:none;" class="flash-alert flash-warning">
          <i class="fas fa-triangle-exclamation"></i>
          <span>You are editing your own account. Role changes are restricted.</span>
        </div>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-glass" onclick="closeModal('editModal')">Cancel</button>
        <button type="submit" class="btn btn-primary">
          <i class="fas fa-floppy-disk"></i> Save Changes
        </button>
      </div>
    </form>
  </div>
</div>


<!-- ══════════════════════════════════════════════════════════
     MODAL: RESET PASSWORD
══════════════════════════════════════════════════════════ -->
<div class="modal-overlay <?= $modal_open==='pwModal'?'open':'' ?>" id="pwModal">
  <div class="modal">
    <div class="modal-header">
      <div class="modal-title-wrap">
        <div class="modal-icon" style="background:rgba(251,191,36,.15);color:var(--warning);">
          <i class="fas fa-key"></i>
        </div>
        <div>
          <div class="modal-title">Reset Password</div>
          <div class="modal-subtitle" id="pwModalSubtitle">Set a new password for this admin</div>
        </div>
      </div>
      <button class="modal-close" onclick="closeModal('pwModal')">
        <i class="fas fa-xmark"></i>
      </button>
    </div>

    <form method="POST" action="" novalidate>
      <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
      <input type="hidden" name="action"   value="reset_admin_password">
      <input type="hidden" name="admin_id" id="pwAdminId"
             value="<?= $modal_open==='pwModal'?htmlspecialchars($_POST['admin_id']??''):'' ?>">

      <div class="modal-body">
        <div class="flash-alert flash-warning" style="margin-bottom:18px;">
          <i class="fas fa-triangle-exclamation"></i>
          <span>This will immediately change the admin's password. Inform them separately.</span>
        </div>

        <div class="form-group">
          <label class="form-label">New Password *</label>
          <div style="position:relative;">
            <input type="password" name="new_password" id="rsPw" class="form-control"
                   style="padding-right:44px;" placeholder="Min 8 chars" />
            <button type="button" class="ptoggle" onclick="togglePw('rsPw',this)">
              <i class="fas fa-eye"></i>
            </button>
          </div>
          <div class="pw-strength"><div class="pw-bar" id="rsPwBar"></div></div>
          <div class="pw-rules">
            <div class="pw-rule" id="r-len">  <i class="fas fa-circle"></i> Min 8 chars</div>
            <div class="pw-rule" id="r-up">   <i class="fas fa-circle"></i> Uppercase</div>
            <div class="pw-rule" id="r-num">  <i class="fas fa-circle"></i> Number</div>
            <div class="pw-rule" id="r-spec"> <i class="fas fa-circle"></i> Special char</div>
          </div>
        </div>

        <div class="form-group">
          <label class="form-label">Confirm Password *</label>
          <div style="position:relative;">
            <input type="password" name="confirm_password" id="rsPwConfirm" class="form-control"
                   style="padding-right:44px;" placeholder="Repeat password" />
            <button type="button" class="ptoggle" onclick="togglePw('rsPwConfirm',this)">
              <i class="fas fa-eye"></i>
            </button>
          </div>
          <div id="rsMatchMsg" style="font-size:12px;margin-top:6px;min-height:16px;"></div>
        </div>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-glass" onclick="closeModal('pwModal')">Cancel</button>
        <button type="submit" class="btn btn-primary">
          <i class="fas fa-key"></i> Reset Password
        </button>
      </div>
    </form>
  </div>
</div>

<?php
$current_admin_id_js = (int)$current_admin['id'];
$extra_scripts = <<<JS
<script>
const CURRENT_ADMIN_ID = {$current_admin_id_js};

// ── Modal open/close ────────────────────────────────────────
function openModal(id) {
  document.getElementById(id).classList.add('open');
  document.body.style.overflow = 'hidden';
}
function closeModal(id) {
  document.getElementById(id).classList.remove('open');
  document.body.style.overflow = '';
}

// Close on overlay click
document.querySelectorAll('.modal-overlay').forEach(overlay => {
  overlay.addEventListener('click', function(e) {
    if (e.target === this) closeModal(this.id);
  });
});

// Close on Escape
document.addEventListener('keydown', e => {
  if (e.key === 'Escape') {
    document.querySelectorAll('.modal-overlay.open').forEach(m => {
      closeModal(m.id);
    });
  }
});

// ── Fill Edit Modal ─────────────────────────────────────────
function openEditModal(admin) {
  document.getElementById('editAdminId').value    = admin.id;
  document.getElementById('editFullName').value   = admin.full_name;
  document.getElementById('editUsername').value   = admin.username;
  document.getElementById('editEmail').value      = admin.email;
  document.getElementById('editPhone').value      = admin.phone ?? '';
  document.getElementById('editRole').value       = admin.role;
  document.getElementById('editStatus').value     = admin.status;
  document.getElementById('editModalSubtitle').textContent = 'Editing: ' + admin.full_name;

  const selfNote = document.getElementById('editSelfNote');
  if (parseInt(admin.id) === CURRENT_ADMIN_ID) {
    selfNote.style.display = 'flex';
    document.getElementById('editRole').disabled = true;
  } else {
    selfNote.style.display = 'none';
    document.getElementById('editRole').disabled = false;
  }
  openModal('editModal');
}

// ── Fill Password Modal ─────────────────────────────────────
function openPwModal(admin) {
  document.getElementById('pwAdminId').value = admin.id;
  document.getElementById('pwModalSubtitle').textContent = 'Reset password for: ' + admin.full_name;
  document.getElementById('rsPw').value = '';
  document.getElementById('rsPwConfirm').value = '';
  document.getElementById('rsMatchMsg').innerHTML = '';
  const bar = document.getElementById('rsPwBar');
  if (bar) { bar.style.width='0'; bar.style.background=''; }
  document.querySelectorAll('#pwModal .pw-rule').forEach(r => {
    r.classList.remove('pass');
    r.querySelector('i').className = 'fas fa-circle';
  });
  openModal('pwModal');
}

// ── Password visibility toggle ──────────────────────────────
function togglePw(id, btn) {
  const inp = document.getElementById(id);
  const ico = btn.querySelector('i');
  const show = inp.type === 'password';
  inp.type = show ? 'text' : 'password';
  ico.className = show ? 'fas fa-eye-slash' : 'fas fa-eye';
}

// ── Generic strength checker factory ───────────────────────
function attachStrength(inputId, barId, rules, confirmId, msgId) {
  const inp     = document.getElementById(inputId);
  const bar     = document.getElementById(barId);
  const confirm = document.getElementById(confirmId);
  const msg     = document.getElementById(msgId);

  if (!inp) return;

  inp.addEventListener('input', () => {
    const v  = inp.value;
    let pass = 0;
    rules.forEach(r => {
      const ok = r.fn(v);
      r.el?.classList.toggle('pass', ok);
      const ico = r.el?.querySelector('i');
      if (ico) ico.className = ok ? 'fas fa-circle-check' : 'fas fa-circle';
      if (ok) pass++;
    });
    const pct    = (pass/4)*100;
    const colors = ['','#f87171','#fbbf24','#a78bfa','#34d399'];
    if (bar) { bar.style.width=pct+'%'; bar.style.background=colors[pass]; }
    checkMatch(inp, confirm, msg);
  });

  confirm?.addEventListener('input', () => checkMatch(inp, confirm, msg));
}

function checkMatch(pw, conf, msg) {
  if (!conf || !msg || !conf.value) { if(msg) msg.innerHTML=''; return; }
  const ok = pw.value === conf.value;
  msg.innerHTML = ok
    ? '<span style="color:var(--success)"><i class="fas fa-circle-check"></i> Passwords match</span>'
    : '<span style="color:var(--danger)"><i class="fas fa-circle-xmark"></i> Passwords do not match</span>';
}

const rulesFns = [
  { fn: v=>v.length>=8,          el: null },
  { fn: v=>/[A-Z]/.test(v),     el: null },
  { fn: v=>/[0-9]/.test(v),     el: null },
  { fn: v=>/[^A-Za-z0-9]/.test(v), el: null },
];

// Add modal
attachStrength('addPw','addPwBar', [
  {fn:v=>v.length>=8,          el:document.getElementById('a-len')},
  {fn:v=>/[A-Z]/.test(v),     el:document.getElementById('a-up')},
  {fn:v=>/[0-9]/.test(v),     el:document.getElementById('a-num')},
  {fn:v=>/[^A-Za-z0-9]/.test(v),el:document.getElementById('a-spec')},
], 'addPwConfirm','addMatchMsg');

// Reset modal
attachStrength('rsPw','rsPwBar', [
  {fn:v=>v.length>=8,          el:document.getElementById('r-len')},
  {fn:v=>/[A-Z]/.test(v),     el:document.getElementById('r-up')},
  {fn:v=>/[0-9]/.test(v),     el:document.getElementById('r-num')},
  {fn:v=>/[^A-Za-z0-9]/.test(v),el:document.getElementById('r-spec')},
], 'rsPwConfirm','rsMatchMsg');
</script>
JS;

require_once 'includes/footer.php';
?>
