<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
auth_require_login();
$pdo = crm_pdo();
$page_title = 'Users Management';

// Only admin can access
$currentRole = gp_user_role($pdo);
if ($currentRole !== 'admin') {
    http_response_code(403);
    exit('Access denied. Admin only.');
}

$msg = '';
$msgType = 'success';

// ── POST handlers ────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    gp_require_csrf();
    $action = trim((string)($_POST['action'] ?? ''));

    // Shared field extraction
    $username   = trim((string)($_POST['username'] ?? ''));
    $email      = trim((string)($_POST['email'] ?? ''));
    $role       = in_array($_POST['role'] ?? '', ['admin','manager','secretary','employee','partner','customer'], true)
                  ? $_POST['role'] : 'employee';
    $password   = (string)($_POST['password'] ?? '');
    $empId      = (int)($_POST['employee_link'] ?? 0) ?: null;
    $partId     = (int)($_POST['partner_link'] ?? 0) ?: null;
    $custId     = (int)($_POST['customer_link'] ?? 0) ?: null;
    $isActive   = isset($_POST['active']) ? 1 : 0;
    $permTheme  = in_array($_POST['perm_theme'] ?? '', ['light','dark','system'], true) ? $_POST['perm_theme'] : 'system';

    // Permissions — admin & manager get all automatically
    $isFullAccess = in_array($role, ['admin','manager'], true);
    $pe  = $isFullAccess ? 1 : (isset($_POST['perm_expenses'])   ? 1 : 0);
    $pr  = $isFullAccess ? 1 : (isset($_POST['perm_reports'])    ? 1 : 0);
    $ps  = $isFullAccess ? 1 : (isset($_POST['perm_settings'])   ? 1 : 0);
    $pb  = $isFullAccess ? 1 : (isset($_POST['perm_branding'])   ? 1 : 0);
    $pu  = $isFullAccess ? 1 : (isset($_POST['perm_users'])      ? 1 : 0);
    $pl  = $isFullAccess ? 1 : (isset($_POST['perm_logs'])       ? 1 : 0);
    $pp  = $isFullAccess ? 1 : (isset($_POST['perm_payroll'])    ? 1 : 0);
    $pd  = $isFullAccess ? 1 : (isset($_POST['perm_dispatch'])   ? 1 : 0);
    $pw  = $isFullAccess ? 1 : (isset($_POST['perm_warehouse'])  ? 1 : 0);
    // v1.3.1 — new CRM operation permissions
    $pco = $isFullAccess ? 1 : (isset($_POST['perm_costings'])   ? 1 : 0);
    $pas = $isFullAccess ? 1 : (isset($_POST['perm_assign'])     ? 1 : 0);
    $pcu = $isFullAccess ? 1 : (isset($_POST['perm_customers'])  ? 1 : 0);
    $pin = $isFullAccess ? 1 : (isset($_POST['perm_invoices'])   ? 1 : 0);
    $pfi = $isFullAccess ? 1 : (isset($_POST['perm_financials']) ? 1 : 0);
    $pph = $isFullAccess ? 1 : (isset($_POST['perm_photos'])     ? 1 : 0);

    if ($action === 'create_user') {
        if ($username === '') { $msg = 'Username is required.'; $msgType = 'danger'; }
        elseif ($password === '') { $msg = 'Password is required.'; $msgType = 'danger'; }
        else {
            try {
                $stmt = $pdo->prepare("INSERT INTO users
                    (username, email, role, password_hash, employee_id, external_partner_id, customer_id,
                     is_active, perm_theme, perm_expenses, perm_reports, perm_settings, perm_branding,
                     perm_users, perm_logs, perm_payroll, perm_dispatch, perm_warehouse,
                     perm_costings, perm_assign, perm_customers, perm_invoices, perm_financials, perm_photos)
                    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
                $stmt->execute([
                    $username, $email ?: null, $role, password_hash($password, PASSWORD_DEFAULT),
                    $empId, $partId, $custId, $isActive,
                    $permTheme, $pe, $pr, $ps, $pb, $pu, $pl, $pp, $pd, $pw,
                    $pco, $pas, $pcu, $pin, $pfi, $pph
                ]);
                $msg = 'User <strong>' . h($username) . '</strong> created.';
                gp_log_action($pdo, 'USER_CREATE', 'user', (int)$pdo->lastInsertId(), "Created user: $username");
            } catch (\Throwable $e) {
                $msg = 'Error: ' . h($e->getMessage()); $msgType = 'danger';
            }
        }
    }

    if ($action === 'save_user') {
        $userId = (int)($_POST['user_id'] ?? 0);
        if ($userId > 0) {
            $sets = "username=?, email=?, role=?, employee_id=?, external_partner_id=?, customer_id=?,
                     is_active=?, perm_theme=?, perm_expenses=?, perm_reports=?, perm_settings=?,
                     perm_branding=?, perm_users=?, perm_logs=?, perm_payroll=?, perm_dispatch=?, perm_warehouse=?,
                     perm_costings=?, perm_assign=?, perm_customers=?, perm_invoices=?, perm_financials=?, perm_photos=?";
            $params = [
                $username, $email ?: null, $role, $empId, $partId, $custId, $isActive,
                $permTheme, $pe, $pr, $ps, $pb, $pu, $pl, $pp, $pd, $pw,
                $pco, $pas, $pcu, $pin, $pfi, $pph
            ];
            if ($password !== '') {
                $sets .= ", password_hash=?";
                $params[] = password_hash($password, PASSWORD_DEFAULT);
            }
            $params[] = $userId;
            $pdo->prepare("UPDATE users SET $sets WHERE id=?")->execute($params);
            $msg = 'User <strong>' . h($username) . '</strong> updated.';
            gp_log_action($pdo, 'USER_UPDATE', 'user', $userId, "Updated user: $username");
        }
    }

    if ($action === 'toggle_active') {
        $uid = (int)($_POST['user_id'] ?? 0);
        if ($uid > 0) {
            $pdo->prepare("UPDATE users SET is_active = 1 - is_active WHERE id = ?")->execute([$uid]);
            $msg = 'User status toggled.';
        }
    }

    if ($action === 'delete_user') {
        $uid = (int)($_POST['user_id'] ?? 0);
        $currentUserId = (int)(auth_user()['id'] ?? 0);
        if ($uid > 0 && $uid !== $currentUserId) {
            $pdo->prepare("DELETE FROM users WHERE id = ?")->execute([$uid]);
            $msg = 'User deleted.';
            gp_log_action($pdo, 'USER_DELETE', 'user', $uid, "Deleted user #$uid");
        } else {
            $msg = 'Cannot delete your own account.'; $msgType = 'danger';
        }
        header('Location: /gopools/public/settings/users.php');
        exit;
    }
}

