<?php
$user_perm_pages = crmPagesConfig();
$user_permission_map = [];
if (tableExists($conn, 'user_permissions')) {
    $pr = $conn->query("SELECT user_id, page_key, action_key FROM user_permissions WHERE account_id=$account_id AND allowed=1");
    while ($pr && $perm = $pr->fetch_assoc()) {
        $uid = (int)$perm['user_id'];
        $pageKey = $perm['page_key'];
        $user_permission_map[$uid][$pageKey] = true;
    }
}
?>
<!-- ===================== USERS TAB ===================== -->
<div class="tab-pane <?= ($requested_tab === 'users') ? 'active' : '' ?>" id="tab-users">
  <div class="mini-tabs" style="margin-bottom:14px">
    <button type="button" class="mini-tab active" onclick="openUsersSubtab('usersListPane',this)">Users List</button>
    <?php if ($can_manage_settings_users): ?>
      <button type="button" class="mini-tab" onclick="openUsersSubtab('usersAddPane',this)">Add User</button>
      <button type="button" class="mini-tab" id="usersPermMiniTab" onclick="openUsersSubtab('usersPermissionsPane',this)" style="display:none">Page Access</button>
    <?php endif; ?>
  </div>

  <?php if ($can_manage_settings_users): ?>
  <div id="usersAddPane" class="users-subpane" style="display:none">
    <div class="card" style="padding:18px;margin-bottom:18px">
      <div class="toolbar" style="margin-bottom:12px"><span class="card-title">Add User</span></div>
      <form id="addUserForm">
        <div class="form-grid">
          <div class="form-group"><label class="form-label">Name *</label><input type="text" name="name" class="form-control" required></div>
          <div class="form-group"><label class="form-label">Phone</label><input type="text" name="phone" class="form-control"></div>
          <div class="form-group"><label class="form-label">Email *</label><input type="email" name="email" class="form-control" required></div>
          <div class="form-group"><label class="form-label">Password *</label><input type="password" name="password" class="form-control" required minlength="6"></div>
          <div class="form-group span-2"><label class="form-label">Role</label><select name="role_id" class="form-control"><option value="">No Role</option><?php $roles->data_seek(0); while ($ro = $roles->fetch_assoc()): ?><option value="<?= $ro['id'] ?>"><?= htmlspecialchars($ro['name']) ?></option><?php endwhile; ?></select></div>
        </div>
        <div class="page-access-box">
          <div class="page-access-head">
            <div><h3>Page access</h3><p>Choose pages from sidebar. Any selected page gives full access inside it.</p></div>
            <label class="check-pill"><input type="checkbox" id="addUserAllPermissions" onchange="toggleAllAddUserPermissions(this.checked)"> Give all pages</label>
          </div>
          <div class="perm-grid">
            <?php foreach($user_perm_pages as $key=>$cfg): ?>
              <label class="perm-card">
                <input type="checkbox" class="add-user-perm-check add-user-perm-<?= htmlspecialchars($key) ?>" name="permissions[]" data-page="<?= htmlspecialchars($key) ?>" data-action="view" value="<?= htmlspecialchars($key.'|view') ?>">
                <span><?= htmlspecialchars($cfg['label']) ?></span>
                <small><?= htmlspecialchars($key) ?></small>
              </label>
            <?php endforeach; ?>
          </div>
        </div>
        <div style="text-align:right;margin-top:16px"><button type="button" class="btn btn-primary" onclick="addUser()">Create User</button></div>
      </form>
    </div>
  </div>

  <div id="usersPermissionsPane" class="users-subpane" style="display:none">
    <div class="card" style="padding:18px;margin-bottom:18px">
      <div class="toolbar" style="margin-bottom:12px;justify-content:space-between;align-items:center">
        <div><span class="card-title">Page Access</span><div class="text-xs text-muted" id="permUserTitle">Select a user from the list.</div></div>
        <button type="button" class="btn btn-secondary btn-sm" onclick="openUsersSubtab('usersListPane', document.querySelector('.mini-tab'))">Back to users</button>
      </div>
      <input type="hidden" id="permUserId" value="">
      <div class="page-access-box">
        <div class="page-access-head">
          <div><h3>Allowed pages</h3><p>If a page is checked, the user can add, edit, delete, view and use all actions on that page.</p></div>
          <label class="check-pill"><input type="checkbox" id="existingAllPermissions" onchange="toggleAllExistingPermissions(this.checked)"> Give all pages</label>
        </div>
        <div class="perm-grid">
          <?php foreach($user_perm_pages as $key=>$cfg): ?>
            <label class="perm-card">
              <input type="checkbox" class="perm-check perm-page-<?= htmlspecialchars($key) ?>" data-page="<?= htmlspecialchars($key) ?>" data-action="view">
              <span><?= htmlspecialchars($cfg['label']) ?></span>
              <small><?= htmlspecialchars($key) ?></small>
            </label>
          <?php endforeach; ?>
        </div>
        <div style="text-align:right;margin-top:16px"><button type="button" class="btn btn-primary" onclick="saveUserPermissions()">Save Access</button></div>
      </div>
    </div>
  </div>
  <?php endif; ?>

  <div id="usersListPane" class="users-subpane">
    <div class="toolbar"><span class="card-title">Team Members</span></div>
    <div class="card">
      <div class="table-wrapper">
        <table class="crm-table">
          <thead><tr><th>Name</th><th>Email</th><th>Phone</th><th>Role</th><th>Since</th><th>Actions</th></tr></thead>
          <tbody>
            <?php while ($u = $all_users->fetch_assoc()): ?>
            <tr id="user_<?= crmEid($u['id']) ?>">
              <td><div class="d-flex align-center gap-8"><div class="avatar avatar-sm"><?= strtoupper(substr($u['name'],0,2)) ?></div><?= htmlspecialchars($u['name']) ?></div></td>
              <td><?= htmlspecialchars($u['email']) ?></td><td><?= htmlspecialchars($u['phone'] ?: '—') ?></td>
              <td><?php if ($can_manage_settings_users && $u['id'] != $user_id): ?><select class="form-control form-control-sm" onchange="changeUserRole('<?= crmEid($u['id']) ?>', this.value)"><option value="">No Role</option><?php $roles->data_seek(0); while ($ro = $roles->fetch_assoc()): ?><option value="<?= $ro['id'] ?>" <?= $u['role_id'] == $ro['id'] ? 'selected' : '' ?>><?= htmlspecialchars($ro['name']) ?></option><?php endwhile; ?></select><?php else: ?><span class="badge badge-blue"><?= htmlspecialchars($u['role_name'] ?: 'User') ?></span><?php endif; ?></td>
              <td class="text-muted text-xs"><?= formatDate($u['datetime_created']) ?></td>
              <td><?php if ($u['id'] != $user_id && $can_manage_settings_users): ?><button class="btn btn-warning btn-sm" onclick="editUser('<?= crmEid($u['id']) ?>', '<?= addslashes($u['name']) ?>', '<?= addslashes($u['email']) ?>', '<?= addslashes($u['phone']) ?>', <?= $u['role_id'] ?: 'null' ?>)">Edit</button> <button class="btn btn-secondary btn-sm" onclick="openUserPermissionsPane('<?= crmEid($u['id']) ?>', '<?= addslashes($u['name']) ?>')">Page Access</button> <button class="btn btn-danger btn-sm" onclick="deleteUser('<?= crmEid($u['id']) ?>', '<?= addslashes($u['name']) ?>')">Remove</button><?php else: ?><span class="badge badge-teal">You</span><?php endif; ?></td>
            </tr>
            <?php endwhile; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<script>
