<?php
$title = 'Utilisateurs';
$base  = rtrim(App\Core\Config::baseUrl(), '/');

$roleColors = [
    'admin'       => ['bg' => '#fef2f2', 'color' => '#b91c1c', 'icon' => 'fa-crown'],
    'manager'     => ['bg' => '#faf5ff', 'color' => '#7e22ce', 'icon' => 'fa-briefcase'],
    'superviseur' => ['bg' => '#fff7ed', 'color' => '#c2410c', 'icon' => 'fa-binoculars'],
    'supervisor'  => ['bg' => '#fff7ed', 'color' => '#c2410c', 'icon' => 'fa-binoculars'],
    'technicien'  => ['bg' => '#f0fdf4', 'color' => '#15803d', 'icon' => 'fa-screwdriver-wrench'],
    'agent'       => ['bg' => '#eff6ff', 'color' => '#1d4ed8', 'icon' => 'fa-headset'],
];
$defaultRole = ['bg' => '#f1f5f9', 'color' => '#475569', 'icon' => 'fa-user'];
$technicianTypeLabels = [
  'etude_raccordement' => 'Etude & Raccordement',
  'raccordement' => 'Raccordement',
  'backbones' => 'Backbones',
  'maintenance_ftth' => 'Maintenance FTTH',
  'etude' => 'Etude',
];
$technicianTypeOptionsByRole = $technicianTypeOptionsByRole ?? [];

$now = new DateTimeImmutable('now');

$formatLastLogin = static function (?string $value, ?string $source = null) use ($now): array {
  if (empty($value)) {
    return [
      'label' => 'Jamais connecté',
      'detail' => 'Aucune connexion enregistrée',
      'tone' => 'never',
    ];
  }

  try {
    $loginAt = new DateTimeImmutable($value);
    $diff = $now->getTimestamp() - $loginAt->getTimestamp();
    $minutes = max(0, (int) floor($diff / 60));
    $hours = max(0, (int) floor($diff / 3600));
    $days = max(0, (int) floor($diff / 86400));

    if ($minutes < 1) {
      $detail = 'à l’instant';
    } elseif ($minutes < 60) {
      $detail = 'il y a ' . $minutes . ' min';
    } elseif ($hours < 24) {
      $detail = 'il y a ' . $hours . ' h';
    } else {
      $detail = 'il y a ' . $days . ' j';
    }

    $channelDetail = match ($source) {
      'mobile' => 'via mobile',
      'device' => 'activité appareil',
      default => 'via plateforme',
    };

    return [
      'label' => $loginAt->format('d/m/Y H:i'),
      'detail' => trim($detail . ' • ' . $channelDetail),
      'tone' => $minutes <= 15 ? 'live' : ($hours < 24 ? 'recent' : 'idle'),
    ];
  } catch (Throwable $e) {
    return [
      'label' => 'Date invalide',
      'detail' => 'Valeur de connexion illisible',
      'tone' => 'never',
    ];
  }
};

$resolveUserStatus = static function (array $user, array $lastLoginMeta): array {
  $isActive = (int)($user['active'] ?? 0) === 1;
  if (!$isActive) {
    return [
      'label' => 'Inactif',
      'detail' => 'Compte désactivé',
      'tone' => 'inactive',
      'animate' => false,
    ];
  }

  return match ($lastLoginMeta['tone']) {
    'live' => [
      'label' => 'Connecté récemment',
      'detail' => 'Connexion enregistrée il y a moins de 15 min',
      'tone' => 'live',
      'animate' => true,
    ],
    'recent' => [
      'label' => 'Actif',
      'detail' => 'Vu aujourd’hui',
      'tone' => 'recent',
      'animate' => true,
    ],
    'idle' => [
      'label' => 'Actif',
      'detail' => 'Pas de connexion récente',
      'tone' => 'idle',
      'animate' => false,
    ],
    default => [
      'label' => 'À activer',
      'detail' => 'Compte créé sans connexion',
      'tone' => 'never',
      'animate' => false,
    ],
  };
};

// Comptages par rôle
$counts = [];
foreach ($users as $u) {
    $r = $u['role_key'] ?? 'agent';
    $counts[$r] = ($counts[$r] ?? 0) + 1;
}
$totalActive   = count(array_filter($users, fn($u) => (int)$u['active'] === 1));
$totalInactive = count($users) - $totalActive;

