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

require_once "includes/dbconn.php";
 include('includes/header.php');
    require_once "includes/dbconn.php";
$selected_classe = $_GET['classe_id'] ?? '';

$classes_result = $conn->query("SELECT id, nom FROM classes ORDER BY nom ASC");
$classes = [];
if ($classes_result && $classes_result->num_rows > 0) {
    while ($c = $classes_result->fetch_assoc()) {
        $classes[] = $c;
    }
}

$where = '';
if ($selected_classe !== '' && is_numeric($selected_classe)) {
    $where = " WHERE e.classe_id = " . intval($selected_classe);
}

$sql = "SELECT e.matricule, e.noms, e.prenom, e.phone, e.date_de_naissance, e.photo, c.nom AS classe_nom, c.id AS classe_id
        FROM etudiants e
        LEFT JOIN classes c ON e.classe_id = c.id
        $where
        ORDER BY c.nom, e.noms, e.prenom";

$result = $conn->query($sql);

$etudiants = [];
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $etudiants[] = $row;
    }
}

$etudiants_par_classe = [];
foreach ($etudiants as $e) {
    $key = $e['classe_nom'] ?: "Sans classe";
    $etudiants_par_classe[$key][] = $e;
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8" />
  <title>Carte d'Identité Étudiante</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    :root {
      --primary-blue: #1a5276;
      --secondary-blue: #2980b9;
      --primary-green: #27ae60;
      --secondary-green: #2ecc71;
      --light-bg: #f5f9fc;
      --text-dark: #2c3e50;
      --text-light: #ecf0f1;
      --border-color: #d6e0ea;
    }

    body {
      background: var(--light-bg);
      font-family: 'Roboto', sans-serif;
      padding: 20px 0;
    }

    .header {
      background: linear-gradient(135deg, var(--primary-blue), var(--secondary-blue));
      color: var(--text-light);
      padding: 20px 0;
      margin-bottom: 30px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
      border-bottom: 4px solid var(--primary-green);
    }

    .header-title {
      font-weight: 700;
      letter-spacing: 1px;
      margin: 0;
      font-size: 24px;
      text-shadow: 1px 1px 3px rgba(0,0,0,0.2);
    }

    .filter-container {
      background: white;
      border-radius: 10px;
      padding: 20px;
      box-shadow: 0 5px 15px rgba(0,0,0,0.05);
      margin-bottom: 30px;
      max-width: 900px;
      margin-left: auto;
      margin-right: auto;
      border: 1px solid var(--border-color);
    }

    .form-select {
      border: 2px solid var(--border-color);
      border-radius: 8px;
      padding: 10px 15px;
      font-size: 15px;
      transition: all 0.3s;
    }

    .form-select:focus {
      border-color: var(--primary-green);
      box-shadow: 0 0 0 0.25rem rgba(39, 174, 96, 0.25);
    }

    .btn-print {
      background: linear-gradient(to right, var(--primary-green), var(--secondary-green));
      border: none;
      padding: 10px 25px;
      border-radius: 8px;
      font-weight: 500;
      transition: all 0.3s;
      color: white;
      box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    }

    .btn-print:hover {
      background: linear-gradient(to right, #219955, #27ae60);
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0,0,0,0.15);
      color: white;
    }

    .section-title {
      color: var(--primary-blue);
      font-weight: 600;
      margin: 30px 0 20px;
      font-size: 20px;
      padding-bottom: 8px;
      border-bottom: 3px solid var(--primary-green);
      display: inline-block;
    }

    .cards-container {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
      gap: 25px;
      padding: 10px;
    }

    /* Format carte ID standard (85.6mm × 53.98mm) */
    .id-card {
      width: 250px;
      height: 160px;
      background: white;
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 5px 15px rgba(0,0,0,0.1);
      position: relative;
      margin: 0 auto;
      transition: transform 0.3s, box-shadow 0.3s;
      border: 1px solid var(--border-color);
    }

    .id-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 25px rgba(0,0,0,0.15);
    }

    .card-header {
      background: linear-gradient(135deg, var(--primary-blue), var(--secondary-blue));
      color: var(--text-light);
      padding: 10px 15px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 35px;
    }

    .school-name {
      font-weight: 600;
      font-size: 11px;
      line-height: 1.2;
      letter-spacing: 0.5px;
    }

    .school-logo {
      width: 28px;
      height: 28px;
      object-fit: contain;
      border-radius: 50%;
      background: white;
      padding: 2px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .card-body {
      display: flex;
      padding: 10px;
      height: calc(100% - 65px);
    }

    .student-photo {
      width: 65px;
      height: 80px;
      border-radius: 6px;
      object-fit: cover;
      border: 2px solid var(--border-color);
      margin-right: 12px;
      flex-shrink: 0;
      background: #f8f9fa;
    }

    .student-info {
      flex-grow: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      font-size: 11px;
    }

    .student-name {
      font-weight: 700;
      font-size: 13px;
      color: var(--primary-blue);
      margin: 0 0 5px 0;
      line-height: 1.3;
    }

    .student-detail {
      margin: 4px 0;
      display: flex;
    }

    .detail-label {
      font-weight: 600;
      min-width: 60px;
      color: var(--primary-green);
    }

    .card-footer {
      background: linear-gradient(to right, #f8f9fa, #eef2f5);
      padding: 6px 10px;
      font-size: 9px;
      text-align: center;
      border-top: 1px solid var(--border-color);
      height: 25px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 500;
      color: var(--primary-blue);
    }

    .no-students {
      text-align: center;
      padding: 40px;
      color: #7f8c8d;
      font-size: 16px;
      background: white;
      border-radius: 10px;
      max-width: 600px;
      margin: 30px auto;
      box-shadow: 0 3px 10px rgba(0,0,0,0.05);
    }

    /* Animation */
    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(10px); }
      to { opacity: 1; transform: translateY(0); }
    }

    .id-card {
      animation: fadeIn 0.4s ease-out forwards;
      opacity: 0;
    }

    .id-card:nth-child(1) { animation-delay: 0.1s; }
    .id-card:nth-child(2) { animation-delay: 0.2s; }
    .id-card:nth-child(3) { animation-delay: 0.3s; }
    .id-card:nth-child(4) { animation-delay: 0.4s; }
    .id-card:nth-child(5) { animation-delay: 0.5s; }
    .id-card:nth-child(n+6) { animation-delay: 0.6s; }

    /* Styles d'impression améliorés */
    @media print {
      @page {
        size: A4 landscape;
        margin: 0.5cm;
      }
      
      body {
        background: white !important;
        padding: 0 !important;
      }
      
      .header, .filter-container {
        display: none !important;
      }
      
      .cards-container {
        grid-template-columns: repeat(3, 1fr) !important;
        gap: 0.5cm !important;
        padding: 0 !important;
      }
      
      .id-card {
        width: 85.6mm !important;
        height: 53.98mm !important;
        box-shadow: none !important;
        border: 1px solid #ddd !important;
        margin: 0 auto !important;
        page-break-inside: avoid !important;
        break-inside: avoid !important;
        -webkit-print-color-adjust: exact !important;
        print-color-adjust: exact !important;
      }
      
      /* Forcer les couleurs à l'impression */
      .card-header {
        background: linear-gradient(135deg, #1a5276, #2980b9) !important;
        color: white !important;
        -webkit-print-color-adjust: exact !important;
        print-color-adjust: exact !important;
      }
      
      .student-name {
        color: #1a5276 !important;
      }
      
      .detail-label {
        color: #27ae60 !important;
      }
      
      .card-footer {
        background: linear-gradient(to right, #f8f9fa, #eef2f5) !important;
        border-top: 1px solid #ddd !important;
      }
      
      /* Optimisation du texte pour l'impression */
      * {
        text-shadow: none !important;
        color-adjust: exact !important;
        -webkit-print-color-adjust: exact !important;
        print-color-adjust: exact !important;
      }
    }

    /* Badge pour le filtre actif */
    .active-filter {
      display: inline-block;
      background: var(--primary-green);
      color: white;
      padding: 3px 10px;
      border-radius: 15px;
      font-size: 14px;
      margin-left: 10px;
      vertical-align: middle;
    }

    /* Responsive */
    @media (max-width: 768px) {
      .cards-container {
        grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
      }
      
      .filter-container {
        padding: 15px;
      }
      
      .header-title {
        font-size: 20px;
      }
    }
  </style>
</head>
<body>

  <header class="header">
    <div class="container text-center">
      <h1 class="header-title">
        <i class="fas fa-id-card me-2"></i>CARTE ÉTUDIANTES
        <?php if ($selected_classe && isset($classes[array_search($selected_classe, array_column($classes, 'id'))])): ?>
          <span class="active-filter">
            <?= htmlspecialchars($classes[array_search($selected_classe, array_column($classes, 'id'))]['nom']) ?>
          </span>
        <?php endif; ?>
      </h1>
    </div>
  </header>

  <div class="container">
    <div class="filter-container">
      <form method="get" class="row align-items-center">
        <div class="col-md-8 mb-3 mb-md-0">
          <label for="classe_id" class="form-label fw-medium">
            <i class="fas fa-filter me-1"></i>Filtrer par classe :
          </label>
          <select name="classe_id" id="classe_id" class="form-select" onchange="this.form.submit()">
            <option value="">Toutes les classes</option>
            <?php foreach ($classes as $c): ?>
              <option value="<?= $c['id'] ?>" <?= ($selected_classe == $c['id']) ? 'selected' : '' ?>>
                <?= htmlspecialchars($c['nom']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-4 d-flex align-items-end">
          <button type="button" id="printBtn" class="btn btn-print w-100">
            <i class="fas fa-print me-2"></i> Imprimer les cartes
          </button>
        </div>
      </form>
    </div>

    <?php if (empty($etudiants_par_classe)): ?>
      <div class="no-students">
        <i class="fas fa-user-graduate fa-3x mb-3" style="color: #bdc3c7;"></i>
        <p class="mb-0">Aucun étudiant trouvé pour cette sélection</p>
      </div>
    <?php else: ?>
      <?php foreach ($etudiants_par_classe as $classe_nom => $eleves): ?>
        <h2 class="section-title">
          <i class="fas fa-users-class me-2"></i>Classe : <?= htmlspecialchars($classe_nom) ?>
          <small class="text-muted ms-2"><?= count($eleves) ?> étudiant(s)</small>
        </h2>
        <div class="cards-container">
          <?php foreach ($eleves as $e): ?>
            <div class="id-card">
              <div class="card-header">
                <div class="school-name">
                 MAIN IT-CENTER 
                </div>
                <img src="assetss/logo.jpeg" alt="Logo École" class="school-logo" />
              </div>
              <div class="card-body">
                <img src="<?= !empty($e['photo']) ? 'studentimages/' . htmlspecialchars($e['photo']) : 'assetss/demo-photo.jpg' ?>"
                     alt="Photo de <?= htmlspecialchars($e['noms'] . ' ' . $e['prenom']) ?>"
                     class="student-photo" />
                <div class="student-info">
                  <div>
                    <h3 class="student-name"><?= htmlspecialchars($e['prenom'] . ' ' . $e['noms']) ?></h3>
                    <p class="student-detail">
                      <span class="detail-label">MATRICULE:</span>
                      <span><?= htmlspecialchars($e['matricule']) ?></span>
                    </p>
                    <p class="student-detail">
                      <span class="detail-label">CLASSE:</span>
                      <span><?= htmlspecialchars($classe_nom) ?></span>
                    </p>
                    <p class="student-detail">
                      <span class="detail-label">NÉ(E) LE:</span>
                      <span><?= htmlspecialchars(date('d/m/Y', strtotime($e['date_de_naissance']))) ?></span>
                    </p>
                  </div>
                </div>
              </div>
              <div class="card-footer">
                <i class="fas fa-calendar-alt me-1"></i> Année académique 2025/2026
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/js/all.min.js"></script>
  <script>
    document.getElementById('printBtn').addEventListener('click', function() {
      // Afficher un message avant l'impression
      if (confirm("Pour une impression optimale :\n\n1. Sélectionnez 'Paysage' dans les options d'impression\n2. Cochez 'Arrière-plans et images'\n\nCliquez sur OK pour continuer")) {
        window.print();
      }
    });

    // Animation trigger
    document.addEventListener('DOMContentLoaded', function() {
      const cards = document.querySelectorAll('.id-card');
      cards.forEach(card => {
        card.style.opacity = '1';
      });
    });
  </script>
</body>
</html>