<?php 
session_start();
if (!isset($_SESSION['user'])) {
    header("Location: login.php");
    exit();
}

require_once "includes/dbconn.php";

// NE PAS inclure le header si AJAX
if (!isset($_GET['ajax'])) {
   
}

if (isset($_GET['ajax'])) {
    if ($_GET['ajax'] == 'classes' && isset($_GET['niveau_id'])) {
        $niveau_id = intval($_GET['niveau_id']);
        $classes = mysqli_query($conn, "SELECT id, nom FROM classes WHERE niveau_id=$niveau_id");
        while ($c = mysqli_fetch_assoc($classes)) {
            echo "<option value='{$c['id']}'>{$c['nom']}</option>";
        }
        exit();
    }
    if ($_GET['ajax'] == 'generate' && isset($_GET['niveau_id']) && isset($_GET['classe_id'])) {
        $niveau_id = intval($_GET['niveau_id']);
        $classe_id = intval($_GET['classe_id']);
        $niveau = mysqli_fetch_assoc(mysqli_query($conn, "SELECT nom_niveau FROM niveaux WHERE id = $niveau_id"));
        $classe = mysqli_fetch_assoc(mysqli_query($conn, "SELECT nom FROM classes WHERE id = $classe_id"));
        $etudiants = mysqli_query($conn, "SELECT matricule, noms, prenom FROM etudiants WHERE classe_id = $classe_id ORDER BY noms, prenom");

        ?>
        <div style="text-align: center; font-weight: bold; font-size: 22px; margin-bottom: 20px;">
            Feuille de présence - <?= date("d/m/Y") ?>
        </div>
        <div class="mb-3" style="font-size: 16px;">
            <strong>Niveau :</strong> <?= htmlspecialchars($niveau['nom_niveau']) ?> &nbsp;&nbsp;&nbsp;
            <strong>Classe :</strong> <?= htmlspecialchars($classe['nom']) ?>
        </div>
        <table class="table table-bordered table-striped">
            <thead class="table-primary text-center align-middle">
                <tr>
                    <th rowspan="2">N°</th>
                    <th rowspan="2">Matricule</th>
                    <th rowspan="2">Nom</th>
                    <th rowspan="2">Prénom</th>
                    <th colspan="2">Matin</th>
                    <th colspan="2">Soir</th>
                </tr>
                <tr>
                    <th>08h - 10h</th>
                    <th>10h - 12h</th>
                    <th>15h - 17h</th>
                    <th>17h - 19h</th>
                </tr>
            </thead>
            <tbody>
            <?php $i=1; while ($e=mysqli_fetch_assoc($etudiants)): ?>
                <tr>
                    <td><?= $i++ ?></td>
                    <td><?= htmlspecialchars($e['matricule']) ?></td>
                    <td><?= htmlspecialchars($e['noms']) ?></td>
                    <td><?= htmlspecialchars($e['prenom']) ?></td>
                    <td></td><td></td><td></td><td></td>
                </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
        <?php
        exit();
    }
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8" />
<title>Feuille de présence</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<style>
  @media print {
    .no-print { display: none !important; }
    @page { size: A4 landscape; margin: 15mm; }
    * {
      -webkit-print-color-adjust: exact !important;
      print-color-adjust: exact !important;
    }
    .modal { position: static !important; display: block !important; overflow: visible !important; }
    .modal-dialog { max-width: 100% !important; width: 100% !important; margin: 0 !important; }
    .modal-content { border: none !important; box-shadow: none !important; }
    .modal-backdrop { display: none !important; }
  }
  
  .bg-teal {
    background-color: #008080 !important;
  }
  
  .btn-teal {
    background-color: #008080;
    color: white;
    border-color: #008080;
  }
  
  .btn-teal:hover {
    background-color: #006666;
    border-color: #006666;
  }
  
  .border-teal {
    border-color: #008080 !important;
  }
  
  .table-primary {
    background-color: #e6f2f2;
  }
  
  .table-primary th {
    background-color: #008080;
    color: white;
  }
</style>
</head>
<body class="p-4">

<div class="container-fluid">
  <div class="card border-teal mb-4 no-print">
    <div class="card-header bg-teal text-white fw-bold">Générer une feuille de présence</div>
    <div class="card-body">
      <a href="index.php" class="btn btn-secondary mb-3">← Retour</a>
      <form id="form-presence">
        <div class="row mb-3">
          <div class="col-md-6">
            <label class="form-label fw-bold">Niveau</label>
            <select id="niveau" name="niveau_id" class="form-select" required>
              <option value="">-- Choisir --</option>
              <?php
                $res = mysqli_query($conn, "SELECT id, nom_niveau FROM niveaux ORDER BY nom_niveau");
                while ($row = mysqli_fetch_assoc($res)) {
                    echo "<option value='{$row['id']}'>{$row['nom_niveau']}</option>";
                }
              ?>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label fw-bold">Classe</label>
            <select id="classe" name="classe_id" class="form-select" required disabled>
              <option value="">-- Choisir niveau d'abord --</option>
            </select>
          </div>
        </div>
        <button type="submit" class="btn btn-teal">📝 Générer la feuille</button>
      </form>
    </div>
  </div>
</div>

<!-- Modal -->
<div class="modal fade" id="modalPresence" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-body" id="contenuPresence"></div>
      <div class="modal-footer no-print">
        <button onclick="window.print()" class="btn btn-teal">🖨️ Imprimer</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fermer</button>
      </div>
    </div>
  </div>
</div>

<script>
$(function() {
  $('#niveau').change(function() {
    let niveau_id = $(this).val();
    if (niveau_id !== "") {
      $.get("feuille_presence.php?ajax=classes&niveau_id=" + niveau_id, function(data) {
        $('#classe').prop("disabled", false).html(data);
      });
    } else {
      $('#classe').prop("disabled", true).html('<option value="">-- Choisir niveau d\'abord --</option>');
    }
  });

  $('#form-presence').submit(function(e) {
    e.preventDefault();
    $.get("feuille_presence.php?ajax=generate", $(this).serialize(), function(html) {
      $('#contenuPresence').html(html);
      new bootstrap.Modal(document.getElementById('modalPresence')).show();
    });
  });
});
</script>

</body>
</html>