// Lire le message d'alerte éventuel
$flashSuccess = $_GET['success'] ?? null;
$flashError   = $_GET['error'] ?? null;
$successMessages = [
    'user_updated' => 'Utilisateur modifié avec succès.',
    'user_deleted' => 'Utilisateur supprimé avec succès.',
];
$errorMessages = [
    'invalid_data'       => 'Données invalides.',
    'user_not_found'     => 'Utilisateur introuvable.',
    'email_exists'       => 'Cet email est déjà utilisé par un autre compte.',
    'update_failed'      => 'Échec de la modification.',
    'cannot_delete_self' => 'Vous ne pouvez pas supprimer votre propre compte.',
    'delete_failed'      => 'Échec de la suppression.',
];
?>

<!-- ── Toasts ──────────────────────────────────────────────────── -->
<?php if ($flashSuccess || $flashError): ?>
<div class="position-fixed bottom-0 end-0 p-3" style="z-index:1100;">
  <div id="pageToast" class="toast align-items-center border-0 text-white <?= $flashSuccess ? 'bg-success' : 'bg-danger' ?>" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="d-flex">
      <div class="toast-body fw-semibold">
        <i class="fas <?= $flashSuccess ? 'fa-circle-check' : 'fa-circle-exclamation' ?> me-2"></i>
        <?= htmlspecialchars($flashSuccess ? ($successMessages[$flashSuccess] ?? 'Opération réussie.') : ($errorMessages[$flashError] ?? 'Une erreur est survenue.')) ?>
      </div>
      <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Fermer"></button>
    </div>
  </div>
</div>
<?php endif; ?>

<style>
  .user-status-badge {
    display: inline-flex;
    align-items: center;
    gap: .55rem;
    padding: .45rem .8rem;
    border-radius: 999px;
    font-weight: 700;
    font-size: .78rem;
    line-height: 1;
    position: relative;
    overflow: hidden;
  }

  .user-status-badge::after {
    content: '';
    position: absolute;
    inset: 0;
    background: linear-gradient(120deg, transparent 20%, rgba(255,255,255,.35) 50%, transparent 80%);
    transform: translateX(-120%);
    opacity: 0;
  }

  .user-status-badge.is-animated::after {
    opacity: 1;
    animation: userStatusShimmer 2.8s linear infinite;
  }

  .user-status-dot {
    width: .55rem;
    height: .55rem;
    border-radius: 50%;
    display: inline-block;
    flex-shrink: 0;
    box-shadow: 0 0 0 0 currentColor;
  }

  .user-status-badge.is-animated .user-status-dot {
    animation: userStatusPulse 1.6s ease-out infinite;
  }

  .user-status--live {
    background: rgba(22, 163, 74, .12);
    color: #15803d;
  }

  .user-status--recent {
    background: rgba(14, 165, 233, .12);
    color: #0369a1;
  }

  .user-status--idle {
    background: rgba(71, 85, 105, .12);
    color: #475569;
  }

  .user-status--inactive {
    background: rgba(220, 38, 38, .12);
    color: #b91c1c;
  }

  .user-status--never {
    background: rgba(245, 158, 11, .14);
    color: #b45309;
  }

  .user-last-login {
    display: flex;
    flex-direction: column;
    gap: .2rem;
  }

  @keyframes userStatusPulse {
    0% { box-shadow: 0 0 0 0 rgba(255,255,255,.1); }
    70% { box-shadow: 0 0 0 9px rgba(255,255,255,0); }
    100% { box-shadow: 0 0 0 0 rgba(255,255,255,0); }
  }

  @keyframes userStatusShimmer {
    0% { transform: translateX(-120%); }
    100% { transform: translateX(120%); }
  }
</style>

<!-- ── En-tête de page ────────────────────────────────────────── -->
<div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-4">
  <div>
    <h4 class="fw-bold mb-0" style="letter-spacing:-.02em;">Gestion des utilisateurs</h4>
    <p class="text-muted small mb-0 mt-1"><?= count($users) ?> compte<?= count($users) > 1 ? 's' : '' ?> enregistré<?= count($users) > 1 ? 's' : '' ?></p>
  </div>
  <button class="btn btn-primary d-inline-flex align-items-center gap-2"
          data-bs-toggle="modal" data-bs-target="#createUserModal">
    <i class="fas fa-user-plus"></i>
    <span>Nouvel utilisateur</span>
  </button>
</div>

