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

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

$matricule = $_GET['matricule'] ?? '';
$classe_id = $_GET['classe_id'] ?? null;
$etudiant = null;
$etudiantsClasse = [];
$modules = [];
$moyenne_generale = null;
$rang = null;
$total_coef = 0;
$total_pond = 0;
$nombre_etudiants = 0;

if ($matricule) {
    $stmt = $conn->prepare("SELECT e.id, e.matricule, e.noms, e.prenom, e.date_de_naissance, e.lieu_de_naissance, c.nom AS classe, e.classe_id
                            FROM etudiants e JOIN classes c ON e.classe_id=c.id WHERE e.matricule=?");
    $stmt->bind_param("s", $matricule);
    $stmt->execute();
    $etudiant = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($etudiant) {
        $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'], $etudiant['classe_id']);
        $stmt->execute();
        $res = $stmt->get_result();

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

        $stmtRang = $conn->prepare("SELECT COUNT(*) + 1 AS rang FROM (
                                        SELECT e.id,
                                        SUM((COALESCE(d1.note,0) + COALESCE(d2.note,0) + COALESCE(ex.note,0))/3 * m.coefficient) / SUM(m.coefficient) AS moyenne_gen
                                        FROM etudiants e
                                        JOIN modules m ON m.classe_id = e.classe_id
                                        LEFT JOIN notes d1 ON d1.module_id = m.id AND d1.etudiant_id = e.id AND d1.type_note = 'Devoir 1'
                                        LEFT JOIN notes d2 ON d2.module_id = m.id AND d2.etudiant_id = e.id AND d2.type_note = 'Devoir 2'
                                        LEFT JOIN notes ex ON ex.module_id = m.id AND ex.etudiant_id = e.id AND ex.type_note = 'Examen'
                                        WHERE e.classe_id = ?
                                        GROUP BY e.id
                                        HAVING moyenne_gen > ?
                                    ) AS subquery");
        $stmtRang->bind_param("id", $etudiant['classe_id'], $moyenne_generale);
        $stmtRang->execute();
        $resRang = $stmtRang->get_result();
        $rang = $resRang->fetch_assoc()['rang'] ?? null;
        $stmtRang->close();

        $stmtCount = $conn->prepare("SELECT COUNT(*) AS total FROM etudiants WHERE classe_id = ?");
        $stmtCount->bind_param("i", $etudiant['classe_id']);
        $stmtCount->execute();
        $resultCount = $stmtCount->get_result()->fetch_assoc();
        $nombre_etudiants = $resultCount['total'];
        $stmtCount->close();
    }
} elseif ($classe_id) {
    $stmt = $conn->prepare("SELECT id, matricule, noms, prenom FROM etudiants WHERE classe_id = ?");
    $stmt->bind_param("i", $classe_id);
    $stmt->execute();
    $etudiantsClasse = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <title>Bulletin</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
  <style>
    :root {
      --primary-color: #1a5276;
      --secondary-color: #1a7f76;
      --accent-color: #a8e6cf;
      --light-bg: #f8f9fa;
      --text-dark: #333;
      --text-light: #fff;
    }
    
    body {
      background: var(--light-bg);
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      padding: 30px 0;
    }
    
    .bulletin-container {
      width: 794px;
      background: white;
      padding: 30px 40px;
      margin: auto;
      border-radius: 8px;
      box-shadow: 0 5px 30px rgba(26, 127, 118, 0.15);
    }
    
    .header-bulletin {
      background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
      color: var(--text-light);
      border-radius: 8px 8px 0 0;
      display: flex;
      align-items: center;
      padding: 15px 20px;
      margin-bottom: 25px;
    }
    
    .header-left {
      width: 100px;
      padding: 5px;
      background: white;
      border-radius: 6px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .header-left img {
      max-width: 100%;
      max-height: 80px;
    }
    
    .header-right {
      flex: 1;
      text-align: right;
      padding-left: 20px;
    }
    
    .header-right h2 {
      margin: 0;
      font-size: 1.8rem;
      font-weight: 700;
      letter-spacing: 0.5px;
    }
    
    .header-right p {
      margin: 3px 0;
      font-size: 0.9rem;
    }
    
    .infos-etudiant {
      margin: 20px 0;
      border: 1px solid #e0e0e0;
      padding: 15px;
      border-radius: 8px;
      background: #f9f9f9;
      display: flex;
      justify-content: space-between;
      box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    }
    
    .infos-etudiant p {
      margin: 5px 0;
    }
    
    .table {
      margin-top: 20px;
      border-collapse: separate;
      border-spacing: 0;
      border-radius: 8px;
      overflow: hidden;
    }
    
    .table thead {
      background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
      color: var(--text-light);
    }
    
    .table th {
      font-weight: 500;
      padding: 12px 8px;
    }
    
    .table td {
      padding: 10px 8px;
      vertical-align: middle;
    }
    
    .table tbody tr:nth-child(even) {
      background-color: #f5f5f5;
    }
    
    .table tbody tr:hover {
      background-color: #e8f4f2;
    }
    
    .summary-table {
      width: 100%;
      margin-top: 25px;
      background: #f9f9f9;
      border-radius: 8px;
      overflow: hidden;
    }
    
    .summary-table th {
      background-color: var(--secondary-color);
      color: white;
      text-align: center;
    }
    
    .summary-table td {
      text-align: center;
      font-weight: 500;
      padding: 12px;
    }
    
    .observation-box textarea {
      width: 100%;
      border: 1px solid #ddd;
      border-radius: 6px;
      padding: 10px;
      resize: none;
      min-height: 80px;
      margin-top: 20px;
    }
    
    .signature-box {
      margin-top: 40px;
      text-align: right;
    }
    
    .signature-line {
      display: inline-block;
      width: 250px;
      border-top: 1px solid var(--primary-color);
      margin-top: 60px;
      position: relative;
    }
    
    .signature-text {
      position: absolute;
      top: -20px;
      left: 50%;
      transform: translateX(-50%);
      background: white;
      padding: 0 10px;
      color: var(--primary-color);
      font-style: italic;
    }
    
    .btn-primary {
      background-color: var(--primary-color);
      border-color: var(--primary-color);
    }
    
    .btn-primary:hover {
      background-color: #144a6d;
      border-color: #144a6d;
    }
    
    .btn-success {
      background-color: var(--secondary-color);
      border-color: var(--secondary-color);
    }
    
    .btn-success:hover {
      background-color: #15776d;
      border-color: #15776d;
    }
    
    @media print {
      .no-print {
        display: none;
      }
      .bulletin-container {
        box-shadow: none;
        padding: 0;
      }
      body {
        padding: 0;
        background: white;
      }
      * {
        -webkit-print-color-adjust: exact !important;
        print-color-adjust: exact !important;
      }
    }
  </style>
</head>
<body>
<div class="bulletin-container">
  <div class="header-bulletin">
    <div class="header-left">
      <img src="assetss/logo.png" alt="Logo École">
    </div>
    <div class="header-right">
      <h2>Bulletin de Notes</h2>
      <p><strong>MAIN IT CENTER</strong></p>
      <p>Kaolack, Leona Lot 167 • Tél : 76 947 21 10</p>
      <p>Email : mainitcenter@gmail.com</p>
    </div>
  </div>

  <?php if (!$etudiant && !$classe_id): ?>
    <div class="search-boxes">
      <form class="row g-3 mb-4" method="get">
        <div class="col-md-8">
          <div class="input-group">
            <span class="input-group-text"><i class="fas fa-id-card"></i></span>
            <input name="matricule" class="form-control" placeholder="Entrez le matricule de l'étudiant" required>
          </div>
        </div>
        <div class="col-md-4">
          <button class="btn btn-success w-100">
            <i class="fas fa-search me-2"></i> Rechercher
          </button>
        </div>
      </form>
      
      <div class="divider d-flex align-items-center my-4">
        <div class="border-top flex-grow-1"></div>
        <span class="px-3 text-muted">OU</span>
        <div class="border-top flex-grow-1"></div>
      </div>
      
      <form class="row g-3" method="get">
        <div class="col-md-8">
          <div class="input-group">
            <span class="input-group-text"><i class="fas fa-users"></i></span>
            <select name="classe_id" class="form-select" required>
              <option value="">-- Sélectionnez une classe --</option>
              <?php
              $res = $conn->query("SELECT id, nom FROM classes ORDER BY nom");
              while ($row = $res->fetch_assoc()):
              ?>
                <option value="<?= $row['id'] ?>"><?= htmlspecialchars($row['nom']) ?></option>
              <?php endwhile; ?>
            </select>
          </div>
        </div>
        <div class="col-md-4">
          <button class="btn btn-primary w-100">
            <i class="fas fa-list me-2"></i> Lister la classe
          </button>
        </div>
      </form>
    </div>

  <?php elseif ($etudiant): ?>
    <div class="infos-etudiant">
      <div>
        <p><strong><i class="fas fa-user me-2"></i> Prénom :</strong> <?= htmlspecialchars($etudiant['prenom']) ?></p>
        <p><strong><i class="fas fa-user-tag me-2"></i> Nom :</strong> <?= htmlspecialchars($etudiant['noms']) ?></p>
        <p><strong><i class="fas fa-birthday-cake me-2"></i> Né(e) le :</strong> <?= htmlspecialchars($etudiant['date_de_naissance'] . ' à ' . $etudiant['lieu_de_naissance']) ?></p>
      </div>
      <div>
        <p><strong><i class="fas fa-id-badge me-2"></i> Matricule :</strong> <?= htmlspecialchars($etudiant['matricule']) ?></p>
        <p><strong><i class="fas fa-graduation-cap me-2"></i> Classe :</strong> <?= htmlspecialchars($etudiant['classe']) ?></p>
        <p><strong><i class="fas fa-calendar-alt me-2"></i> Année scolaire :</strong> 2025-2026</p>
      </div>
    </div>

    <div class="table-responsive">
      <table class="table table-bordered table-hover">
        <thead>
          <tr>
            <th width="5%">#</th>
            <th width="25%">Module</th>
            <th width="8%">Coef</th>
            <th width="12%">Devoir 1</th>
            <th width="12%">Devoir 2</th>
            <th width="12%">Examen</th>
            <th width="13%">Moy. Pond.</th>
            <th width="13%">Appréciation</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($modules as $i => $mod): ?>
          <tr>
            <td><?= $i + 1 ?></td>
            <td><?= htmlspecialchars($mod['module']) ?></td>
            <td><?= $mod['coefficient'] ?></td>
            <td><?= is_numeric($mod['d1']) ? number_format($mod['d1'], 2) : '-' ?></td>
            <td><?= is_numeric($mod['d2']) ? number_format($mod['d2'], 2) : '-' ?></td>
            <td><?= is_numeric($mod['ex']) ? number_format($mod['ex'], 2) : '-' ?></td>
            <td><?= number_format($mod['note_ponderee'], 2) ?></td>
            <td class="<?= $mod['appreciation'] === 'Suffisant' ? 'text-success' : 'text-danger' ?>">
              <i class="fas fa-<?= $mod['appreciation'] === 'Suffisant' ? 'check-circle' : 'times-circle' ?> me-1"></i>
              <?= $mod['appreciation'] ?>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>

    <table class="table summary-table">
      <tr>
        <th><i class="fas fa-calculator me-2"></i> Moyenne Générale</th>
        <th><i class="fas fa-trophy me-2"></i> Rang</th>
        <th><i class="fas fa-users me-2"></i> Effectif Classe</th>
      </tr>
      <tr>
        <td class="fw-bold"><?= number_format($moyenne_generale, 2) ?> / 20</td>
        <td><?= $rang ?><?= $rang ? ' / ' . $nombre_etudiants : '' ?></td>
        <td><?= $nombre_etudiants ?> élèves</td>
      </tr>
    </table>

    <div class="observation-box">
      <label class="form-label"><i class="fas fa-comment me-2"></i> Observations :</label>
      <textarea class="form-control" placeholder="Remarques ou commentaires..."></textarea>
    </div>

    <div class="signature-box">
      <div class="signature-line">
        <span class="signature-text">Signature du Directeur</span>
      </div>
    </div>

    <div class="text-center mt-4 no-print">
      <button onclick="window.print()" class="btn btn-primary me-2">
        <i class="fas fa-print me-2"></i> Imprimer
      </button>
      <a href="?" class="btn btn-secondary">
        <i class="fas fa-redo me-2"></i> Nouvelle recherche
      </a>
    </div>

  <?php elseif ($classe_id): ?>
    <div class="d-flex justify-content-between align-items-center mb-4">
      <h4 class="mb-0"><i class="fas fa-users-class me-2"></i> Liste des étudiants</h4>
      <a href="?" class="btn btn-sm btn-secondary">
        <i class="fas fa-arrow-left me-1"></i> Retour
      </a>
    </div>
    
    <div class="table-responsive">
      <table class="table table-bordered table-hover">
        <thead>
          <tr>
            <th width="5%">#</th>
            <th width="20%">Matricule</th>
            <th>Nom complet</th>
            <th width="15%">Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($etudiantsClasse as $i => $e): ?>
          <tr>
            <td><?= $i + 1 ?></td>
            <td><?= htmlspecialchars($e['matricule']) ?></td>
            <td><?= htmlspecialchars($e['prenom'] . ' ' . $e['noms']) ?></td>
            <td>
              <a href="?matricule=<?= urlencode($e['matricule']) ?>" class="btn btn-sm btn-primary">
                <i class="fas fa-file-alt me-1"></i> Bulletin
              </a>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  <?php endif; ?>
</div>
</body>
</html>