<?php
session_start();
require_once "includes/dbconn.php";

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

$classe_id = $_GET['classe_id'] ?? null;

// Info école
$ecole_nom    = "Nom de l'École";
$ecole_adresse= "Adresse de l'école, Ville";
$ecole_tel    = "01 23 45 67 89";
$ecole_email  = "contact@ecole.fr";

// Récupération des classes
$classes = [];
$res = $conn->query("SELECT id, nom, nom FROM classes ORDER BY nom");
if ($res) {
    while ($row = $res->fetch_assoc()) {
        $classes[] = $row;
    }
} else {
    die("Erreur SQL classes : " . $conn->error);
}

// Fonction pour récupérer modules + notes d’un étudiant
function getModulesAndNotes($conn, $etudiant_id, $classe_id) {
    $modules = [];
    $stmt = $conn->prepare("
        SELECT m.id, m.nom AS module, m.coefficient,
               MAX(CASE WHEN n.type_note='Devoir 1' THEN n.note END) AS d1,
               MAX(CASE WHEN n.type_note='Devoir 2' THEN n.note END) AS d2,
               MAX(CASE WHEN n.type_note='Examen'    THEN n.note END) AS ex
        FROM modules m
        LEFT JOIN notes n ON m.id = n.module_id AND n.etudiant_id = ?
        WHERE m.classe_id = ?
        GROUP BY m.id, m.nom, m.coefficient
        ORDER BY m.nom
    ");
    $stmt->bind_param("ii", $etudiant_id, $classe_id);
    $stmt->execute();
    $res = $stmt->get_result();

    $total_coef = $total_pond = 0;
    while ($row = $res->fetch_assoc()) {
        $notes = array_filter([$row['d1'], $row['d2'], $row['ex']], 'is_numeric');
        $moy = $notes ? array_sum($notes) / count($notes) : 0;
        $pond = round($moy * $row['coefficient'], 2);
        $row['note_ponderee'] = $pond;
        $modules[] = $row;
        $total_coef += $row['coefficient'];
        $total_pond += $pond;
    }
    $moyenne_generale = $total_coef ? round($total_pond / $total_coef, 2) : null;
    $stmt->close();
    return [$modules, $moyenne_generale];
}

// Fonction pour calculer le rang global des étudiants
function calculerRangsClasse($conn, $classe_id) {
    // Récupérer tous les étudiants de la classe
    $stmt = $conn->prepare("SELECT id FROM etudiants WHERE classe_id = ?");
    $stmt->bind_param("i", $classe_id);
    $stmt->execute();
    $res = $stmt->get_result();

    $etudiants = [];
    while ($row = $res->fetch_assoc()) {
        $etudiants[] = $row['id'];
    }
    $stmt->close();

    $moyennes = [];

    foreach ($etudiants as $etudiant_id) {
        $stmt = $conn->prepare("
            SELECT m.coefficient,
                   MAX(CASE WHEN n.type_note = 'Devoir 1' THEN n.note END) AS d1,
                   MAX(CASE WHEN n.type_note = 'Devoir 2' THEN n.note END) AS d2,
                   MAX(CASE WHEN n.type_note = 'Examen' THEN n.note END) AS ex
            FROM modules m
            LEFT JOIN notes n ON m.id = n.module_id AND n.etudiant_id = ?
            WHERE m.classe_id = ?
            GROUP BY m.id, m.coefficient
        ");
        $stmt->bind_param("ii", $etudiant_id, $classe_id);
        $stmt->execute();
        $res_mod = $stmt->get_result();

        $total_coef = 0;
        $total_pond = 0;

        while ($row = $res_mod->fetch_assoc()) {
            $notes = array_filter([$row['d1'], $row['d2'], $row['ex']], 'is_numeric');
            $moy = $notes ? array_sum($notes) / count($notes) : 0;
            $pond = $moy * $row['coefficient'];
            $total_coef += $row['coefficient'];
            $total_pond += $pond;
        }

        $stmt->close();

        $moyenne = $total_coef ? round($total_pond / $total_coef, 2) : 0;
        $moyennes[$etudiant_id] = $moyenne;
    }

    // Tri par ordre décroissant de moyenne pour calculer le rang
    arsort($moyennes);
    $rangs = [];
    $rang = 0;
    $position = 0;
    $prev_moyenne = null;

    foreach ($moyennes as $id => $moy) {
        $position++;
        if ($moy !== $prev_moyenne) {
            $rang = $position;
        }
        $rangs[$id] = $rang;
        $prev_moyenne = $moy;
    }

    return $rangs;
}


if ($classe_id) {
    // Récupérer étudiants & modules + rangs
    $stmt = $conn->prepare("SELECT id, matricule, noms, prenom, date_de_naissance, lieu_de_naissance FROM etudiants WHERE classe_id = ?");
    $stmt->bind_param("i", $classe_id);
    $stmt->execute();
    $etudiants = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    $stmt = $conn->prepare("SELECT id, nom AS module, coefficient FROM modules WHERE classe_id = ? ORDER BY nom");
    $stmt->bind_param("i", $classe_id);
    $stmt->execute();
    $modules_all = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    $rangs = calculerRangsClasse($conn, $classe_id);
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Bulletins</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
  background:#f8f9fa;
  padding:20px;
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.bulletin-container {
  background:#fff;
  width:794px;
  min-height:1123px;
  margin:auto 0 50px;
  padding:30px 40px 60px;
  border-radius:8px;
  box-shadow:0 0 10px rgba(0,0,0,0.1);
  page-break-after:always;
  position:relative;
  text-align: justify;
  text-justify: inter-word;
}
.header-bulletin {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}
.header-left {
  width: 150px;
}
.header-left img {
  max-width: 150px;
  height: auto;
  display: block;
}
.header-right {
  max-width: 600px;
  text-align: right;
  line-height: 1.3;
  color: #800000;
  font-weight: 600;
}
.header-right h2 {
  text-transform: uppercase;
  font-weight: 700;
  font-size: 2rem;
  margin-bottom: 0.3rem;
}
.infos-etudiant {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  font-size: 0.95rem;
}
.infos-left, .infos-right {
  width: 48%;
}
.infos-left p, .infos-right p {
  margin: 3px 0;
}
table thead {
  background: #800000;
  color: #fff;
}
table {
  font-size: 0.95rem;
  width: 100%;
  border-collapse: collapse;
}
table, th, td {
  border: 1px solid #800000;
}
th, td {
  padding: 8px 10px;
  text-align: center;
}
.footer-summary {
  margin-top: 20px;
  border-top: 2px solid #800000;
  padding-top: 15px;
  text-align: right;
  font-size: 1.1rem;
}
.observation-box {
  margin-top: 15px;
  font-size: 0.95rem;
}
.observation-box textarea {
  width: 100%;
  height: 60px;
  resize: none;
  padding: 6px;
  font-family: inherit;
}
.signature-box {
  text-align: center;
  font-size: 0.95rem;
  margin-top: 50px;
}
.signature-box .line {
  margin-top: 60px;
  border-top: 1px solid #000;
  width: 220px;
  margin-left: auto;
  margin-right: auto;
}
@page {
  size: A4;
  margin: 0;
}

body, html {
  margin: 0;
  padding: 0;
  width: 210mm;
  height: 297mm;
  background: #f8f9fa;
}

.bulletin-container {
  width: 210mm;
  height: 297mm;
  margin: 0;
  padding: 20mm;
  background: #fff;
  box-sizing: border-box;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
  page-break-after: always;
}

@media print {
  .no-print {
    display: none;
  }
  .bulletin-container {
    box-shadow: none;
  }
  * {
    -webkit-print-color-adjust: exact !important;
    print-color-adjust: exact !important;
  }
}



</style>
<?php if ($classe_id): ?><script>window.onload=()=>window.print();</script><?php endif; ?>
</head>
<body>

<div class="container">
<?php if (!$classe_id): ?>
  <h1 class="mb-4 text-center text-uppercase" style="color:#800000;">Sélectionnez la classe</h1>
  <form method="get" class="mb-5 w-50 mx-auto">
    <select name="classe_id" class="form-select" required>
      <option value="" disabled selected>-- Choisir une classe --</option>
      <?php foreach ($classes as $c): ?>
        <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['nom']) ?> (Niv. <?= htmlspecialchars($c['niveau']) ?>)</option>
      <?php endforeach; ?>
    </select>
    <div class="text-center mt-3"><button type="submit" class="btn btn-success">Afficher les bulletins</button></div>
  </form>

<?php elseif (empty($etudiants)): ?>
  <div class="alert alert-warning text-center no-print">Aucun étudiant trouvé pour cette classe.</div>

<?php else: ?>
  <div class="text-center mb-4 no-print">
    <button onclick="window.print()" class="btn btn-primary">Imprimer les bulletins</button>
  </div>
  <?php foreach ($etudiants as $et): ?>
    <?php list($modules, $moyenne_generale) = getModulesAndNotes($conn, $et['id'], $classe_id); ?>
    <?php $rang = $rangs[$et['id']] ?? '-'; ?>

    <div class="bulletin-container">
      <div class="header-bulletin">
        <div class="header-left">
          <img src="assetss/logo.jpeg" alt="Logo">
        </div>
        <div class="header-right">
          <h2>BULLETIN DE NOTE</h2>
          <p><?= htmlspecialchars($ecole_nom) ?></p>
          <p><?= htmlspecialchars($ecole_adresse) ?></p>
          <p>Tél: <?= htmlspecialchars($ecole_tel) ?></p>
          <p>Email: <?= htmlspecialchars($ecole_email) ?></p>
        </div>
      </div>

      <div class="infos-etudiant">
        <div class="infos-left">
          <p><strong>Prénom :</strong> <?= htmlspecialchars($et['prenom']) ?></p>
          <p><strong>Nom :</strong> <?= htmlspecialchars($et['noms']) ?></p>
          <p><strong>Date de naissance :</strong> <?= htmlspecialchars($et['date_de_naissance']) ?></p>
          <p><strong>Lieu :</strong> <?= htmlspecialchars($et['lieu_de_naissance']) ?></p>
        </div>
        <div class="infos-right">
          <p><strong>Matricule :</strong> <?= htmlspecialchars($et['matricule']) ?></p>
          <?php 
            $cl = array_filter($classes, fn($c)=>$c['id']==$classe_id);
            $cl = reset($cl);
          ?>
          <p><strong>Classe :</strong> <?= htmlspecialchars($cl['nom']) ?> (Niv. <?= htmlspecialchars($cl['nom']) ?>)</p>
        </div>
      </div>

      <table>
        <thead>
          <tr>
            <th>#</th><th>Module</th><th>Coefficient</th>
            <th>Devoir 1</th><th>Devoir 2</th><th>Examen</th><th>Note pondérée</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($modules as $i=>$m): ?>
          <tr>
            <td><?= $i+1 ?></td>
            <td><?= htmlspecialchars($m['module']) ?></td>
            <td><?= $m['coefficient'] ?></td>
            <td><?= is_numeric($m['d1']) ? $m['d1'] : '-' ?></td>
            <td><?= is_numeric($m['d2']) ? $m['d2'] : '-' ?></td>
            <td><?= is_numeric($m['ex']) ? $m['ex'] : '-' ?></td>
            <td><?= $m['note_ponderee'] ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>

      <div class="footer-summary">
        <h5>Moyenne générale : <span class="badge bg-info"><?= $moyenne_generale ?> / 20</span></h5>
        <h5>Rang : <span class="badge bg-danger"><?= $rang ?></span></h5>
      </div>

      <div class="observation-box">
        <label><strong>Observations :</strong></label>
        <textarea readonly></textarea>
      </div>
      <div class="signature-box">
        <div>Signature du directeur</div>
        <div class="line"></div>
      </div>
    </div>
  <?php endforeach; ?>
<?php endif; ?>
</div>

</body>
</html>