<!-- ── Cartes de résumé ───────────────────────────────────────── -->
<div class="row g-3 mb-4">
  <div class="col-6 col-md-3">
    <div class="card border-0 shadow-sm h-100" style="border-radius:.875rem;">
      <div class="card-body d-flex align-items-center gap-3 py-3">
        <div class="rounded-3 d-flex align-items-center justify-content-center flex-shrink-0"
             style="width:44px;height:44px;background:#eff6ff;">
          <i class="fas fa-users" style="color:#1d4ed8;font-size:1.1rem;"></i>
        </div>
        <div>
          <div class="fw-bold fs-4 lh-1"><?= count($users) ?></div>
          <div class="text-muted" style="font-size:.8rem;">Total</div>
        </div>
      </div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="card border-0 shadow-sm h-100" style="border-radius:.875rem;">
      <div class="card-body d-flex align-items-center gap-3 py-3">
        <div class="rounded-3 d-flex align-items-center justify-content-center flex-shrink-0"
             style="width:44px;height:44px;background:#f0fdf4;">
          <i class="fas fa-circle-check" style="color:#15803d;font-size:1.1rem;"></i>
        </div>
        <div>
          <div class="fw-bold fs-4 lh-1"><?= $totalActive ?></div>
          <div class="text-muted" style="font-size:.8rem;">Actifs</div>
        </div>
      </div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="card border-0 shadow-sm h-100" style="border-radius:.875rem;">
      <div class="card-body d-flex align-items-center gap-3 py-3">
        <div class="rounded-3 d-flex align-items-center justify-content-center flex-shrink-0"
             style="width:44px;height:44px;background:#fef2f2;">
          <i class="fas fa-ban" style="color:#b91c1c;font-size:1.1rem;"></i>
        </div>
        <div>
          <div class="fw-bold fs-4 lh-1"><?= $totalInactive ?></div>
          <div class="text-muted" style="font-size:.8rem;">Inactifs</div>
        </div>
      </div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="card border-0 shadow-sm h-100" style="border-radius:.875rem;">
      <div class="card-body d-flex align-items-center gap-3 py-3">
        <div class="rounded-3 d-flex align-items-center justify-content-center flex-shrink-0"
             style="width:44px;height:44px;background:#faf5ff;">
          <i class="fas fa-screwdriver-wrench" style="color:#7e22ce;font-size:1.1rem;"></i>
        </div>
        <div>
          <div class="fw-bold fs-4 lh-1"><?= ($counts['technicien'] ?? 0) ?></div>
          <div class="text-muted" style="font-size:.8rem;">Techniciens</div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- ── Tableau ────────────────────────────────────────────────── -->
