<?php
session_start();
include '_serveur.php';
mysqli_set_charset($link, "utf8");

$classeid = intval($_SESSION['classeid'] ?? 0);
$classe1  = $_SESSION['classe1'] ?? '';
$date1    = $_SESSION['date1']   ?? date('Y-m-d');

if (!$classeid) {
    header('Location: _ecrireabsencec1.php');
    exit;
}

// Fetch cycleid for this class
$cycleRes = mysqli_query($link, 'SELECT cycleID FROM classes WHERE id="' . $classeid . '" LIMIT 1');
$cycleRow = mysqli_fetch_assoc($cycleRes);
$cycleid  = intval($cycleRow['cycleID'] ?? 0);

// ════════════════════════════════════════════════════════════════════
// HANDLE SUBMIT — process absences + batch push notifications
// ════════════════════════════════════════════════════════════════════
$results   = [];  // feedback messages for UI
$doneCount = 0;

if (isset($_POST['envoyer'])) {
    include 'sjmSendPush.php';

    $selected = $_POST['plat'] ?? [];

    // Parse selected students
    $students = [];
    foreach ($selected as $val) {
        $parts = explode(';', $val, 6);
        if (count($parts) < 6) continue;
        $students[] = [
            'numero'    => $parts[0],
            'studentid' => intval($parts[1]),
            'userID'    => intval($parts[2]),
            'prenom'    => $parts[3],
            'family'    => $parts[4],
            'userType'  => $parts[5],
        ];
    }

    // Determine direction userIDs based on cycleid
    if ($cycleid == 5 ) {
        $directionIDs = [100103, 100102,253062,100104];
    } elseif (in_array($cycleid, [1, 2])) {
        $directionIDs = [240200, 253062, 10023,100102,100104];
    } else {
        $directionIDs = [100105, 253062, 10010,100104];
    }

    // Collect device tokens for batch — keyed by message
    $pushJobs = []; // array of ['deviceType'=>..., 'pushid'=>..., 'message'=>...]

    foreach ($students as $st) {
        if (empty($st['prenom'])) continue;

        $sid     = $st['studentid'];
        $uid     = $st['userID'];
        $message = $st['prenom'] . ' ' . $st['family'] . ' en classe ' . $classe1 . ' EST ABSENT(E)';

        // Check if already recorded for this date
        $chk = mysqli_query($link, 'SELECT id FROM absences WHERE studentID="' . $sid . '" AND date="' . mysqli_real_escape_string($link, $date1) . '"');
        if (mysqli_num_rows($chk) > 0) {
            $results[] = ['type' => 'warn', 'msg' => $st['prenom'] . ' ' . $st['family'] . ' est déjà enregistré(e).'];
            continue;
        }

        // Insert absence
        mysqli_query($link, 'INSERT INTO absences VALUES(DEFAULT,"' . $sid . '","' . $classeid . '","' . mysqli_real_escape_string($link, $date1) . '","' . mysqli_real_escape_string($link, $message) . '")');

        // Insert notification for the student's parent
        mysqli_query($link, 'INSERT INTO notifications VALUES(DEFAULT,"Absences","' . mysqli_real_escape_string($link, $message) . '","' . mysqli_real_escape_string($link, $date1) . '",NULL,"' . $uid . '")');

        $results[] = ['type' => 'ok', 'msg' => $st['prenom'] . ' ' . $st['family'] . ' marqué(e) absent(e).'];
        $doneCount++;

        // Collect devices for this student + direction (based on cycle)
        $userList = array_merge([$uid], $directionIDs);
        $inList   = implode(',', array_map('intval', $userList));
        $devRes   = mysqli_query($link, 'SELECT id, deviceType FROM devices WHERE userID IN (' . $inList . ')');
        while ($dev = mysqli_fetch_assoc($devRes)) {
            $pushJobs[] = [
                'deviceType' => $dev['deviceType'],
                'pushid'     => (string)$dev['id'],
                'message'    => $message,
            ];
        }
    }

    // ── BATCH PUSH — group by deviceType to minimize HTTP calls ────
    // Group: [deviceType][message] => [pushids]
    $batches = [];
    foreach ($pushJobs as $job) {
        $dt  = ($job['deviceType'] === 'ios') ? 'iOS' : $job['deviceType'];
        $msg = $job['message'];
        $batches[$dt][$msg][] = $job['pushid'];
    }

    foreach ($batches as $deviceType => $messages) {
        foreach ($messages as $msg => $pushids) {
            // Send all devices for this message in one call
            $payload = json_encode([
                'type'    => $deviceType,
                'data'    => ['title' => 'Absences', 'body' => $msg],
                'devices' => $pushids,   // array of all push IDs at once
            ]);
            sendPush($payload);
        }
    }
}

// ════════════════════════════════════════════════════════════════════
// Load students for display
// ════════════════════════════════════════════════════════════════════
$sql = 'SELECT students.id, students.userID, students.firstName, students.lastName, users.firstName AS middleName
        FROM students
        JOIN users ON users.id = students.userID
        WHERE students.classID="' . $classeid . '"
        ORDER BY students.firstName, students.lastName, users.firstName ASC';