// ── Load data ────────────────────────────────────────────────────────────────
$editId   = (int)($_GET['edit_id'] ?? 0);
$editUser = null;
if ($editId > 0) {
    $s = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $s->execute([$editId]);
    $editUser = $s->fetch() ?: null;
}

$employees = $pdo->query("SELECT id, full_name AS name FROM employees WHERE active = 1 ORDER BY full_name")->fetchAll();
$partners  = $pdo->query("SELECT id, company_name AS name FROM external_partners WHERE active = 1 ORDER BY company_name")->fetchAll();
$customers = $pdo->query("SELECT id, name FROM customers WHERE active = 1 ORDER BY name")->fetchAll();
$users     = $pdo->query("
    SELECT u.*,
           e.full_name AS emp_name,
           ep.company_name AS part_name,
           c.name AS cust_name
    FROM users u
    LEFT JOIN employees e ON u.employee_id = e.id
    LEFT JOIN external_partners ep ON u.external_partner_id = ep.id
    LEFT JOIN customers c ON u.customer_id = c.id
    ORDER BY u.id DESC
")->fetchAll();

function sel_opts(array $list, int $selected): string {
    $h = '<option value="">—</option>';
    foreach ($list as $r) {
        $s = ((int)($r['id'] ?? 0) === $selected) ? ' selected' : '';
        $h .= '<option value="' . (int)$r['id'] . '"' . $s . '>' . h($r['name'] ?? '') . '</option>';
    }
    return $h;
}

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>User Management</h1>
    <span>Admin only · Manage accounts &amp; granular permissions</span>
  </div>
</div>

<?php if ($msg !== ''): ?>
  <div class="alert-<?php echo $msgType === 'danger' ? 'danger' : 'success'; ?>" style="margin-bottom:1rem">
    <?php echo $msg; ?>
  </div>
<?php endif; ?>

<div class="grid-2" style="align-items:start">

  <!-- ── LEFT: Create / Edit form ── -->
  <div class="card">
    <div class="page-header-title" style="margin-bottom:1rem">
      <h1 style="font-size:1.1rem"><?php echo $editUser ? 'Edit user' : 'Create new user'; ?></h1>
      <?php if ($editUser): ?>
        <a href="/gopools/public/settings/users.php" class="btn btn-sm btn-outline-light">+ New user</a>
      <?php endif; ?>
    </div>

    <form method="post">
      <?php echo csrf_field(); ?>
      <input type="hidden" name="action" value="<?php echo $editUser ? 'save_user' : 'create_user'; ?>">
      <?php if ($editUser): ?>
        <input type="hidden" name="user_id" value="<?php echo (int)$editUser['id']; ?>">
      <?php endif; ?>

      <div class="form-grid">
        <div class="form-group">
          <label>Username</label>
          <input type="text" name="username" value="<?php echo h($editUser['username'] ?? ''); ?>" required>
        </div>
        <div class="form-group">
          <label>Email</label>
          <input type="email" name="email" value="<?php echo h($editUser['email'] ?? ''); ?>">
        </div>
        <div class="form-group">
          <label>Password <?php echo $editUser ? '(blank = keep)' : ''; ?></label>
          <input type="password" name="password" autocomplete="new-password" <?php echo $editUser ? '' : 'required'; ?>>
        </div>
        <div class="form-group">
          <label>Role</label>
          <select name="role" id="roleSelect">
            <?php foreach (['admin','manager','secretary','employee','partner','customer'] as $r): ?>
              <option value="<?php echo $r; ?>" <?php echo (($editUser['role'] ?? 'employee') === $r) ? 'selected' : ''; ?>>
                <?php echo ucfirst($r); ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label>Link to Employee</label>
          <select name="employee_link">
            <?php echo sel_opts($employees, (int)($editUser['employee_id'] ?? 0)); ?>
          </select>
        </div>
        <div class="form-group">
          <label>Link to Partner</label>
          <select name="partner_link">
            <?php echo sel_opts($partners, (int)($editUser['external_partner_id'] ?? 0)); ?>
          </select>
        </div>
        <div class="form-group" style="grid-column:1/-1">
          <label>Link to Customer</label>
          <select name="customer_link">
            <?php echo sel_opts($customers, (int)($editUser['customer_id'] ?? 0)); ?>
          </select>
        </div>
      </div>

      <!-- Active toggle -->
      <label style="display:flex;align-items:center;gap:.5rem;margin:.5rem 0 1rem;cursor:pointer;font-weight:600;font-size:.85rem">
        <input type="checkbox" name="active" value="1" <?php echo (int)($editUser['is_active'] ?? 1) ? 'checked' : ''; ?>>
        Active account
      </label>

      <!-- ── Permissions ── -->
      <div class="perm-card" id="permissionsSection">
        <div class="perm-hdr">🔒 Permissions &amp; Access
          <small class="perm-note" id="adminNote" style="display:none">Admin = full access (locked)</small>
        </div>

        <div class="perm-group" style="margin-bottom:.75rem">
          <div class="perm-gtitle">🎨 Theme Preference</div>
          <div style="display:flex;gap:.5rem;flex-wrap:wrap">
            <?php foreach (['system' => ['System','☀'], 'light' => ['Light','🌤'], 'dark' => ['Dark','🌙']] as $v => [$lb, $ic]): ?>
              <?php $cur = $editUser['perm_theme'] ?? 'system'; ?>
              <label class="theme-opt <?php echo $cur === $v ? 'active' : ''; ?>">
                <input type="radio" name="perm_theme" value="<?php echo $v; ?>" <?php echo $cur === $v ? 'checked' : ''; ?> class="visually-hidden" style="position:absolute;opacity:0">
                <?php echo $ic; ?> <?php echo $lb; ?>
              </label>
            <?php endforeach; ?>
          </div>
        </div>

        <!-- CRM Operations group -->
        <div class="perm-group">
          <div class="perm-gtitle">📋 CRM Λειτουργίες</div>
          <div class="perms-grid">
            <?php foreach ([
              ['perm_costings',   '💰', 'Κοστολόγια',   'Βλέπει κοστολόγια & προσφορές συνεργατών'],
              ['perm_assign',     '📌', 'Ανάθεση',       'Αναθέτει εργασίες σε συνεργάτες/υπαλλήλους'],
              ['perm_customers',  '👤', 'Πελάτες',       'Δημιουργεί & επεξεργάζεται πελάτες'],
              ['perm_invoices',   '🧾', 'Τιμολόγια',     'Βλέπει & διαχειρίζεται πληρωμές/τιμολόγια'],
              ['perm_financials', '📈', 'Οικονομικά',    'Βλέπει συνολικές οικονομικές αναλύσεις & P&L'],
              ['perm_photos',     '📸', 'Gallery Εικόνων','Διαχειρίζεται όλες τις φωτογραφίες έργων'],
            ] as [$k, $ic, $lb, $desc]): ?>
              <label class="perm-item" title="<?php echo h($desc); ?>">
                <span class="perm-cw">
                  <input type="checkbox" name="<?php echo $k; ?>" value="1" class="perm-cb"
                    <?php echo !empty($editUser[$k]) ? 'checked' : ''; ?>>
                  <span class="perm-ck"></span>
                </span>
                <span class="perm-lbl"><?php echo $ic; ?> <?php echo $lb; ?></span>
              </label>
            <?php endforeach; ?>
          </div>
        </div>

        <!-- System Admin group -->
        <div class="perm-group" style="margin-top:.75rem">
          <div class="perm-gtitle">⚙️ Διαχείριση Συστήματος</div>
          <div class="perms-grid">
            <?php foreach ([
              ['perm_expenses',  '💸', 'Έξοδα',         'Βλέπει & καταχωρεί έξοδα έργων'],
              ['perm_reports',   '📊', 'Αναφορές',      'Βλέπει αναφορές & στατιστικά'],
              ['perm_payroll',   '💳', 'Μισθοδοσία',    'Διαχειρίζεται μισθοδοσία'],
              ['perm_dispatch',  '🚀', 'Dispatch',       'Dispatch dashboard πρόσβαση'],
              ['perm_warehouse', '📦', 'Αποθήκη',       'Διαχείριση αποθήκης'],
              ['perm_settings',  '⚙️', 'Ρυθμίσεις',    'Πρόσβαση στις ρυθμίσεις συστήματος'],
              ['perm_branding',  '🎨', 'Branding',       'Επεξεργασία branding & λογοτύπου'],
              ['perm_users',     '👥', 'Χρήστες',       'Διαχείριση λογαριασμών χρηστών'],
              ['perm_logs',      '📋', 'System Logs',   'Βλέπει αρχεία καταγραφής συστήματος'],
            ] as [$k, $ic, $lb, $desc]): ?>
              <label class="perm-item" title="<?php echo h($desc); ?>">
                <span class="perm-cw">
                  <input type="checkbox" name="<?php echo $k; ?>" value="1" class="perm-cb"
                    <?php echo !empty($editUser[$k]) ? 'checked' : ''; ?>>
                  <span class="perm-ck"></span>
                </span>
                <span class="perm-lbl"><?php echo $ic; ?> <?php echo $lb; ?></span>
              </label>
            <?php endforeach; ?>
          </div>
        </div>

        <div style="display:flex;align-items:center;gap:.4rem;flex-wrap:wrap;margin-top:.75rem">
          <span style="font-size:.75rem;font-weight:600;color:var(--gp-muted)">Quick:</span>
          <button type="button" class="btn btn-sm btn-outline-light" onclick="setAll(true)">✅ Όλα</button>
          <button type="button" class="btn btn-sm btn-outline-light" onclick="setAll(false)">✖ Κανένα</button>
          <button type="button" class="btn btn-sm btn-outline-light" onclick="setPreset('manager')">👔 Manager</button>
          <button type="button" class="btn btn-sm btn-outline-light" onclick="setPreset('secretary')">📝 Γραμματεία</button>
          <button type="button" class="btn btn-sm btn-outline-light" onclick="setPreset('employee')">👷 Υπάλληλος</button>
        </div>
      </div>

      <div class="form-actions" style="margin-top:1rem">
        <button class="btn btn-primary" type="submit">
          <?php echo $editUser ? '💾 Save user' : '+ Create user'; ?>
        </button>
        <?php if ($editUser): ?>
          <a href="/gopools/public/settings/users.php" class="btn btn-outline-light">Cancel</a>
        <?php endif; ?>
      </div>
    </form>
  </div>

  <!-- ── RIGHT: Users table ── -->
  <div class="card">
    <div class="page-header-title" style="margin-bottom:1rem">
      <h1 style="font-size:1.1rem">Users</h1>
      <span>System accounts · <?php echo count($users); ?> total</span>
    </div>

    <div class="table-responsive">
      <table class="table">
        <thead>
          <tr>
            <th>ID</th>
            <th>Username</th>
            <th>Email</th>
            <th>Role</th>
            <th>Perms</th>
            <th>Status</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($users as $u): ?>
          <tr style="<?php echo !(int)$u['is_active'] ? 'opacity:.5' : ''; ?>">
            <td><?php echo (int)$u['id']; ?></td>
            <td>
              <strong><?php echo h($u['username']); ?></strong>
              <?php if ($u['emp_name']): ?>
                <br><small style="color:var(--gp-muted)">👷 <?php echo h($u['emp_name']); ?></small>
              <?php elseif ($u['part_name']): ?>
                <br><small style="color:var(--gp-muted)">🤝 <?php echo h($u['part_name']); ?></small>
              <?php elseif ($u['cust_name']): ?>
                <br><small style="color:var(--gp-muted)">👤 <?php echo h($u['cust_name']); ?></small>
              <?php endif; ?>
            </td>
            <td><?php echo h($u['email'] ?? ''); ?></td>
            <td>
              <span class="badge role-<?php echo h($u['role']); ?>"><?php echo h($u['role']); ?></span>
            </td>
            <td>
              <?php
                $perms = ['perm_expenses','perm_reports','perm_settings','perm_branding',
                          'perm_users','perm_logs','perm_payroll','perm_dispatch','perm_warehouse',
                          'perm_costings','perm_assign','perm_customers','perm_invoices','perm_financials','perm_photos'];
                $count = array_sum(array_map(fn($k) => (int)($u[$k] ?? 0), $perms));
                $total = count($perms);
                $pct   = round($count / $total * 100);
              ?>
              <div style="display:flex;align-items:center;gap:.4rem">
                <div style="background:var(--gp-card-border);border-radius:999px;height:6px;width:56px;overflow:hidden">
                  <div style="height:100%;width:<?php echo $pct; ?>%;background:<?php echo $pct===100 ? 'var(--gp-success,#16a34a)' : ($pct>50 ? '#f59e0b' : 'var(--gp-muted)'); ?>;border-radius:999px"></div>
                </div>
                <small><?php echo $count; ?>/<?php echo $total; ?></small>
              </div>
            </td>
            <td>
              <form method="post" style="display:inline">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="action" value="toggle_active">
                <input type="hidden" name="user_id" value="<?php echo (int)$u['id']; ?>">
                <button type="submit" class="btn btn-sm <?php echo (int)$u['is_active'] ? 'btn-outline-light' : 'btn-outline-light'; ?>"
                        style="padding:2px 8px;font-size:.75rem" title="Toggle active">
                  <?php echo (int)$u['is_active'] ? '✅ Active' : '⛔ Off'; ?>
                </button>
              </form>
            </td>
            <td style="display:flex;gap:.25rem">
              <a href="/gopools/public/settings/users.php?edit_id=<?php echo (int)$u['id']; ?>"
                 class="btn btn-sm btn-outline-light">✏️</a>
              <?php if ((int)$u['id'] !== (int)(auth_user()['id'] ?? 0)): ?>
                <form method="post" style="display:inline" onsubmit="return confirm('Delete user <?php echo h($u['username']); ?>?')">
                  <?php echo csrf_field(); ?>
                  <input type="hidden" name="action" value="delete_user">
                  <input type="hidden" name="user_id" value="<?php echo (int)$u['id']; ?>">
                  <button type="submit" class="btn btn-sm btn-outline-light">🗑️</button>
                </form>
              <?php endif; ?>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>

<script>
// Theme option toggle
document.querySelectorAll('.theme-opt input').forEach(r => {
  r.addEventListener('change', () => {
    document.querySelectorAll('.theme-opt').forEach(b => b.classList.remove('active'));
    r.closest('.theme-opt').classList.add('active');
  });
});

// Role → lock permissions for admin
const rs = document.getElementById('roleSelect');
function syncAdmin() {
  const a = rs.value === 'admin';
  document.getElementById('adminNote').style.display = a ? 'inline' : 'none';
  document.querySelectorAll('.perm-cb').forEach(c => {
    if (a) { c.checked = true; c.disabled = true; }
    else { c.disabled = false; }
  });
}
rs.addEventListener('change', syncAdmin);
syncAdmin();

function setAll(v) { document.querySelectorAll('.perm-cb:not(:disabled)').forEach(c => c.checked = v); }
function setPreset(t) {
  setAll(false);
  const presets = {
    manager:   ['perm_expenses','perm_reports','perm_payroll','perm_dispatch','perm_warehouse',
                'perm_costings','perm_assign','perm_customers','perm_invoices','perm_financials','perm_photos'],
    secretary: ['perm_assign','perm_customers','perm_photos'],
    employee:  []
  };
  (presets[t] || []).forEach(n => {
    const c = document.querySelector('input[name="' + n + '"]');
    if (c && !c.disabled) c.checked = true;
  });
}
</script>

<style>
.badge { display:inline-block; padding:.25em .55em; border-radius:999px; font-size:.7rem; font-weight:700; color:#fff; text-transform:uppercase; }
.badge.role-admin { background:#dc2626; }
.badge.role-manager { background:#2563eb; }
.badge.role-secretary { background:#7c3aed; }
.badge.role-employee { background:#16a34a; }
.badge.role-partner { background:#ea580c; }
.badge.role-customer { background:#0891b2; }
.visually-hidden { position:absolute; opacity:0; width:1px; height:1px; }
.perm-card { background:var(--gp-card-bg); border:1.5px solid var(--gp-primary); border-radius:var(--radius,10px); padding:1rem 1.25rem; margin-top:.5rem; }
.perm-hdr { display:flex; align-items:center; gap:.5rem; font-weight:700; font-size:.85rem; text-transform:uppercase; letter-spacing:.06em; color:var(--gp-primary); margin-bottom:1rem; }
.perm-note { background:var(--gp-primary); color:#fff; border-radius:999px; padding:2px 10px; font-size:.7rem; font-weight:500; }
.perm-group { margin-bottom:.5rem; }
.perm-gtitle { font-size:.75rem; font-weight:600; text-transform:uppercase; color:var(--gp-muted); display:flex; align-items:center; gap:.4rem; margin-bottom:.6rem; }
.theme-opt { display:flex; align-items:center; gap:.35rem; padding:.4rem .75rem; border-radius:999px; border:1.5px solid var(--gp-card-border); cursor:pointer; font-size:.8rem; font-weight:500; transition:all .18s; background:var(--gp-card-bg); color:var(--gp-muted); }
.theme-opt:hover { border-color:var(--gp-primary); color:var(--gp-primary); }
.theme-opt.active { border-color:var(--gp-primary); background:var(--gp-primary); color:#fff; }
.perms-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(130px,1fr)); gap:.5rem; }
.perm-item { display:flex; align-items:center; gap:.5rem; padding:.45rem .65rem; border-radius:8px; border:1.5px solid var(--gp-card-border); cursor:pointer; transition:all .15s; background:var(--gp-card-bg); }
.perm-item:hover { border-color:var(--gp-primary); }
.perm-cw { position:relative; flex-shrink:0; }
.perm-cb { position:absolute; opacity:0; width:18px; height:18px; cursor:pointer; z-index:1; top:0; left:0; }
.perm-ck { display:block; width:18px; height:18px; border-radius:5px; border:2px solid var(--gp-card-border); background:transparent; transition:all .15s; }
.perm-cb:checked + .perm-ck { background:var(--gp-primary); border-color:var(--gp-primary); }
.perm-item:has(.perm-cb:checked) { border-color:var(--gp-primary); }
.perm-lbl { display:flex; align-items:center; gap:.3rem; font-size:.78rem; font-weight:500; color:var(--gp-text); }
</style>