<div class="card border-0 shadow-sm" style="border-radius:.875rem;overflow:hidden;">

  <!-- Barre de recherche + filtre -->
  <div class="card-header bg-white border-bottom d-flex flex-wrap gap-2 align-items-center py-3 px-4">
    <div class="input-group" style="max-width:280px;">
      <span class="input-group-text bg-light border-end-0">
        <i class="fas fa-magnifying-glass text-muted" style="font-size:.85rem;"></i>
      </span>
      <input type="search" id="userSearch" class="form-control border-start-0 bg-light"
             placeholder="Rechercher…" style="font-size:.875rem;">
    </div>
    <select id="roleFilter" class="form-select" style="width:auto;font-size:.875rem;">
      <option value="">Tous les rôles</option>
      <option value="admin">Admin</option>
      <option value="manager">Manager</option>
      <option value="superviseur">Superviseur</option>
      <option value="technicien">Technicien</option>
      <option value="agent">Agent</option>
    </select>
    <select id="statusFilter" class="form-select" style="width:auto;font-size:.875rem;">
      <option value="">Tous les statuts</option>
      <option value="1">Actifs</option>
      <option value="0">Inactifs</option>
    </select>
    <span id="filteredCount" class="text-muted ms-auto" style="font-size:.82rem;white-space:nowrap;"></span>
  </div>

  <div class="table-responsive">
    <table class="table mb-0" id="usersTable" style="font-size:.875rem;">
      <thead style="background:#f8fafc;">
        <tr>
          <th class="px-4 py-3 fw-semibold text-muted border-0" style="font-size:.78rem;letter-spacing:.04em;text-transform:uppercase;">Utilisateur</th>
          <th class="py-3 fw-semibold text-muted border-0" style="font-size:.78rem;letter-spacing:.04em;text-transform:uppercase;">Rôle</th>
          <th class="py-3 fw-semibold text-muted border-0" style="font-size:.78rem;letter-spacing:.04em;text-transform:uppercase;">Statut</th>
          <th class="py-3 fw-semibold text-muted border-0" style="font-size:.78rem;letter-spacing:.04em;text-transform:uppercase;">Dernière connexion</th>
          <th class="py-3 fw-semibold text-muted border-0" style="font-size:.78rem;letter-spacing:.04em;text-transform:uppercase;">2FA</th>
          <th class="py-3 fw-semibold text-muted border-0 text-end pe-4" style="font-size:.78rem;letter-spacing:.04em;text-transform:uppercase;">Actions</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach ($users as $u):
        $role     = $u['role_key'] ?? 'agent';
        $technicianType = (string)($u['technician_type'] ?? '');
        $assignedCity = trim((string)($u['assigned_city'] ?? ''));
        $rc       = $roleColors[$role] ?? $defaultRole;
        $initials = mb_strtoupper(mb_substr($u['name'] ?? '?', 0, 1));
        $isActive = (int)$u['active'] === 1;
        $lastLoginMeta = $formatLastLogin($u['last_activity_at'] ?? ($u['last_login'] ?? null), $u['last_activity_source'] ?? null);
        $statusMeta = $resolveUserStatus($u, $lastLoginMeta);
        // Palette d'avatar basée sur l'ID
        $avatarPalette = ['#6366f1','#0ea5e9','#10b981','#f59e0b','#ef4444','#8b5cf6','#14b8a6'];
        $avatarBg = $avatarPalette[$u['id'] % count($avatarPalette)];
      ?>
        <tr class="user-row border-top"
            data-name="<?= htmlspecialchars(strtolower($u['name'] . ' ' . $u['email'])) ?>"
            data-role="<?= htmlspecialchars($role) ?>"
          data-technician-type="<?= htmlspecialchars($technicianType) ?>"
            data-active="<?= $isActive ? '1' : '0' ?>">
          <td class="px-4 py-3">
            <div class="d-flex align-items-center gap-3">
              <div class="rounded-circle d-flex align-items-center justify-content-center fw-bold text-white flex-shrink-0"
                   style="width:38px;height:38px;background:<?= htmlspecialchars($avatarBg) ?>;font-size:.9rem;overflow:hidden;">
                <?php if (!empty($u['photo_url'])): ?>
                  <img src="<?= htmlspecialchars($u['photo_url']) ?>" alt="<?= htmlspecialchars($u['name']) ?>" style="width:100%;height:100%;object-fit:cover;">
                <?php else: ?>
                  <?= htmlspecialchars($initials) ?>
                <?php endif; ?>
              </div>
              <div>
                <div class="fw-semibold lh-1 mb-1"><?= htmlspecialchars($u['name']) ?></div>
                <div class="text-muted" style="font-size:.8rem;"><?= htmlspecialchars($u['email']) ?></div>
                <?php if ($assignedCity !== ''): ?>
                <div class="text-muted d-inline-flex align-items-center gap-1 mt-1" style="font-size:.75rem;">
                  <i class="fas fa-city"></i>
                  <span><?= htmlspecialchars($assignedCity) ?></span>
                </div>
                <?php endif; ?>
              </div>
            </div>
          </td>
          <td class="py-3 align-middle">
            <div class="d-flex flex-column gap-1 align-items-start">
              <span class="d-inline-flex align-items-center gap-1 px-2 py-1 rounded-pill fw-semibold"
                    style="font-size:.78rem;background:<?= htmlspecialchars($rc['bg']) ?>;color:<?= htmlspecialchars($rc['color']) ?>;">
                <i class="fas <?= htmlspecialchars($rc['icon']) ?>" style="font-size:.72rem;"></i>
                <?= htmlspecialchars(ucfirst($role)) ?>
              </span>
                <?php if (in_array($role, ['technicien', 'technician', 'agent', 'superviseur', 'supervisor'], true) && $technicianType !== ''): ?>
              <span class="d-inline-flex align-items-center gap-1 px-2 py-1 rounded-pill fw-semibold"
                    style="font-size:.74rem;background:#ecfeff;color:#0f766e;">
                <i class="fas fa-layer-group" style="font-size:.68rem;"></i>
                <?= htmlspecialchars($technicianTypeLabels[$technicianType] ?? ucfirst(str_replace('_', ' ', $technicianType))) ?>
              </span>
              <?php endif; ?>
            </div>
          </td>
          <td class="py-3 align-middle">
            <div class="d-flex flex-column gap-1">
              <span class="user-status-badge user-status--<?= htmlspecialchars($statusMeta['tone']) ?><?= !empty($statusMeta['animate']) ? ' is-animated' : '' ?>">
                <span class="user-status-dot" aria-hidden="true"></span>
                <?= htmlspecialchars($statusMeta['label']) ?>
              </span>
              <span class="text-muted" style="font-size:.76rem;"><?= htmlspecialchars($statusMeta['detail']) ?></span>
            </div>
          </td>
          <td class="py-3 align-middle">
            <div class="user-last-login">
              <span class="fw-semibold text-dark"><?= htmlspecialchars($lastLoginMeta['label']) ?></span>
              <span class="text-muted" style="font-size:.76rem;"><?= htmlspecialchars($lastLoginMeta['detail']) ?></span>
            </div>
          </td>
          <td class="py-3 align-middle">
            <a href="<?= htmlspecialchars(route_url('/users/toggle2fa', ['id' => (int)$u['id']])) ?>"
               class="btn btn-sm d-inline-flex align-items-center gap-1"
               style="font-size:.78rem;border-radius:.5rem;background:#f1f5f9;border:1px solid #e2e8f0;color:#475569;"
               title="Activer / Désactiver la 2FA">
              <i class="fas fa-shield-halved"></i>
              <span>2FA</span>
            </a>
          </td>
          <td class="py-3 align-middle text-end pe-4">
            <div class="d-inline-flex gap-2">
              <button class="btn btn-sm d-inline-flex align-items-center gap-1"
                      style="font-size:.8rem;border-radius:.5rem;background:#eff6ff;border:1px solid #dbeafe;color:#1d4ed8;"
                      onclick="editUser(<?= (int)$u['id'] ?>, '<?= htmlspecialchars($u['name'], ENT_QUOTES) ?>', '<?= htmlspecialchars($u['email'], ENT_QUOTES) ?>', '<?= htmlspecialchars($role, ENT_QUOTES) ?>', '<?= htmlspecialchars($technicianType, ENT_QUOTES) ?>', '<?= htmlspecialchars($assignedCity, ENT_QUOTES) ?>', <?= (int)$u['active'] ?>, '<?= htmlspecialchars((string)($u['photo_url'] ?? ''), ENT_QUOTES) ?>')"
                      title="Modifier">
                <i class="fas fa-pen-to-square"></i>
                <span class="d-none d-md-inline">Modifier</span>
              </button>
              <button class="btn btn-sm d-inline-flex align-items-center gap-1"
                      style="font-size:.8rem;border-radius:.5rem;background:#fef2f2;border:1px solid #fecaca;color:#b91c1c;"
                      onclick="deleteUser(<?= (int)$u['id'] ?>, '<?= htmlspecialchars($u['name'], ENT_QUOTES) ?>')"
                      title="Supprimer">
                <i class="fas fa-trash-can"></i>
                <span class="d-none d-md-inline">Supprimer</span>
              </button>
            </div>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <!-- État vide après filtre -->
  <div id="emptyState" class="text-center py-5 d-none">
    <i class="fas fa-user-slash fa-2x text-muted mb-3 d-block"></i>
    <p class="text-muted mb-0">Aucun utilisateur ne correspond à vos critères.</p>
  </div>