$req      = mysqli_query($link, $sql);
$students = [];
while ($d = mysqli_fetch_assoc($req)) { $students[] = $d; }
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Absences — <?= htmlspecialchars($classe1) ?></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
*{margin:0;padding:0;box-sizing:border-box;}
body{font-family:"Segoe UI",Arial,sans-serif;background:#f0f4ff;min-height:100vh;color:#1f2937;}

.topbar{background:#1e3a8a;color:white;padding:14px 24px;display:flex;align-items:center;justify-content:space-between;box-shadow:0 2px 8px rgba(0,0,0,.3);}
.topbar h1{font-size:18px;font-weight:700;display:flex;align-items:center;gap:10px;}
.btn-back{background:rgba(255,255,255,.15);color:white;border:1px solid rgba(255,255,255,.35);padding:7px 16px;border-radius:8px;font-size:12px;font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:6px;text-decoration:none;}
.btn-back:hover{background:rgba(255,255,255,.25);}

.container{max-width:860px;margin:28px auto;padding:0 16px 60px;}

.info-badge{display:inline-flex;align-items:center;gap:10px;background:linear-gradient(90deg,#eff6ff,#ecfdf5);border:1px solid #bfdbfe;border-radius:999px;padding:8px 20px;font-weight:700;font-size:.95rem;color:#1e3a8a;margin-bottom:22px;flex-wrap:wrap;}
.info-badge span{color:#374151;font-weight:500;}

.card{background:white;border-radius:16px;box-shadow:0 4px 24px rgba(0,0,0,.09);padding:28px 32px;margin-bottom:22px;border:1px solid #e5e7eb;}
.card-title{font-size:.7rem;font-weight:700;letter-spacing:1.2px;text-transform:uppercase;color:#1e3a8a;margin-bottom:20px;display:flex;align-items:center;gap:8px;}
.card-title::after{content:'';flex:1;height:1px;background:#e5e7eb;}

/* Student grid */
.student-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:10px;}
.student-item{display:flex;align-items:center;gap:10px;padding:10px 14px;border:1.5px solid #e5e7eb;border-radius:10px;cursor:pointer;transition:.15s;user-select:none;}
.student-item:hover{border-color:#1e3a8a;background:#eff6ff;}
.student-item.checked{border-color:#dc2626;background:#fef2f2;}
.student-item input[type="checkbox"]{display:none;}
.student-num{font-size:.75rem;color:#9ca3af;font-weight:700;min-width:22px;}
.student-name{font-size:.9rem;font-weight:600;color:#1f2937;}
.student-item.checked .student-name{color:#dc2626;}
.check-icon{margin-left:auto;color:#dc2626;display:none;font-size:.9rem;}
.student-item.checked .check-icon{display:block;}

/* Select all bar */
.select-bar{display:flex;align-items:center;gap:12px;margin-bottom:16px;flex-wrap:wrap;}
.btn-sel{padding:7px 16px;border-radius:8px;font-size:.82rem;font-weight:700;cursor:pointer;border:1.5px solid;display:inline-flex;align-items:center;gap:6px;transition:.15s;}
.btn-all{background:#fef2f2;color:#dc2626;border-color:#fca5a5;}.btn-all:hover{background:#fee2e2;}
.btn-none{background:#f3f4f6;color:#374151;border-color:#d1d5db;}.btn-none:hover{background:#e5e7eb;}
.sel-count{font-size:.85rem;color:#6b7280;margin-left:auto;}
.sel-count b{color:#dc2626;}

/* Action row */
.action-row{display:flex;gap:12px;padding-top:18px;border-top:1px solid #e5e7eb;margin-top:6px;flex-wrap:wrap;}
.btn{padding:11px 26px;border:none;border-radius:10px;font-size:.9rem;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:8px;transition:.15s;}
.btn-danger{background:#dc2626;color:white;}.btn-danger:hover{background:#b91c1c;transform:translateY(-1px);box-shadow:0 4px 14px rgba(220,38,38,.35);}
.btn-danger:disabled{opacity:.55;cursor:not-allowed;transform:none;box-shadow:none;}
.btn-ghost{background:#f3f4f6;color:#374151;border:1.5px solid #d1d5db;}.btn-ghost:hover{border-color:#1e3a8a;color:#1e3a8a;}

/* Results */
.result-item{display:flex;align-items:center;gap:10px;padding:9px 14px;border-radius:8px;margin-bottom:6px;font-size:.88rem;font-weight:500;}
.result-ok{background:#f0fdf4;border:1px solid #86efac;color:#166534;}
.result-warn{background:#fefce8;border:1px solid #fde68a;color:#92400e;}

/* Loading overlay */
#loadingOverlay{display:none;position:fixed;inset:0;background:rgba(30,58,138,.55);z-index:9999;align-items:center;justify-content:center;flex-direction:column;gap:16px;}
#loadingOverlay.show{display:flex;}
.spinner{width:52px;height:52px;border:5px solid rgba(255,255,255,.3);border-top-color:white;border-radius:50%;animation:spin .8s linear infinite;}
@keyframes spin{to{transform:rotate(360deg);}}
#loadingOverlay p{color:white;font-size:1rem;font-weight:600;}

@media(max-width:500px){.student-grid{grid-template-columns:1fr 1fr;}}
</style>
</head>
<body>

<!-- Loading overlay shown while sending -->
<div id="loadingOverlay">
  <div class="spinner"></div>
  <p>Envoi des notifications en cours…</p>
</div>

<div class="topbar">
  <h1><i class="fa fa-calendar-xmark"></i> Saisie des Absences</h1>
  <a href="javascript:history.go(-1)" class="btn-back"><i class="fa fa-arrow-left"></i> Retour</a>
</div>

<div class="container">

  <!-- Info badge -->
  <div class="info-badge">
    <i class="fa fa-users" style="color:#1e3a8a"></i>
    <?= htmlspecialchars($classe1) ?>
    &nbsp;|&nbsp;
    <i class="fa fa-calendar-day" style="color:#059669"></i>
    <span><?= htmlspecialchars(date('d/m/Y', strtotime($date1))) ?></span>
  </div>

  <?php if (!empty($results)): ?>
  <!-- Results card -->
  <div class="card">
    <div class="card-title"><i class="fa fa-circle-check"></i> Résultats</div>
    <?php foreach ($results as $r): ?>
      <div class="result-item result-<?= $r['type'] ?>">
        <i class="fa <?= $r['type']==='ok' ? 'fa-check-circle' : 'fa-triangle-exclamation' ?>"></i>
        <?= htmlspecialchars($r['msg']) ?>
      </div>
    <?php endforeach; ?>
    <?php if ($doneCount > 0): ?>
      <div style="margin-top:12px;padding:10px 14px;background:#eff6ff;border-radius:8px;font-weight:700;color:#1e3a8a;font-size:.9rem;">
        <i class="fa fa-circle-check"></i> <?= $doneCount ?> absence(s) enregistrée(s) et notifications envoyées.
      </div>
    <?php endif; ?>
  </div>
  <?php endif; ?>

  <!-- Student selection form -->
  <form method="post" action="continuerabsencec1.php" id="absForm">
  <div class="card">
    <div class="card-title"><i class="fa fa-user-xmark"></i> Élèves absents — cochez les absents</div>

    <div class="select-bar">
      <button type="button" class="btn-sel btn-all" onclick="selectAll()"><i class="fa fa-check-double"></i> Tous</button>
      <button type="button" class="btn-sel btn-none" onclick="selectNone()"><i class="fa fa-xmark"></i> Aucun</button>
      <span class="sel-count">Sélectionnés : <b id="selCount">0</b></span>
    </div>

    <div class="student-grid" id="studentGrid">
      <?php foreach ($students as $i => $s): ?>
        <?php
          $num   = $i + 1;
          $name  = htmlspecialchars(trim($s['firstName'] . ' ' . $s['middleName'] . ' ' . $s['lastName']));
          $value = $num . ';' . $s['id'] . ';' . $s['userID'] . ';' . $s['firstName'] . ';' . $s['lastName'] . ';student';
        ?>
        <label class="student-item" id="lbl_<?= $i ?>">
          <input type="checkbox" name="plat[]" value="<?= htmlspecialchars($value) ?>" onchange="toggleItem(this, <?= $i ?>)">
          <span class="student-num"><?= $num ?></span>
          <span class="student-name"><?= $name ?></span>
          <i class="fa fa-circle-xmark check-icon"></i>
        </label>
      <?php endforeach; ?>
    </div>

    <div class="action-row">
      <button type="submit" name="envoyer" class="btn btn-danger" id="submitBtn" disabled onclick="showLoading()">
        <i class="fa fa-paper-plane"></i> Envoyer les Absences
      </button>
      <button type="reset" class="btn btn-ghost" onclick="selectNone()"><i class="fa fa-rotate-left"></i> Effacer</button>
    </div>
  </div>
  </form>

</div>

<script>
function toggleItem(cb, idx) {
  const lbl = document.getElementById('lbl_' + idx);
  if (cb.checked) lbl.classList.add('checked');
  else            lbl.classList.remove('checked');
  updateCount();
}

function updateCount() {
  const n = document.querySelectorAll('#studentGrid input:checked').length;
  document.getElementById('selCount').textContent = n;
  document.getElementById('submitBtn').disabled = (n === 0);
}

function selectAll() {
  document.querySelectorAll('#studentGrid input[type="checkbox"]').forEach((cb, idx) => {
    cb.checked = true;
    document.getElementById('lbl_' + idx).classList.add('checked');
  });
  updateCount();
}

function selectNone() {
  document.querySelectorAll('#studentGrid input[type="checkbox"]').forEach((cb, idx) => {
    cb.checked = false;
    document.getElementById('lbl_' + idx).classList.remove('checked');
  });
  updateCount();
}

function showLoading() {
  const n = document.querySelectorAll('#studentGrid input:checked').length;
  if (n > 0) document.getElementById('loadingOverlay').classList.add('show');
}
</script>
</body>
</html>
