<?php
$admin = $admin ?? \App\Core\Auth::currentUser();
$active = 'users';
$pageTitle = 'User Management';
require __DIR__ . '/../layout/admin_header.php';
?>

<div class="topbar">
  <div>
    <h1>Super Admin Backend Control Panel</h1>
    <div class="crumbs">Workspace → Admin → User Management</div>
  </div>
  <div class="user-chip"><span class="dot"></span> <?= htmlspecialchars($admin['name']) ?></div>
</div>

<div class="stat-grid">
  <div class="stat-card">
    <div class="icon blue">👥</div>
    <div class="label">Total Users</div>
    <div class="value"><?= $stats['total_users'] ?></div>
  </div>
  <div class="stat-card">
    <div class="icon green">✅</div>
    <div class="label">Active Users</div>
    <div class="value"><?= $stats['active_users'] ?></div>
  </div>
  <div class="stat-card">
    <div class="icon amber">🏢</div>
    <div class="label">Departments</div>
    <div class="value"><?= $stats['departments'] ?></div>
  </div>
  <div class="stat-card">
    <div class="icon purple">📁</div>
    <div class="label">Total Projects</div>
    <div class="value"><?= $stats['total_projects'] ?></div>
  </div>
</div>

<?php if ($flash): ?>
  <div class="alert alert-<?= $flash['type'] === 'error' ? 'error' : 'success' ?>"><?= htmlspecialchars($flash['msg']) ?></div>
<?php endif; ?>

<div class="card">
  <div class="toolbar">
    <form class="search-box" method="GET" action="/admin/users">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>
      <input type="text" name="q" value="<?= htmlspecialchars($search) ?>" placeholder="Search by name, username or email...">
    </form>
    <button class="btn-primary" onclick="openModal('addUserModal')">+ Add New User</button>
    <form method="POST" action="/admin/users/bulk-generate-credentials" style="display:inline;" onsubmit="return confirm('Generate usernames and temporary passwords for every manager/employee who doesn\\'t have login access yet? Existing accounts are never touched.');">
      <button type="submit" class="btn-secondary">⚡ Generate Logins for Everyone Without Access</button>
    </form>
  </div>

  <table>
    <thead>
      <tr>
        <th>Name</th>
        <th>Role</th>
        <th>Department Access</th>
        <th>Project Access</th>
        <th>Reports To</th>
        <th>Status</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($users as $u): ?>
        <?php
          $initials = strtoupper(substr($u['name'] ?? '?', 0, 1));
          $isSA = $u['user_type'] === 'superadmin';
          $avatarPalette = ['#4f6ef7','#12a150','#f0a83c','#7c3ae0','#0f8a7f','#e3453a','#1d63e0','#c17a12'];
          $avatarColor = $avatarPalette[crc32($u['name'] ?? 'x') % count($avatarPalette)];
          $roleBadgeMap = [
            'Super Admin' => 'badge-role-super', 'CEO' => 'badge-role-ceo', 'Director' => 'badge-role-director',
            'Ops Manager' => 'badge-role-manager', 'Office Manager' => 'badge-role-manager',
            'Account Manager' => 'badge-role-manager', 'Manager' => 'badge-role-manager',
            'Field Team' => 'badge-role-field', 'Employee' => 'badge-role-employee',
          ];
          $badgeClass = $roleBadgeMap[$u['role_name']] ?? 'badge-role-default';
        ?>
        <tr>
          <td>
            <div class="row-name">
              <span class="avatar" style="background:<?= $avatarColor ?>;"><?= htmlspecialchars($initials) ?></span>
              <div>
                <div style="font-weight:700;"><?= htmlspecialchars($u['name']) ?></div>
                <div style="color:var(--text-muted);font-size:12px;"><?= htmlspecialchars($u['email'] ?? '') ?></div>
                <?php if (!empty($u['username'])): ?>
                  <div style="color:var(--blue-600);font-size:11.5px;font-weight:600;">@<?= htmlspecialchars($u['username']) ?></div>
                <?php endif; ?>
              </div>
            </div>
          </td>
          <td>
            <span class="badge <?= $badgeClass ?>"><?= htmlspecialchars($u['role_name']) ?></span>
          </td>
          <td><?= htmlspecialchars($u['departments']) ?></td>
          <td><?= htmlspecialchars($u['projects']) ?></td>
          <td><?= htmlspecialchars($u['reports_to_name']) ?></td>
          <td>
            <span class="badge <?= (int)$u['is_active'] === 1 ? 'badge-active' : 'badge-disabled' ?>">
              <?= (int)$u['is_active'] === 1 ? 'Active' : 'Inactive' ?>
            </span>
          </td>
          <td>
            <?php if (!$isSA): ?>
              <button class="btn-secondary" style="padding:6px 12px;font-size:12px;"
                onclick='openAccessModal(<?= json_encode([
                  "user_type" => $u["user_type"],
                  "id" => (int)$u["id"],
                  "name" => $u["name"],
                  "username" => $u["username"] ?? '',
                  "role_id" => \App\Models\UserManager::currentRoleId($u["user_type"], (int)$u["id"]),
                  "department_ids" => \App\Models\UserManager::currentDepartmentIds($u["user_type"], (int)$u["id"]),
                  "project_ids" => \App\Models\UserManager::currentProjectIds($u["user_type"], (int)$u["id"]),
                  "reports_to" => (function() use ($u) {
                    $rt = \App\Models\UserManager::currentReportsTo($u["user_type"], (int)$u["id"]);
                    return $rt ? $rt["type"] . ':' . $rt["id"] : '';
                  })(),
                ], JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP) ?>)'>Manage Access</button>

              <form method="POST" action="/admin/users/toggle" style="display:inline;">
                <input type="hidden" name="user_type" value="<?= htmlspecialchars($u['user_type']) ?>">
                <input type="hidden" name="id" value="<?= (int)$u['id'] ?>">
                <input type="hidden" name="active" value="<?= (int)$u['is_active'] === 1 ? '0' : '1' ?>">
                <?php if ((int)$u['is_active'] === 1): ?>
                  <button type="submit" class="btn-danger">Disable</button>
                <?php else: ?>
                  <button type="submit" class="btn-success">Enable</button>
                <?php endif; ?>
              </form>
            <?php else: ?>
              <span style="color:var(--text-muted);font-size:12px;">Protected</span>
            <?php endif; ?>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