</div>


<!-- ══ Modal : Créer un utilisateur ══════════════════════════════ -->
<div class="modal fade" id="createUserModal" tabindex="-1" aria-labelledby="createUserLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0 shadow-lg" style="border-radius:1rem;overflow:hidden;">
      <div class="modal-header border-0 pb-0 px-4 pt-4">
        <div>
          <h5 class="modal-title fw-bold mb-1" id="createUserLabel">Nouvel utilisateur</h5>
          <p class="text-muted small mb-0">Renseignez les informations du compte à créer.</p>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>
      <form method="post" action="<?= htmlspecialchars(route_url('/users/create')) ?>" class="needs-validation" enctype="multipart/form-data" novalidate>
        <div class="modal-body px-4 py-3">
          <div class="mb-3">
            <label class="form-label fw-medium" style="font-size:.875rem;">Nom complet</label>
            <input name="name" class="form-control" placeholder="Jean Dupont" required>
            <div class="invalid-feedback">Nom requis.</div>
          </div>
          <div class="mb-3">
            <label class="form-label fw-medium" style="font-size:.875rem;">Adresse email</label>
            <input name="email" type="email" class="form-control" placeholder="jean@domaine.com" required>
            <div class="invalid-feedback">Email valide requis.</div>
          </div>
          <div class="mb-3">
            <label class="form-label fw-medium" style="font-size:.875rem;">Mot de passe</label>
            <input name="password" type="password" class="form-control" placeholder="Min. 6 caractères" required minlength="6">
            <div class="invalid-feedback">Mot de passe requis (min 6 car.).</div>
          </div>
          <div class="mb-1">
            <label class="form-label fw-medium" style="font-size:.875rem;">Rôle</label>
            <select name="role_key" class="form-select js-role-select" data-technician-target="createTechnicianTypeWrap" required>
              <option value="agent">Agent</option>
              <option value="technicien">Technicien</option>
              <option value="superviseur">Superviseur</option>
              <option value="manager">Manager</option>
              <option value="admin">Admin</option>
            </select>
          </div>
          <div class="mt-3 d-none" id="createTechnicianTypeWrap">
            <label class="form-label fw-medium" style="font-size:.875rem;">Type métier</label>
            <select name="technician_type" id="create_technician_type" class="form-select js-technician-type-select">
              <option value="">Sélectionner un type</option>
              <?php foreach (($technicianTypeOptions ?? []) as $technicianTypeOption): ?>
              <option value="<?= htmlspecialchars($technicianTypeOption) ?>"><?= htmlspecialchars($technicianTypeLabels[$technicianTypeOption] ?? ucfirst(str_replace('_', ' ', $technicianTypeOption))) ?></option>
              <?php endforeach; ?>
            </select>
            <div class="form-text">Utilisez ce champ pour distinguer le périmètre métier de validation ou d'intervention: Raccordement, Backbones, Maintenance FTTH ou Etude.</div>
          </div>
          <div class="mt-3">
            <label class="form-label fw-medium" style="font-size:.875rem;">Ville de rattachement</label>
            <input name="assigned_city" class="form-control" placeholder="Abidjan">
            <div class="form-text">L'utilisateur ne gérera que les actions liées à cette ville. Laissez vide pour un périmètre global.</div>
          </div>
          <div class="mt-3">
            <label class="form-label fw-medium" style="font-size:.875rem;">Photo de profil</label>
            <input name="photo" type="file" class="form-control" accept="image/png,image/jpeg,image/webp">
            <div class="form-text">JPG, PNG ou WebP. Cette photo sera affichée devant le nom du technicien.</div>
          </div>
        </div>
        <div class="modal-footer border-0 px-4 pb-4 pt-2 gap-2">
          <button type="button" class="btn btn-light" data-bs-dismiss="modal">Annuler</button>
          <button type="submit" class="btn btn-primary d-inline-flex align-items-center gap-2">
            <i class="fas fa-user-plus"></i> Créer le compte
          </button>
        </div>
      </form>
    </div>
  </div>