window.userPermissionMap = <?= json_encode($user_permission_map, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE) ?>;
</script>
<style>
.mini-tabs{display:flex;gap:8px;border-bottom:1px solid var(--border);padding-bottom:8px;flex-wrap:wrap}.mini-tab{border:0;background:transparent;padding:10px 14px;border-radius:10px;font-weight:800;color:var(--text-muted);cursor:pointer}.mini-tab.active{background:#eaf2ff;color:#163b7c}.page-access-box{border-top:1px solid var(--border);margin-top:16px;padding-top:16px}.page-access-head{display:flex;justify-content:space-between;gap:10px;align-items:center;flex-wrap:wrap;margin-bottom:12px}.page-access-head h3{margin:0}.page-access-head p{margin:4px 0 0;color:var(--text-muted);font-size:12px}.check-pill{display:inline-flex;align-items:center;gap:7px;background:var(--bg-base);border:1px solid var(--border);border-radius:999px;padding:8px 12px;font-weight:800}.perm-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:10px}.perm-card{display:flex;flex-direction:column;gap:4px;background:#fff;border:1px solid var(--border);border-radius:12px;padding:12px;cursor:pointer}.perm-card:hover{border-color:#8fb1df}.perm-card input{width:18px;height:18px}.perm-card span{font-weight:800}.perm-card small{color:var(--text-muted)}
</style>
<script>
function openUsersSubtab(id,btn){document.querySelectorAll('#tab-users .users-subpane').forEach(p=>p.style.display='none');const p=document.getElementById(id);if(p)p.style.display='block';document.querySelectorAll('#tab-users .mini-tab').forEach(b=>b.classList.remove('active'));if(btn)btn.classList.add('active');}
</script>
