<?php
$title = 'Licences mobiles';
$flash = $flash ?? null;
$licenses = $licenses ?? [];
$events = $events ?? [];
$search = trim((string)($search ?? ''));

$total = count($licenses);
$enabledCount = count(array_filter($licenses, static fn(array $row): bool => (int)($row['is_enabled'] ?? 0) === 1));
$activatedCount = count(array_filter($licenses, static fn(array $row): bool => !empty($row['activated_at'])));
$pendingCount = count(array_filter($licenses, static fn(array $row): bool => (int)($row['is_enabled'] ?? 0) === 1 && empty($row['activated_at'])));

$statusFor = static function (array $row): array {
  if (!isset($row['is_enabled']) || $row['is_enabled'] === null) {
    return ['label' => 'À préparer', 'class' => 'light', 'detail' => 'Aucune licence mobile créée'];
  }
    if ((int)($row['is_enabled'] ?? 0) !== 1) {
        return ['label' => 'Suspendue', 'class' => 'secondary', 'detail' => 'Accès mobile coupé'];
    }
    if (!empty($row['activated_at'])) {
        return ['label' => 'Activée', 'class' => 'success', 'detail' => 'Première utilisation validée'];
    }
    if (!empty($row['activation_code_expires_at'])) {
        return ['label' => 'En attente', 'class' => 'warning', 'detail' => 'Code généré, activation non finalisée'];
    }
    return ['label' => 'À préparer', 'class' => 'light', 'detail' => 'Aucun code émis'];
};

$formatDate = static function (?string $value): string {
    if (empty($value)) {
        return '—';
    }
    $timestamp = strtotime($value);
    if ($timestamp === false) {
        return '—';
    }
    return date('d/m/Y H:i', $timestamp);
};
?>

<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;">Licences mobiles</h4>
    <p class="text-muted small mb-0 mt-1">Générez les codes d’activation, suivez les premières activations et contrôlez l’accès mobile par utilisateur.</p>
  </div>
</div>

<div class="card border-0 shadow-sm mb-4" style="border-radius:1rem;">
  <div class="card-body p-3 p-lg-4">
    <form method="get" action="<?= htmlspecialchars(route_url('/mobile-licenses')) ?>" class="row g-2 align-items-end">
      <div class="col-12 col-lg-8">
        <label for="mobile-license-search" class="form-label small text-muted text-uppercase mb-1">Recherche</label>
        <input
          type="search"
          id="mobile-license-search"
          name="q"
          value="<?= htmlspecialchars($search) ?>"
          class="form-control"
          placeholder="Nom, email, rôle, code, appareil, événement..."
        >
      </div>
      <div class="col-12 col-lg-4 d-flex gap-2">
        <button type="submit" class="btn btn-primary flex-fill">Rechercher</button>
        <?php if ($search !== ''): ?>
          <a href="<?= htmlspecialchars(route_url('/mobile-licenses')) ?>" class="btn btn-outline-secondary">Réinitialiser</a>
        <?php endif; ?>
      </div>
    </form>
  </div>
</div>

<?php if (!empty($flash['message'])): ?>
  <div class="alert alert-<?= htmlspecialchars($flash['type'] === 'error' ? 'danger' : ($flash['type'] === 'warning' ? 'warning' : 'success')) ?> shadow-sm border-0 mb-4">
    <div class="d-flex flex-column gap-1">
      <strong><?= htmlspecialchars($flash['message']) ?></strong>
      <?php if (!empty($flash['user_name']) && !empty($flash['code'])): ?>
        <span>Utilisateur: <?= htmlspecialchars($flash['user_name']) ?> | Code: <span class="fw-bold" style="letter-spacing:.16em;"><?= htmlspecialchars($flash['code']) ?></span></span>
      <?php endif; ?>
      <?php if (!empty($flash['expires_at'])): ?>
        <span>Expiration du code: <?= htmlspecialchars($formatDate($flash['expires_at'])) ?></span>
      <?php endif; ?>
    </div>
  </div>