</div>


<!-- ══ Modal : Modifier un utilisateur ═══════════════════════════ -->
<div class="modal fade" id="editUserModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0 shadow-lg" style="border-radius:1rem;overflow:hidden;">
      <div class="modal-header border-0 pb-0 px-4 pt-4">
        <div>
          <h5 class="modal-title fw-bold mb-1">Modifier l'utilisateur</h5>
          <p class="text-muted small mb-0" id="editUserSubtitle">Mettez à jour les informations du compte.</p>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>
      <form method="post" action="<?= htmlspecialchars(route_url('/users/update')) ?>" id="editUserForm" class="needs-validation" enctype="multipart/form-data" novalidate>
        <div class="modal-body px-4 py-3">
          <input type="hidden" name="user_id" id="edit_user_id">
          <div class="mb-3 d-flex align-items-center gap-3">
            <div id="editPhotoPreview" class="rounded-circle d-flex align-items-center justify-content-center text-white fw-bold" style="width:56px;height:56px;background:#2563eb;overflow:hidden;">?</div>
            <div>
              <div class="fw-medium" style="font-size:.875rem;">Photo actuelle</div>
              <div class="text-muted" style="font-size:.78rem;">Ajoutez une nouvelle photo pour la remplacer.</div>
            </div>
          </div>
          <div class="mb-3">
            <label class="form-label fw-medium" style="font-size:.875rem;">Nom complet</label>
            <input type="text" name="name" id="edit_name" class="form-control" required>
            <div class="invalid-feedback">Nom requis.</div>
          </div>
          <div class="mb-3">
            <label class="form-label fw-medium" style="font-size:.875rem;">Adresse email</label>
            <input type="email" name="email" id="edit_email" class="form-control" required>
            <div class="invalid-feedback">Email valide requis.</div>
          </div>
          <div class="mb-3">
            <label class="form-label fw-medium" style="font-size:.875rem;">Rôle</label>
            <select name="role_key" id="edit_role_key" class="form-select js-role-select" data-technician-target="editTechnicianTypeWrap" required>
              <option value="agent">Agent</option>
              <option value="technicien">Technicien</option>
              <option value="superviseur">Superviseur</option>
              <option value="manager">Manager</option>
              <option value="admin">Admin</option>
            </select>
          </div>
          <div class="mb-3 d-none" id="editTechnicianTypeWrap">
            <label class="form-label fw-medium" style="font-size:.875rem;">Type métier</label>
            <select name="technician_type" id="edit_technician_type" class="form-select js-technician-type-select">
              <option value="">Sélectionner un type</option>
              <?php foreach (($technicianTypeOptions ?? []) as $technicianTypeOption): ?>
              <option value="<?= htmlspecialchars($technicianTypeOption) ?>"><?= htmlspecialchars($technicianTypeLabels[$technicianTypeOption] ?? ucfirst(str_replace('_', ' ', $technicianTypeOption))) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="mb-3">
            <label class="form-label fw-medium" style="font-size:.875rem;">Ville de rattachement</label>
            <input type="text" name="assigned_city" id="edit_assigned_city" class="form-control" placeholder="Abidjan">
          </div>
          <div class="mb-3">
            <div class="form-check">
              <input type="checkbox" name="active" id="edit_active" class="form-check-input" value="1">
              <label class="form-check-label" for="edit_active" style="font-size:.875rem;">Compte actif</label>
            </div>
          </div>
          <div class="mb-1">
            <label class="form-label fw-medium" style="font-size:.875rem;">Nouveau mot de passe <span class="text-muted fw-normal">(optionnel)</span></label>
            <input type="password" name="password" id="edit_password" class="form-control"
                   placeholder="Laisser vide pour ne pas modifier">
          </div>
          <div class="mt-3">
            <label class="form-label fw-medium" style="font-size:.875rem;">Photo de profil</label>
            <input name="photo" type="file" id="edit_photo" class="form-control" accept="image/png,image/jpeg,image/webp">
          </div>
        </div>
        <div class="modal-footer border-0 px-4 pb-4 pt-2 gap-2">
          <button type="button" class="btn btn-light" data-bs-dismiss="modal">Annuler</button>
          <button type="submit" class="btn btn-primary d-inline-flex align-items-center gap-2">
            <i class="fas fa-floppy-disk"></i> Enregistrer
          </button>
        </div>
      </form>
    </div>
  </div>
