<?php session_start(); ?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Réactivation des comptes</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link href="https://fonts.googleapis.com/css2?family=Sora:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  <style>
    :root {
      --bg:        #0d1117;
      --surface:   #161b22;
      --card:      #1c2330;
      --border:    #30363d;
      --accent:    #2ea8ff;
      --accent2:   #1a7dd4;
      --success:   #3fb950;
      --danger:    #f85149;
      --text:      #e6edf3;
      --muted:     #8b949e;
      --radius:    14px;
      --transition: 0.2s ease;
    }

    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

    body {
      font-family: 'Sora', sans-serif;
      background: var(--bg);
      color: var(--text);
      min-height: 100vh;
      padding: 0 0 40px;
    }

    /* ── Header ── */
    .page-header {
      background: linear-gradient(135deg, #0d1f3c 0%, #0d1117 100%);
      border-bottom: 1px solid var(--border);
      padding: 20px 20px 18px;
      display: flex;
      align-items: center;
      gap: 14px;
      position: sticky;
      top: 0;
      z-index: 10;
      backdrop-filter: blur(8px);
    }

    .header-icon {
      width: 42px;
      height: 42px;
      background: var(--accent);
      border-radius: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
    }

    .header-icon svg { width: 22px; height: 22px; fill: #fff; }

    .header-text h1 {
      font-size: 17px;
      font-weight: 700;
      letter-spacing: -0.3px;
    }

    .header-text p {
      font-size: 12px;
      color: var(--muted);
      margin-top: 2px;
    }

    /* ── Wrapper ── */
    .wrapper {
      max-width: 680px;
      margin: 0 auto;
      padding: 24px 16px 0;
    }

    /* ── Section label ── */
    .section-label {
      font-size: 11px;
      font-weight: 600;
      letter-spacing: 1px;
      text-transform: uppercase;
      color: var(--muted);
      margin-bottom: 12px;
    }

    /* ── User cards grid ── */
    .users-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 10px;
      margin-bottom: 28px;
    }

    @media (max-width: 380px) {
      .users-grid { grid-template-columns: 1fr; }
    }

    .user-card {
      background: var(--card);
      border: 1px solid var(--border);
      border-radius: var(--radius);
      padding: 14px 14px 14px 12px;
      display: flex;
      align-items: center;
      gap: 12px;
      cursor: pointer;
      transition: border-color var(--transition), background var(--transition), transform var(--transition);
      -webkit-tap-highlight-color: transparent;
      position: relative;
    }

    .user-card:active { transform: scale(0.98); }

    /* Hide native checkbox */
    .user-card input[type="checkbox"] {
      position: absolute;
      opacity: 0;
      width: 0;
      height: 0;
    }

    /* Custom checkbox */
    .check-box {
      width: 22px;
      height: 22px;
      border-radius: 6px;
      border: 2px solid var(--border);
      background: var(--surface);
      flex-shrink: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all var(--transition);
    }

    .check-box svg {
      width: 12px;
      height: 12px;
      stroke: #fff;
      stroke-width: 2.5;
      opacity: 0;
      transform: scale(0.5);
      transition: all var(--transition);
    }

    .user-card.selected {
      border-color: var(--accent);
      background: rgba(46,168,255,0.08);
    }

    .user-card.selected .check-box {
      background: var(--accent);
      border-color: var(--accent);
    }

    .user-card.selected .check-box svg {
      opacity: 1;
      transform: scale(1);
    }

    /* Avatar */
    .avatar {
      width: 38px;
      height: 38px;
      border-radius: 50%;
      background: linear-gradient(135deg, #1a4a6e, #0d2b45);
      border: 1px solid var(--border);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      font-weight: 600;
      color: var(--accent);
      flex-shrink: 0;
      text-transform: uppercase;
    }

    .user-info { flex: 1; min-width: 0; }

    .user-index {
      font-size: 10px;
      color: var(--muted);
      font-weight: 500;
    }

    .user-name {
      font-size: 13px;
      font-weight: 600;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin-top: 1px;
    }

    /* ── Empty state ── */
    .empty-state {
      text-align: center;
      padding: 48px 20px;
      color: var(--muted);
    }

    .empty-state svg {
      width: 48px;
      height: 48px;
      stroke: var(--muted);
      margin-bottom: 14px;
      opacity: 0.5;
    }

    .empty-state p { font-size: 14px; }

    /* ── Action bar ── */
    .action-bar {
      display: flex;
      gap: 10px;
      margin-top: 8px;
      margin-bottom: 32px;
      padding: 16px;
      background: var(--surface);
      border: 1px solid var(--border);
      border-radius: var(--radius);
    }

    .btn {
      flex: 1;
      padding: 14px;
      border: none;
      border-radius: 10px;
      font-family: 'Sora', sans-serif;
      font-size: 14px;
      font-weight: 600;
      cursor: pointer;
      transition: opacity var(--transition), transform var(--transition);
      -webkit-tap-highlight-color: transparent;
    }

    .btn:active { transform: scale(0.97); }

    .btn-reset {
      background: transparent;
      border: 1px solid var(--border);
      color: var(--muted);
    }

    .btn-submit {
      background: var(--accent);
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
    }

    .btn-submit:disabled { opacity: 0.4; cursor: not-allowed; }

    .btn-submit svg {
      width: 16px;
      height: 16px;
      stroke: #fff;
      stroke-width: 2;
      fill: none;
    }

    /* ── Toast / result banner ── */
    .toast {
      margin-bottom: 20px;
      border-radius: var(--radius);
      padding: 14px 16px;
      font-size: 13px;
      font-weight: 500;
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .toast.success {
      background: rgba(63,185,80,0.12);
      border: 1px solid rgba(63,185,80,0.4);
      color: var(--success);
    }

    .toast.error {
      background: rgba(248,81,73,0.10);
      border: 1px solid rgba(248,81,73,0.4);
      color: var(--danger);
    }

    .toast svg {
      width: 18px;
      height: 18px;
      flex-shrink: 0;
      fill: currentColor;
    }

    /* ── Counter badge ── */
    #counter-badge {
      display: none;
      background: var(--accent);
      color: #fff;
      font-size: 11px;
      font-weight: 700;
      border-radius: 20px;
      padding: 2px 7px;
      margin-left: 6px;
      vertical-align: middle;
    }
  </style>
</head>
<body>

<?php
include("_serveur.php");
include 'header.php';
?>

<!-- Page header -->
<div class="page-header">
  <div class="header-icon">
    <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
      <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 14H9V8h2v8zm4 0h-2V8h2v8z"/>
    </svg>
  </div>
  <div class="header-text">
    <h1>Réactivation <span id="counter-badge">0</span></h1>
    <p>Sélectionnez les comptes à réactiver</p>
  </div>
</div>

<div class="wrapper">

<?php
/* ── Process form submission ── */
if (isset($_POST['envoyer'])) {
    $activated = 0;
    $errors    = [];

    if (!empty($_POST['plat'])) {
        $plat  = implode(';', $_POST['plat']);
        $parts = explode(';', $plat);

        $j = 0; $k = 1; $l = 2; $m = 3;
        $records = [];
        while (isset($parts[$j])) {
            $records[] = [
                'numero'    => $parts[$j] ?? '',
                'id'        => $parts[$k] ?? '',
                'firstname' => $parts[$l] ?? '',
                'lastname'  => $parts[$m] ?? '',
            ];
            $j += 4; $k += 4; $l += 4; $m += 4;
        }

        foreach ($records as $rec) {
            if (empty($rec['id'])) continue;
            $safe_id = mysqli_real_escape_string($link, $rec['id']);
            $sql1 = "UPDATE users SET active=1 WHERE id='$safe_id'";
            if (!mysqli_query($link, $sql1)) {
                $errors[] = "Erreur DB pour ID {$rec['id']}: " . mysqli_error($link);
            } else {
                $activated++;
            }
        }

        /* Push notifications */
        include("sjmSendPush.php");
        foreach ($records as $rec) {
            if (empty($rec['firstname'])) continue;
            $safe_id  = mysqli_real_escape_string($link, $rec['id']);
            $fullname = htmlspecialchars($rec['firstname'] . ' ' . $rec['lastname']);
            $message  = "$fullname EST ACTIVÉ(E) DE NOUVEAU";

            $sqlD = "SELECT * FROM devices WHERE userID='$safe_id' OR userID=230100 OR userID=10055 OR userID=232024 OR userID=10001";
            $reqD = mysqli_query($link, $sqlD);
            while ($ddata = mysqli_fetch_array($reqD)) {
                $deviceType = $ddata[2];
                $pushid     = (string)$ddata[0];
                if (strtolower($deviceType) === 'ios') $deviceType = 'iOS';
                $payload = ['type' => $deviceType, 'data' => ['title' => 'Réactivé(e)', 'body' => $message], 'devices' => [$pushid]];
                sendPush(json_encode($payload));
            }
        }
    }

    /* Result feedback */
    if (!empty($errors)) {
        foreach ($errors as $err) {
            echo "<div class='toast error'>
                    <svg viewBox='0 0 24 24'><path d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10S22 17.52 22 12 17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z'/></svg>
                    " . htmlspecialchars($err) . "
                  </div>";
        }
    }
    if ($activated > 0) {
        echo "<div class='toast success'>
                <svg viewBox='0 0 24 24'><path d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10S22 17.52 22 12 17.52 2 12 2zm-2 14l-4-4 1.41-1.41L10 13.17l6.59-6.59L18 8l-8 8z'/></svg>
                $activated compte(s) réactivé(s) avec succès.
              </div>";
    }
}

/* ── Fetch inactive users ── */
$sql = 'SELECT * FROM users WHERE active="0"';
$req = mysqli_query($link, $sql);
if (!$req) {
    echo "<div class='toast error'>Erreur: " . mysqli_error($link) . "</div>";
}
$rows = [];
while ($data = mysqli_fetch_array($req)) {
    $rows[] = $data;
}
?>

  <!-- User list -->
  <p class="section-label">Comptes désactivés — <?= count($rows) ?> utilisateur(s)</p>

  <?php if (empty($rows)): ?>
    <div class="empty-state">
      <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
        <circle cx="12" cy="8" r="4" stroke-width="1.5"/>
        <path d="M4 20c0-4 3.58-7 8-7s8 3 8 7" stroke-width="1.5" stroke-linecap="round"/>
      </svg>
      <p>Aucun compte désactivé trouvé.</p>
    </div>
  <?php else: ?>
  <form method="post" action="reactivatef.php" id="reactForm">
    <div class="users-grid">
      <?php foreach ($rows as $i => $data): 
        $idx   = $i + 1;
        $fname = htmlspecialchars($data[2]);
        $lname = htmlspecialchars($data[3]);
        $initials = mb_substr($fname, 0, 1) . mb_substr($lname, 0, 1);
        $val   = $idx . ';' . $data[0] . ';' . $data[2] . ';' . $data[3];
      ?>
      <label class="user-card" id="card-<?= $idx ?>">
        <input type="checkbox" name="plat[]" value="<?= htmlspecialchars($val) ?>" onchange="updateCard(this, <?= $idx ?>)">
        <div class="check-box">
          <svg viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
            <polyline points="2,7 5.5,10.5 12,3"/>
          </svg>
        </div>
        <div class="avatar"><?= $initials ?></div>
        <div class="user-info">
          <div class="user-index">#<?= $idx ?></div>
          <div class="user-name"><?= $fname ?> <?= $lname ?></div>
        </div>
      </label>
      <?php endforeach; ?>
    </div>

    <!-- Fixed action bar -->
    <div class="action-bar">
      <button type="reset" class="btn btn-reset" onclick="resetAll()">Effacer</button>
      <button type="submit" name="envoyer" class="btn btn-submit" id="submitBtn" disabled>
        <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
          <polyline points="20 6 9 17 4 12"/>
        </svg>
        Réactiver
      </button>
    </div>
  </form>
  <?php endif; ?>

</div><!-- .wrapper -->

<script>
  let selectedCount = 0;
  const badge  = document.getElementById('counter-badge');
  const submit = document.getElementById('submitBtn');

  function updateCard(checkbox, idx) {
    const card = document.getElementById('card-' + idx);
    if (checkbox.checked) {
      card.classList.add('selected');
      selectedCount++;
    } else {
      card.classList.remove('selected');
      selectedCount--;
    }
    badge.textContent = selectedCount;
    badge.style.display = selectedCount > 0 ? 'inline-block' : 'none';
    submit.disabled = selectedCount === 0;
  }

  function resetAll() {
    document.querySelectorAll('.user-card').forEach(c => c.classList.remove('selected'));
    selectedCount = 0;
    badge.style.display = 'none';
    if (submit) submit.disabled = true;
  }
</script>
</body>
</html>