<?php endif; ?>

<div class="row g-3 mb-4">
  <div class="col-6 col-xl-3">
    <div class="card border-0 shadow-sm h-100"><div class="card-body"><div class="text-muted small text-uppercase">Comptes</div><div class="fw-bold fs-3"><?= $total ?></div></div></div>
  </div>
  <div class="col-6 col-xl-3">
    <div class="card border-0 shadow-sm h-100"><div class="card-body"><div class="text-muted small text-uppercase">Licences actives</div><div class="fw-bold fs-3 text-primary"><?= $enabledCount ?></div></div></div>
  </div>
  <div class="col-6 col-xl-3">
    <div class="card border-0 shadow-sm h-100"><div class="card-body"><div class="text-muted small text-uppercase">Activations finalisées</div><div class="fw-bold fs-3 text-success"><?= $activatedCount ?></div></div></div>
  </div>
  <div class="col-6 col-xl-3">
    <div class="card border-0 shadow-sm h-100"><div class="card-body"><div class="text-muted small text-uppercase">En attente</div><div class="fw-bold fs-3 text-warning"><?= $pendingCount ?></div></div></div>
  </div>
</div>

<div class="card border-0 shadow-sm mb-4" style="border-radius:1rem; overflow:hidden;">
  <div class="card-header bg-white border-bottom py-3 px-4">
    <strong>Gestion des comptes mobiles</strong>
  </div>
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead style="background:#f8fafc;">
        <tr>
          <th class="px-4 py-3 text-muted text-uppercase" style="font-size:.76rem;">Utilisateur</th>
          <th class="py-3 text-muted text-uppercase" style="font-size:.76rem;">État</th>
          <th class="py-3 text-muted text-uppercase" style="font-size:.76rem;">Code / activation</th>
          <th class="py-3 text-muted text-uppercase" style="font-size:.76rem;">Dernier accès mobile</th>
          <th class="py-3 text-muted text-uppercase text-end pe-4" style="font-size:.76rem;">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($licenses)): ?>
          <tr>
            <td colspan="5" class="px-4 py-4 text-muted">
              <?= $search !== ''
                ? 'Aucun compte mobile ne correspond à cette recherche.'
                : 'Aucun compte mobile disponible pour le moment.' ?>
            </td>
          </tr>
        <?php endif; ?>
        <?php foreach ($licenses as $row): ?>
          <?php $status = $statusFor($row); ?>
          <tr>
            <td class="px-4 py-3">
              <div class="fw-semibold"><?= htmlspecialchars($row['name'] ?? 'Utilisateur') ?></div>
              <div class="text-muted small"><?= htmlspecialchars($row['email'] ?? '') ?></div>
              <div class="text-muted small"><?= htmlspecialchars(ucfirst((string)($row['role_key'] ?? 'utilisateur'))) ?></div>
            </td>
            <td class="py-3">
              <span class="badge text-bg-<?= htmlspecialchars($status['class']) ?> px-3 py-2"><?= htmlspecialchars($status['label']) ?></span>
              <div class="text-muted small mt-1"><?= htmlspecialchars($status['detail']) ?></div>
            </td>
            <td class="py-3">
              <div class="small"><strong>Code:</strong> <?= htmlspecialchars((string)($row['activation_code_hint'] ?? 'Aucun')) ?></div>
              <div class="small text-muted"><strong>Généré:</strong> <?= htmlspecialchars($formatDate($row['code_generated_at'] ?? null)) ?></div>
              <div class="small text-muted"><strong>Expire:</strong> <?= htmlspecialchars($formatDate($row['activation_code_expires_at'] ?? null)) ?></div>
              <div class="small text-muted"><strong>Activé:</strong> <?= htmlspecialchars($formatDate($row['activated_at'] ?? null)) ?></div>
              <div class="small text-muted"><strong>Appareil:</strong> <?= htmlspecialchars(trim((string)($row['activated_platform'] ?? '')) !== '' ? (($row['activated_platform'] ?? '') . ' ' . ($row['activated_model'] ?? '')) : '—') ?></div>
            </td>
            <td class="py-3">
              <div class="small"><strong>Connexion:</strong> <?= htmlspecialchars($formatDate($row['mobile_last_login_at'] ?? null)) ?></div>
              <div class="small text-muted"><strong>Dernier device vu:</strong> <?= htmlspecialchars($formatDate($row['device_last_seen_at'] ?? null)) ?></div>
              <div class="small text-muted"><strong>Nb activations:</strong> <?= (int)($row['activation_count'] ?? 0) ?></div>
            </td>
            <td class="py-3 text-end pe-4">
              <div class="d-inline-flex flex-wrap justify-content-end gap-2">
                <form method="post" action="<?= htmlspecialchars(route_url('/mobile-licenses/generate')) ?>" class="d-inline">
                  <input type="hidden" name="user_id" value="<?= (int)($row['user_id'] ?? 0) ?>">
                  <button type="submit" class="btn btn-sm btn-primary">Générer & envoyer</button>
                </form>
                <form method="post" action="<?= htmlspecialchars(route_url('/mobile-licenses/toggle')) ?>" class="d-inline">
                  <input type="hidden" name="user_id" value="<?= (int)($row['user_id'] ?? 0) ?>">
                  <input type="hidden" name="enabled" value="<?= (int)($row['is_enabled'] ?? 0) === 1 ? 0 : 1 ?>">
                  <button type="submit" class="btn btn-sm btn-outline-<?= (int)($row['is_enabled'] ?? 0) === 1 ? 'danger' : 'success' ?>">
                    <?= (int)($row['is_enabled'] ?? 0) === 1 ? 'Suspendre' : 'Réactiver' ?>
                  </button>
                </form>
              </div>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<div class="card border-0 shadow-sm" style="border-radius:1rem; overflow:hidden;">
  <div class="card-header bg-white border-bottom py-3 px-4">
    <strong>Suivi des événements</strong>
  </div>
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead style="background:#f8fafc;">
        <tr>
          <th class="px-4 py-3 text-muted text-uppercase" style="font-size:.76rem;">Date</th>
          <th class="py-3 text-muted text-uppercase" style="font-size:.76rem;">Utilisateur</th>
          <th class="py-3 text-muted text-uppercase" style="font-size:.76rem;">Événement</th>
          <th class="py-3 text-muted text-uppercase" style="font-size:.76rem;">Contexte</th>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($events)): ?>
          <tr><td colspan="4" class="px-4 py-4 text-muted"><?= $search !== '' ? 'Aucun événement mobile ne correspond à cette recherche.' : 'Aucun événement mobile enregistré pour le moment.' ?></td></tr>
        <?php endif; ?>
        <?php foreach ($events as $event): ?>
          <tr>
            <td class="px-4 py-3 small"><?= htmlspecialchars($formatDate($event['created_at'] ?? null)) ?></td>
            <td class="py-3">
              <div class="fw-semibold small"><?= htmlspecialchars($event['user_name'] ?? 'Utilisateur') ?></div>
              <div class="text-muted small"><?= htmlspecialchars($event['user_email'] ?? ($event['email_snapshot'] ?? '')) ?></div>
            </td>
            <td class="py-3">
              <div class="fw-semibold small"><?= htmlspecialchars($event['event_label'] ?? '') ?></div>
              <div class="text-muted small"><?= htmlspecialchars($event['event_type'] ?? '') ?></div>
            </td>
            <td class="py-3 small text-muted">
              <div>Acteur: <?= htmlspecialchars($event['actor_name'] ?? 'Système') ?></div>
              <div>Appareil: <?= htmlspecialchars(trim((string)($event['platform'] ?? '')) !== '' ? (($event['platform'] ?? '') . ' ' . ($event['model'] ?? '')) : '—') ?></div>
              <div>IP: <?= htmlspecialchars($event['ip_address'] ?? '—') ?></div>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>