</div>


<!-- ══ Modal : Confirmer suppression ═════════════════════════════ -->
<div class="modal fade" id="deleteUserModal" tabindex="-1" aria-labelledby="deleteUserLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-sm">
    <div class="modal-content border-0 shadow-lg" style="border-radius:1rem;overflow:hidden;">
      <div class="modal-body px-4 pt-4 pb-3 text-center">
        <div class="rounded-circle bg-danger bg-opacity-10 d-inline-flex align-items-center justify-content-center mb-3"
             style="width:56px;height:56px;">
          <i class="fas fa-trash-can text-danger fa-lg"></i>
        </div>
        <h5 class="fw-bold mb-1">Supprimer le compte ?</h5>
        <p class="text-muted small mb-0">
          Cette action est définitive. Le compte de <strong id="deleteUserName" class="text-danger"></strong> sera supprimé.
        </p>
      </div>
      <div class="modal-footer border-0 px-4 pb-4 pt-1 gap-2 justify-content-center">
        <button type="button" class="btn btn-light px-4" data-bs-dismiss="modal">Annuler</button>
        <button type="button" class="btn btn-danger px-4" id="confirmDeleteUserBtn">
          <i class="fas fa-trash-can me-1"></i> Supprimer
        </button>
      </div>
    </div>
  </div>
</div>