<!-- ===================== ADD USER MODAL ===================== -->
<div class="modal-overlay" id="addUserModal">
  <div class="modal">
    <h3>Grant Workspace Access</h3>
    <p style="font-size:12.5px;color:var(--text-muted);margin-top:-8px;margin-bottom:16px;">
      Select an already-imported manager or employee to set up their login. New people are added via
      the staffing import — this only turns on system access for someone already on file.
    </p>
    <form method="POST" action="/admin/users/create">
      <div class="field">
        <label>User Type</label>
        <select name="user_type" id="grantUserType" required style="width:100%;padding:10px;border:1px solid var(--border);border-radius:10px;" onchange="toggleGrantPersonList()">
          <option value="manager">Manager</option>
          <?php if (\App\Core\Features::employeeOnboardingEnabled()): ?>
            <option value="employee">Employee</option>
          <?php endif; ?>
        </select>
      </div>
      <div class="field" id="managerPickerField">
        <label>Select Manager</label>
        <select name="existing_id" id="managerPicker" style="width:100%;padding:10px;border:1px solid var(--border);border-radius:10px;" onchange="clearNewPersonName('manager')">
          <option value="">— Select —</option>
          <?php foreach ($allManagersForDisplay as $m): ?>
            <option value="<?= $m['id'] ?>" <?= $m['has_access'] ? 'disabled' : '' ?>><?= htmlspecialchars($m['name']) ?><?= $m['dept'] ? ' (' . htmlspecialchars($m['dept']) . ')' : '' ?><?= $m['has_access'] ? ' — already has access' : '' ?></option>
          <?php endforeach; ?>
        </select>
        <?php if (empty($availableManagers)): ?>
          <small style="color:var(--text-muted);">All imported managers already have access. (Greyed-out names above already have a login — pick a name without that label to grant new access.)</small>
        <?php endif; ?>
        <div style="margin-top:8px;">
          <a href="#" onclick="toggleNewPersonField('manager');return false;" id="managerNewToggleLink" style="font-size:12.5px;">+ Add a new manager not on this list</a>
          <div id="managerNewNameField" style="display:none;margin-top:6px;">
            <input type="text" name="new_person_name" id="managerNewName" placeholder="Full name" style="width:100%;padding:10px;border:1px solid var(--border);border-radius:10px;">
            <small style="color:var(--text-muted);">This creates a new record on file, then grants them login access.</small>
          </div>
        </div>
      </div>
      <div class="field" id="employeePickerField" style="display:none;">
        <label>Select Employee</label>
        <select name="existing_id" id="employeePicker" style="width:100%;padding:10px;border:1px solid var(--border);border-radius:10px;" onchange="clearNewPersonName('employee')">
          <option value="">— Select —</option>
          <?php foreach ($availableEmployees as $e): ?>
            <option value="<?= $e['id'] ?>"><?= htmlspecialchars($e['name']) ?></option>
          <?php endforeach; ?>
        </select>
        <?php if (empty($availableEmployees)): ?>
          <small style="color:var(--text-muted);">All imported employees already have access.</small>
        <?php endif; ?>
        <div style="margin-top:8px;">
          <a href="#" onclick="toggleNewPersonField('employee');return false;" id="employeeNewToggleLink" style="font-size:12.5px;">+ Add a new employee not on this list</a>
          <div id="employeeNewNameField" style="display:none;margin-top:6px;">
            <input type="text" name="new_person_name" id="employeeNewName" placeholder="Full name" style="width:100%;padding:10px;border:1px solid var(--border);border-radius:10px;">
            <small style="color:var(--text-muted);">This creates a new record on file, then grants them login access.</small>
          </div>
        </div>
      </div>
      <div class="field"><label>Username <small style="text-transform:none;font-weight:500;">(auto-suggested, editable)</small></label><input type="text" name="username" id="grantUsername"></div>
      <div class="field"><label>Email (optional — keeps imported email if blank)</label><input type="email" name="email"></div>
      <div class="field">
        <label>Temporary Password <small style="text-transform:none;font-weight:500;">(auto-generated if left blank)</small></label>
        <div style="display:flex;gap:8px;">
          <input type="text" name="password" id="grantPassword" minlength="8" style="flex:1;">
          <button type="button" class="btn-secondary" onclick="generateGrantPassword()">🎲 Generate</button>
        </div>
      </div>
      <div class="field">
        <label>Role</label>
        <select name="role_id" style="width:100%;padding:10px;border:1px solid var(--border);border-radius:10px;">
          <option value="">— Select Role —</option>
          <?php foreach ($roles as $r): ?>
            <option value="<?= $r['id'] ?>"><?= htmlspecialchars($r['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="field">
        <label>Reports To (Reporting Manager)</label>
        <select name="reports_to" style="width:100%;padding:10px;border:1px solid var(--border);border-radius:10px;">
          <option value="">— None —</option>
          <?php foreach ($reportsToCandidates as $rt): ?>
            <option value="<?= htmlspecialchars($rt['user_type']) ?>:<?= (int)$rt['id'] ?>">
              <?= htmlspecialchars($rt['name']) ?> <?= $rt['user_type'] === 'superadmin' ? '(Super Admin)' : '(Manager)' ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="field">
        <label>Department Access</label>
        <label style="display:flex;align-items:center;gap:7px;font-size:12.5px;font-weight:700;color:var(--blue-600);margin-bottom:8px;">
          <input type="checkbox" id="grantSelectAllDepts" onchange="toggleAllGrantDepts(this.checked)"> Select All Departments
        </label>
        <div class="checkbox-grid">
          <?php foreach ($departments as $d): ?>
            <label><input type="checkbox" name="department_ids[]" value="<?= $d['id'] ?>" class="grant-dept-checkbox" onchange="filterGrantProjects()"> <?= htmlspecialchars($d['name']) ?></label>
          <?php endforeach; ?>
        </div>
      </div>
      <div class="field">
        <label>Project Access <small style="text-transform:none;font-weight:500;">(all projects — assign independently of department)</small></label>
        <div class="checkbox-grid" id="grantProjGrid">
          <?php foreach ($projectsByDept as $deptId => $projects): ?>
            <?php foreach ($projects as $p): ?>
              <label class="grant-proj-option" data-dept="<?= (int)$deptId ?>">
                <input type="checkbox" name="project_ids[]" value="<?= $p['id'] ?>" class="grant-proj-checkbox" data-dept="<?= (int)$deptId ?>">
                <?= htmlspecialchars($p['name']) ?>
                <small style="color:var(--text-muted);font-size:11px;margin-left:4px;">(<?= htmlspecialchars($p['department_name'] ?? '') ?>)</small>
              </label>
            <?php endforeach; ?>
          <?php endforeach; ?>
        </div>
      </div>
      <div class="modal-actions">
        <button type="button" class="btn-secondary" onclick="closeModal('addUserModal')">Cancel</button>
        <button type="submit" class="btn-primary">Grant Access</button>
      </div>
    </form>
  </div>
</div>

<!-- ===================== MANAGE ACCESS MODAL ===================== -->
<div class="modal-overlay" id="accessModal">
  <div class="modal">
    <h3>Manage Access — <span id="accessUserName"></span></h3>
    <p style="font-size:12px;color:var(--text-muted);margin-top:-8px;margin-bottom:16px;">
      Login ID: <strong id="accessUserUsername" style="color:var(--blue-600);">—</strong>
    </p>
    <form method="POST" action="/admin/users/access">
      <input type="hidden" name="user_type" id="accessUserType">
      <input type="hidden" name="id" id="accessUserId">

      <div class="field">
        <label>Role</label>
        <select name="role_id" id="accessRoleId" style="width:100%;padding:10px;border:1px solid var(--border);border-radius:10px;">
          <option value="">— No Change —</option>
          <?php foreach ($roles as $r): ?>
            <option value="<?= $r['id'] ?>"><?= htmlspecialchars($r['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="field">
        <label>Reports To (Reporting Manager)</label>
        <select name="reports_to" id="accessReportsTo" style="width:100%;padding:10px;border:1px solid var(--border);border-radius:10px;">
          <option value="">— None —</option>
          <?php foreach ($reportsToCandidates as $rt): ?>
            <option value="<?= htmlspecialchars($rt['user_type']) ?>:<?= (int)$rt['id'] ?>">
              <?= htmlspecialchars($rt['name']) ?> <?= $rt['user_type'] === 'superadmin' ? '(Super Admin)' : '(Manager)' ?>
            </option>
          <?php endforeach; ?>
        </select>
        <small style="color:var(--text-muted);">Used automatically by future modules (KPI, Tasks, Approvals) — no extra setup needed there.</small>
      </div>

      <div class="field">
        <label>Department Access</label>
        <label style="display:flex;align-items:center;gap:7px;font-size:12.5px;font-weight:700;color:var(--blue-600);margin-bottom:8px;">
          <input type="checkbox" id="accessSelectAllDepts" onchange="toggleAllAccessDepts(this.checked)"> Select All Departments
        </label>
        <div class="checkbox-grid" id="accessDeptGrid">
          <?php foreach ($departments as $d): ?>
            <label>
              <input type="checkbox" name="department_ids[]" value="<?= $d['id'] ?>" class="dept-checkbox">
              <?= htmlspecialchars($d['name']) ?>
            </label>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="field">
        <label>Project Access <small style="text-transform:none;font-weight:500;">(all projects — assign independently of department)</small></label>
        <div class="checkbox-grid" id="accessProjGrid">
          <?php foreach ($projectsByDept as $deptId => $projects): ?>
            <?php foreach ($projects as $p): ?>
              <label class="proj-option" data-dept="<?= (int)$deptId ?>">
                <input type="checkbox" name="project_ids[]" value="<?= $p['id'] ?>" class="proj-checkbox" data-dept="<?= (int)$deptId ?>">
                <?= htmlspecialchars($p['name']) ?>
                <small style="color:var(--text-muted);font-size:11px;margin-left:4px;">(<?= htmlspecialchars($p['department_name'] ?? '') ?>)</small>
              </label>
            <?php endforeach; ?>
          <?php endforeach; ?>
          <span id="accessNoDeptMsg" style="display:none;"></span>
        </div>
      </div>

      <div class="modal-actions">
        <button type="button" class="btn-secondary" onclick="closeModal('accessModal')">Cancel</button>
        <button type="submit" class="btn-primary">Save Access</button>
      </div>
    </form>

    <hr style="margin:22px 0;border:none;border-top:1px solid var(--border);">

    <h3 style="font-size:14px;">Reset Password</h3>
    <p style="font-size:12px;color:var(--text-muted);margin-top:-8px;margin-bottom:14px;">
      Sets a new password immediately — no email required. They'll be required to change it on next login.
    </p>
    <form method="POST" action="/admin/users/reset-password" onsubmit="return confirm('Reset this user\\'s password now? The old password will stop working immediately.');">
      <input type="hidden" name="user_type" id="resetUserType">
      <input type="hidden" name="id" id="resetUserId">
      <div class="field">
        <label>New Temporary Password</label>
        <div style="display:flex;gap:8px;">
          <input type="text" name="new_password" id="resetNewPassword" required minlength="8" style="flex:1;">
          <button type="button" class="btn-secondary" onclick="generateTempPassword()">🎲 Generate</button>
        </div>
        <small style="color:var(--text-muted);">Click "Generate" for a random password, or type your own — then click Save below to apply it.</small>
      </div>
      <div class="modal-actions">
        <button type="submit" class="btn-primary" style="padding:11px 22px;font-size:13px;">💾 Save New Password</button>
      </div>
    </form>
  </div>
</div>

<script>
function openModal(id){ document.getElementById(id).classList.add('open'); }
function closeModal(id){ document.getElementById(id).classList.remove('open'); }

function toggleGrantPersonList(){
  const type = document.getElementById('grantUserType').value;
  document.getElementById('managerPickerField').style.display = type === 'manager' ? 'block' : 'none';
  document.getElementById('employeePickerField').style.display = type === 'employee' ? 'block' : 'none';
  document.getElementById('managerPicker').name = type === 'manager' ? 'existing_id' : 'existing_id_disabled';
  document.getElementById('employeePicker').name = type === 'employee' ? 'existing_id' : 'existing_id_disabled';
  // Keep the "add new person" name fields in sync with whichever picker is active,
  // and collapse/clear the inactive one so it never gets submitted alongside it.
  document.getElementById('managerNewName').name = type === 'manager' ? 'new_person_name' : 'new_person_name_disabled';
  document.getElementById('employeeNewName').name = type === 'employee' ? 'new_person_name' : 'new_person_name_disabled';
  if (type !== 'manager') { document.getElementById('managerNewNameField').style.display = 'none'; document.getElementById('managerNewName').value = ''; }
  if (type !== 'employee') { document.getElementById('employeeNewNameField').style.display = 'none'; document.getElementById('employeeNewName').value = ''; }
}
function toggleNewPersonField(kind){
  const field = document.getElementById(kind + 'NewNameField');
  const showing = field.style.display !== 'none';
  field.style.display = showing ? 'none' : 'block';
  if (showing) { document.getElementById(kind + 'NewName').value = ''; }
  else { document.getElementById(kind === 'manager' ? 'managerPicker' : 'employeePicker').value = ''; }
}
function clearNewPersonName(kind){
  // If the Super Admin picks someone from the dropdown after having typed a
  // new name, clear the typed name so only one or the other is ever sent.
  const field = document.getElementById(kind + 'NewNameField');
  document.getElementById(kind + 'NewName').value = '';
  field.style.display = 'none';
}

function suggestGrantCredentials(selectEl){
  const label = selectEl.options[selectEl.selectedIndex]?.text || '';
  const namePart = label.split('(')[0].trim(); // strip "(Dept)" suffix if present
  if (!namePart) return;

  const words = namePart.split(/\s+/).filter(Boolean);
  const first = (words[0] || '').toLowerCase().replace(/[^a-z]/g, '');
  const last = (words[words.length - 1] || '').toLowerCase().replace(/[^a-z]/g, '');
  const username = last && last !== first ? `${first}.${last}` : first;

  document.getElementById('grantUsername').value = username;

  const firstCap = first ? first.charAt(0).toUpperCase() + first.slice(1) : 'User';
  const num = Math.floor(1000 + Math.random() * 9000);
  document.getElementById('grantPassword').value = `${firstCap}@${num}`;
}

function generateGrantPassword(){
  const username = document.getElementById('grantUsername').value || 'user';
  const first = username.split('.')[0];
  const firstCap = first ? first.charAt(0).toUpperCase() + first.slice(1) : 'User';
  const num = Math.floor(1000 + Math.random() * 9000);
  document.getElementById('grantPassword').value = `${firstCap}@${num}`;
}
document.getElementById('managerPicker').addEventListener('change', e => suggestGrantCredentials(e.target));
document.getElementById('employeePicker').addEventListener('change', e => suggestGrantCredentials(e.target));

function toggleAllGrantDepts(checked){
  document.querySelectorAll('.grant-dept-checkbox').forEach(cb => cb.checked = checked);
  filterGrantProjects();
}

function toggleAllAccessDepts(checked){
  document.querySelectorAll('.dept-checkbox').forEach(cb => cb.checked = checked);
  filterAccessProjects();
}

function filterGrantProjects(){
  // Projects are always visible — department checkboxes only control dept access.
}

function filterAccessProjects(){
  // Projects are always visible — department checkboxes only control dept access.
}
document.querySelectorAll('.dept-checkbox').forEach(cb => cb.addEventListener('change', filterAccessProjects));

function openAccessModal(user){
  document.getElementById('accessUserName').textContent = user.name;
  document.getElementById('accessUserUsername').textContent = user.username ? '@' + user.username : '— not set —';
  document.getElementById('accessUserType').value = user.user_type;
  document.getElementById('accessUserId').value = user.id;
  document.getElementById('accessRoleId').value = user.role_id || '';
  document.getElementById('accessReportsTo').value = user.reports_to || '';
  document.getElementById('accessSelectAllDepts').checked = false;

  document.getElementById('resetUserType').value = user.user_type;
  document.getElementById('resetUserId').value = user.id;
  document.getElementById('resetNewPassword').value = '';
  window._currentAccessUserName = user.name;

  document.querySelectorAll('.dept-checkbox').forEach(cb => {
    cb.checked = user.department_ids.includes(parseInt(cb.value));
  });

  filterAccessProjects(); // reveal project rows for the now-checked departments first

  document.querySelectorAll('.proj-checkbox').forEach(cb => {
    cb.checked = user.project_ids.includes(parseInt(cb.value));
  });

  openModal('accessModal');
}

function generateTempPassword(){
  const name = (window._currentAccessUserName || 'User').split(' ')[0].replace(/[^a-zA-Z]/g, '');
  const first = name ? name.charAt(0).toUpperCase() + name.slice(1).toLowerCase() : 'User';
  const num = Math.floor(1000 + Math.random() * 9000);
  document.getElementById('resetNewPassword').value = `${first}@${num}`;
}

// close modal when clicking outside the box
document.querySelectorAll('.modal-overlay').forEach(overlay => {
  overlay.addEventListener('click', e => { if (e.target === overlay) overlay.classList.remove('open'); });
});

// Ensure the correct field names are active for the default selected User
// Type as soon as the page loads (not just after the dropdown is changed),
// so the Manager picker/new-name field are the ones actually submitted by
// default, matching whichever option is selected.
toggleGrantPersonList();
</script>

<?php require __DIR__ . '/../layout/admin_footer.php'; ?>