<script>
(function () {
  'use strict';

  const technicianTypeOptionsByRole = <?= json_encode($technicianTypeOptionsByRole, JSON_UNESCAPED_UNICODE) ?>;

  // ── Toast flash ────────────────────────────────────────────────
  const toastEl = document.getElementById('pageToast');
  const currentUrl = new URL(window.location.href);
  const hadFlashParam = currentUrl.searchParams.has('success') || currentUrl.searchParams.has('error');
  if (toastEl) {
    bootstrap.Toast.getOrCreateInstance(toastEl, { delay: 4500 }).show();
  }
  if (hadFlashParam) {
    currentUrl.searchParams.delete('success');
    currentUrl.searchParams.delete('error');
    const cleanedUrl = currentUrl.pathname + (currentUrl.searchParams.toString() ? '?' + currentUrl.searchParams.toString() : '') + currentUrl.hash;
    window.history.replaceState({}, document.title, cleanedUrl);
  }

  // ── Validation Bootstrap 5 ────────────────────────────────────
  document.querySelectorAll('form.needs-validation').forEach(form => {
    form.addEventListener('submit', e => {
      if (!form.checkValidity()) { e.preventDefault(); e.stopPropagation(); }
      form.classList.add('was-validated');
    });
  });

  // ── Filtre / recherche tableau ────────────────────────────────
  const searchInput  = document.getElementById('userSearch');
  const roleFilter   = document.getElementById('roleFilter');
  const statusFilter = document.getElementById('statusFilter');
  const rows         = document.querySelectorAll('#usersTable tbody .user-row');
  const emptyState   = document.getElementById('emptyState');
  const countEl      = document.getElementById('filteredCount');

  function applyFilters() {
    const q      = searchInput.value.toLowerCase().trim();
    const role   = roleFilter.value;
    const status = statusFilter.value;
    let visible  = 0;

    rows.forEach(row => {
      const matchSearch = !q || row.dataset.name.includes(q);
      const matchRole   = !role   || row.dataset.role   === role;
      const matchStatus = !status || row.dataset.active === status;
      const show = matchSearch && matchRole && matchStatus;
      row.style.display = show ? '' : 'none';
      if (show) visible++;
    });

    emptyState.classList.toggle('d-none', visible > 0);
    countEl.textContent = (q || role || status) ? visible + ' résultat' + (visible > 1 ? 's' : '') : '';
  }

  searchInput.addEventListener('input',  applyFilters);
  roleFilter.addEventListener('change',  applyFilters);
  statusFilter.addEventListener('change', applyFilters);

  // ── Modal édition ─────────────────────────────────────────────
  function toggleTechnicianTypeField(select) {
    const targetId = select.dataset.technicianTarget;
    if (!targetId) return;
    const wrapper = document.getElementById(targetId);
    if (!wrapper) return;
    const typeSelect = wrapper.querySelector('.js-technician-type-select');
    const supportsTypedProfile = ['technicien', 'technician', 'agent', 'superviseur', 'supervisor'].includes(select.value);
    wrapper.classList.toggle('d-none', !supportsTypedProfile);
    if (typeSelect) {
      const allowedTypes = technicianTypeOptionsByRole[select.value] || [];
      Array.from(typeSelect.options).forEach((option) => {
        if (!option.value) {
          option.hidden = false;
          option.disabled = false;
          return;
        }
        const allowed = allowedTypes.includes(option.value);
        option.hidden = !allowed;
        option.disabled = !allowed;
      });
      typeSelect.required = supportsTypedProfile;
      if (!supportsTypedProfile || (typeSelect.value && !allowedTypes.includes(typeSelect.value))) {
        typeSelect.value = '';
      }
    }
  }

  document.querySelectorAll('.js-role-select').forEach((select) => {
    select.addEventListener('change', () => toggleTechnicianTypeField(select));
    toggleTechnicianTypeField(select);
  });

  window.editUser = function (id, name, email, roleKey, technicianType, assignedCity, active, photoUrl) {
    document.getElementById('edit_user_id').value = id;
    document.getElementById('edit_name').value    = name;
    document.getElementById('edit_email').value   = email;
    document.getElementById('edit_role_key').value = roleKey;
    document.getElementById('edit_technician_type').value = technicianType || '';
    document.getElementById('edit_assigned_city').value = assignedCity || '';
    document.getElementById('edit_active').checked = (active === 1);
    document.getElementById('edit_password').value = '';
    document.getElementById('edit_photo').value = '';
    document.getElementById('editUserSubtitle').textContent = 'Modification du compte de ' + name;
    const preview = document.getElementById('editPhotoPreview');
    if (photoUrl) {
      preview.innerHTML = '<img src="' + photoUrl.replace(/"/g, '&quot;') + '" alt="' + name.replace(/"/g, '&quot;') + '" style="width:100%;height:100%;object-fit:cover;">';
      preview.style.background = '#2563eb';
    } else {
      preview.textContent = (name || '?').trim().charAt(0).toUpperCase() || '?';
      preview.style.background = '#2563eb';
    }
    toggleTechnicianTypeField(document.getElementById('edit_role_key'));
    document.getElementById('editUserForm').classList.remove('was-validated');
    bootstrap.Modal.getOrCreateInstance(document.getElementById('editUserModal')).show();
  };

  // ── Modal suppression ─────────────────────────────────────────
  let userIdToDelete = null;

  window.deleteUser = function (id, name) {
    userIdToDelete = id;
    document.getElementById('deleteUserName').textContent = name;
    bootstrap.Modal.getOrCreateInstance(document.getElementById('deleteUserModal')).show();
  };

  document.getElementById('confirmDeleteUserBtn').addEventListener('click', () => {
    if (!userIdToDelete) return;
    const form   = document.createElement('form');
    form.method  = 'POST';
    form.action  = '<?= htmlspecialchars(route_url('/users/delete')) ?>';
    const input  = document.createElement('input');
    input.type   = 'hidden';
    input.name   = 'user_id';
    input.value  = userIdToDelete;
    form.appendChild(input);
    document.body.appendChild(form);
    form.submit();
  });
})();
</script>
