<?php
/**
 * Cartes d'identité scolaire — élèves et enseignants
 */
require_once '../config/database.php';
require_once '../includes/auth_check.php';
require_once '../includes/functions.php';
header('Content-Type: text/html; charset=utf-8');

checkRole(['super_admin', 'school_admin', 'teacher']);
requirePermission('students', 'view');

$schoolFilter = currentSchoolId();
if (isSuperAdmin() && !empty($_GET['school_id'])) {
    $schoolFilter = (int)$_GET['school_id'];
}

// ── Charger les réglages carte depuis la BDD ──
$cardSettings = [];
if ($schoolFilter) {
    $st = $pdo->prepare("SELECT * FROM id_card_settings WHERE school_id=?");
    $st->execute([$schoolFilter]);
    $cardSettings = $st->fetch() ?: [];
}

// ── Sauvegarde des réglages ──
if (isset($_GET['save_settings']) && $schoolFilter && hasRole(['super_admin','school_admin'])) {
    verifyCsrf();
    $pdo->prepare("INSERT INTO id_card_settings (school_id, bg1, bg2, title_color, label_color, show_flag, show_logo, card_width, card_height, updated_at)
                    VALUES (?,?,?,?,?,?,?,?,?,NOW())
                    ON DUPLICATE KEY UPDATE bg1=VALUES(bg1), bg2=VALUES(bg2), title_color=VALUES(title_color), label_color=VALUES(label_color),
                                             show_flag=VALUES(show_flag), show_logo=VALUES(show_logo), card_width=VALUES(card_width), card_height=VALUES(card_height), updated_at=NOW()")
        ->execute([$schoolFilter,
            $_GET['bg1'] ?? '#7eb8f7',
            $_GET['bg2'] ?? '#b8d8f7',
            $_GET['title_color'] ?? '#1a3a5c',
            $_GET['label_color'] ?? '#0d2640',
            isset($_GET['show_flag']) ? 1 : 0,
            isset($_GET['show_logo']) ? 1 : 0,
            (int)($_GET['card_width'] ?? 540),
            (int)($_GET['card_height'] ?? 340)
        ]);
    flashMessage('success', 'Réglages de la carte enregistrés.');
    $qs = http_build_query(array_filter(['type'=>$type,'school_id'=>$schoolFilter,'class_id'=>$classId,'academic_year'=>$currentYear]));
    header("Location: id_cards.php?$qs");
    exit;
}

// ── Réinitialisation des réglages ──
if (isset($_GET['reset_settings']) && $schoolFilter && hasRole(['super_admin','school_admin'])) {
    verifyCsrf();
    $pdo->prepare("DELETE FROM id_card_settings WHERE school_id=?")->execute([$schoolFilter]);
    flashMessage('success', 'Réglages réinitialisés (défaut).');
    $qs = http_build_query(array_filter(['type'=>$type,'school_id'=>$schoolFilter,'class_id'=>$classId,'academic_year'=>$currentYear]));
    header("Location: id_cards.php?$qs");
    exit;
}

// ── Appliquer réglages (GET surcharge la BDD) ──
$cs_bg1         = $_GET['bg1'] ?? ($cardSettings['bg1'] ?? '#7eb8f7');
$cs_bg2         = $_GET['bg2'] ?? ($cardSettings['bg2'] ?? '#b8d8f7');
$cs_title_color = $_GET['title_color'] ?? ($cardSettings['title_color'] ?? '#1a3a5c');
$cs_label_color = $_GET['label_color'] ?? ($cardSettings['label_color'] ?? '#0d2640');
$cs_show_flag   = isset($_GET['show_flag']) ? (bool)$_GET['show_flag'] : ($cardSettings['show_flag'] ?? true);
$cs_show_logo   = isset($_GET['show_logo']) ? (bool)$_GET['show_logo'] : ($cardSettings['show_logo'] ?? true);
$cs_card_w = (int)($_GET['card_width'] ?? ($cardSettings['card_width'] ?? 540));
$cs_card_h = (int)($_GET['card_height'] ?? ($cardSettings['card_height'] ?? 340));
if ($cs_card_w < 200) $cs_card_w = 200;
if ($cs_card_h < 120) $cs_card_h = 120;
// Dimensions d'impression (physiques) : 1px CSS = 1/96 pouce = 25,4/96 mm
$cs_card_w_mm = round($cs_card_w * 25.4 / 96, 3);
$cs_card_h_mm = round($cs_card_h * 25.4 / 96, 3);

if ($schoolFilter) {
    $academicYears = $pdo->prepare("SELECT DISTINCT year FROM academic_years WHERE school_id=? ORDER BY year DESC");
    $academicYears->execute([$schoolFilter]);
    $academicYears = $academicYears->fetchAll(PDO::FETCH_COLUMN);
} else {
    $academicYears = $pdo->query("SELECT DISTINCT year FROM academic_years ORDER BY year DESC")->fetchAll(PDO::FETCH_COLUMN);
}
if (empty($academicYears)) { $academicYears = []; }
$academicYears = array_unique(array_merge($academicYears, [date('Y') . '-' . (date('Y')+1)]));
$defaultYear = getDefaultAcademicYear($pdo, currentSchoolId());
$currentYear = $_GET['academic_year'] ?? $defaultYear;

$type    = $_GET['type'] ?? 'students';
$classId = (int)($_GET['class_id'] ?? 0);
$selIds  = isset($_GET['ids']) ? array_map('intval', (array)$_GET['ids']) : [];

// Écoles
$schools = $pdo->query("SELECT id, name, logo, address, phone, email FROM schools ORDER BY name")->fetchAll();

// Classes (filtrées par école)
if ($schoolFilter) {
    $stmt = $pdo->prepare("SELECT DISTINCT c.id, c.name FROM classes c JOIN students s ON s.class_id = c.id WHERE s.school_id=? ORDER BY " . getClassSortSQL('c'));
    $stmt->execute([$schoolFilter]);
    $classes = $stmt->fetchAll();
} else {
    $classes = $pdo->query("SELECT id, name FROM classes c ORDER BY " . getClassSortSQL('c'))->fetchAll();
}

// Charger les données selon le type
$cards = [];
if ($type === 'students') {
    $sql = "SELECT s.id, s.first_name, s.last_name, s.gender, s.birth_date,
                   c.name AS class_name, sc.name AS school_name, sc.logo AS school_logo,
                   sc.address, sc.phone AS school_phone, sc.email AS school_email,
                   u.photo
            FROM students s
            JOIN classes c ON s.class_id = c.id
            JOIN schools sc ON s.school_id = sc.id
            LEFT JOIN users u ON s.user_id = u.id";
    $where = [];
    $params = [];
    if ($schoolFilter) { $where[] = "s.school_id=?"; $params[] = $schoolFilter; }
    if ($classId) { $where[] = "s.class_id=?"; $params[] = $classId; }
    if (!empty($selIds)) {
        $placeholders = implode(',', array_fill(0, count($selIds), '?'));
        $where[] = "s.id IN ($placeholders)";
        $params = array_merge($params, $selIds);
    }
    if ($where) $sql .= " WHERE " . implode(' AND ', $where);
    $sql .= " ORDER BY s.last_name, s.first_name";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $cards = $stmt->fetchAll();
} else {
    $sql = "SELECT t.id, t.first_name, t.last_name, t.gender, t.phone, t.email, t.diploma, t.subject,
                   sc.name AS school_name, sc.logo AS school_logo,
                   sc.address, sc.phone AS school_phone, sc.email AS school_email,
                   u.photo
            FROM teachers t
            JOIN schools sc ON t.school_id = sc.id
            LEFT JOIN users u ON u.email = t.email";
    $where = [];
    $params = [];
    if ($schoolFilter) { $where[] = "t.school_id=?"; $params[] = $schoolFilter; }
    if (!empty($selIds)) {
        $placeholders = implode(',', array_fill(0, count($selIds), '?'));
        $where[] = "t.id IN ($placeholders)";
        $params = array_merge($params, $selIds);
    }
    if ($where) $sql .= " WHERE " . implode(' AND ', $where);
    $sql .= " ORDER BY t.last_name, t.first_name";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $cards = $stmt->fetchAll();
}

// Vérifier les cartes importées pour ces personnes
$importedIds = [];
if (!empty($cards)) {
    $idCol = $type === 'students' ? 'student' : 'teacher';
    $stmt = $pdo->prepare("SELECT person_id, type FROM imported_idcards WHERE type=? AND person_id IS NOT NULL AND status='valide'");
    $stmt->execute([$idCol]);
    foreach ($stmt->fetchAll() as $r) {
        $importedIds[$r['person_id']] = true;
    }
}

// Ajouter l'année scolaire à chaque carte
foreach ($cards as &$card) {
    $card['academic_year'] = $currentYear;
    // Générer un ID unique simple
    $prefix = $type === 'students' ? 'EL' : 'PR';
    $card['card_id'] = $prefix . '-' . str_pad($card['id'], 5, '0', STR_PAD_LEFT) . '/' . substr($currentYear, 2, 2) . substr($currentYear, 7, 2);
    $card['has_imported'] = isset($importedIds[$card['id']]);
}
unset($card);
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cartes d'identité - Nukunu Mofiala</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --card-w: <?= $cs_card_w ?>px;
            --card-h: <?= $cs_card_h ?>px;
            --bg1: <?= e($cs_bg1) ?>;
            --bg2: <?= e($cs_bg2) ?>;
            --bg3: #e0f0ff;
            --bg4: #f5faff;
            --title-color: <?= e($cs_title_color) ?>;
            --text-color: <?= e($cs_title_color) ?>;
            --label-color: <?= e($cs_label_color) ?>;
            --photo-size: 130px;
            --font-family: 'Times New Roman', Times, serif;
        }

        .idcard-grid {
            display: block;
            margin-top: 1rem;
        }

        .card-page {
            width: var(--card-w);
            margin: 0 auto 2rem auto;
            background: #fff;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 2rem;
            box-shadow: 0 10px 30px rgba(0,0,0,.15);
        }

        .card-page:last-child { margin-bottom: 0; }

        .carte {
            width: var(--card-w);
            height: var(--card-h);
            margin: 0 auto;
            position: relative;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 10px 40px rgba(0,0,0,.25), 0 2px 8px rgba(0,0,0,.15);
            background: linear-gradient(160deg, var(--bg1) 0%, var(--bg2) 40%, var(--bg3) 70%, var(--bg4) 100%);
            font-family: var(--font-family);
        }

        .carte::before {
            content: '';
            position: absolute;
            inset: 0;
            background:
                repeating-linear-gradient(45deg, transparent, transparent 18px, rgba(255,255,255,.35) 18px, rgba(255,255,255,.35) 19px),
                repeating-linear-gradient(-45deg, transparent, transparent 18px, rgba(255,255,255,.35) 18px, rgba(255,255,255,.35) 19px);
            pointer-events: none;
            z-index: 1;
        }

        .carte-contenu {
            position: relative;
            z-index: 2;
            width: 100%;
            height: 100%;
            padding: 16px 22px 92px 22px;
            display: flex;
            flex-direction: column;
        }

        .carte-en-tete {
            text-align: center;
            margin-bottom: 6px;
        }

        .carte-en-tete h1 {
            font-size: 21px;
            font-weight: bold;
            color: var(--title-color);
            text-decoration: underline;
            text-underline-offset: 4px;
            letter-spacing: .5px;
            text-shadow: 0 1px 2px rgba(255,255,255,.6);
        }

        .carte-drapeau {
            position: absolute;
            top: 14px;
            right: 18px;
            width: 52px;
            height: 34px;
            border-radius: 3px;
            overflow: hidden;
            box-shadow: 0 2px 6px rgba(0,0,0,.2);
            z-index: 10;
        }

        .carte-drapeau .bande { width: 100%; height: 20%; }
        .carte-drapeau .verte { background: #006a4e; }
        .carte-drapeau .jaune { background: #ffce00; }
        .carte-drapeau .canton {
            position: absolute;
            top: 0; left: 0;
            width: 40%; height: 60%;
            background: #d21034;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .carte-drapeau .etoile {
            width: 50%; height: 50%;
            background: white;
            clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%);
        }

        .carte-corps {
            display: flex;
            align-items: center;
            gap: 28px;
            flex: 1;
            padding: 0 8px;
        }

        .carte-photo {
            width: var(--photo-size);
            height: var(--photo-size);
            min-width: var(--photo-size);
            border-radius: 50%;
            background: #fff;
            box-shadow: 0 0 25px 12px rgba(255,255,255,.7), 0 4px 15px rgba(0,0,0,.1);
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            position: relative;
        }

        .carte-photo img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .carte-photo-initial {
            width: var(--photo-size);
            height: var(--photo-size);
            min-width: var(--photo-size);
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea, #764ba2);
            box-shadow: 0 0 25px 12px rgba(255,255,255,.7), 0 4px 15px rgba(0,0,0,.1);
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 2.8rem;
            color: white;
            overflow: hidden;
            position: relative;
        }

        .carte-infos {
            flex: 1;
            background: rgba(255,255,255,.55);
            backdrop-filter: blur(6px);
            -webkit-backdrop-filter: blur(6px);
            border-radius: 14px;
            padding: 16px 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,.08);
            border: 1px solid rgba(255,255,255,.5);
        }

        .carte-ligne {
            display: flex;
            margin-bottom: 7px;
            font-size: 12.5px;
            color: var(--text-color);
            line-height: 1.4;
        }

        .carte-ligne:last-child { margin-bottom: 0; }

        .carte-ligne .label {
            font-weight: bold;
            min-width: 105px;
            color: var(--label-color);
        }

        .carte-ligne .valeur {
            flex: 1;
            border-bottom: 1px solid rgba(26,58,92,.25);
            padding-left: 6px;
            min-height: 18px;
            font-weight: 500;
        }

        .carte-pied {
            margin-top: auto;
            margin-bottom: 0;
            padding-top: 6px;
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
        }

        .carte-signature {
            text-align: center;
        }

        .carte-signature .ligne {
            width: 140px;
            border-bottom: 1px solid var(--text-color);
            margin-bottom: 4px;
        }

        .carte-signature .texte {
            font-size: 10px;
            color: var(--text-color);
            font-style: italic;
        }

        .carte-cachet {
            width: 55px;
            height: 55px;
            border: 2px dashed rgba(26,58,92,.3);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 9px;
            color: rgba(26,58,92,.35);
            text-align: center;
            line-height: 1.2;
        }

        .carte-imported-badge {
            position: absolute;
            top: 6px;
            left: 6px;
            background: #10B981;
            color: white;
            padding: 2px 8px;
            border-radius: 10px;
            font-size: 10px;
            font-weight: 600;
            z-index: 5;
            font-family: Arial, sans-serif;
        }

        @page {
            size: <?= $cs_card_w_mm ?>mm <?= $cs_card_h_mm ?>mm;
            margin: 0;
        }

        @media print {
            .no-print { display: none !important; }
            .main-content { margin: 0 !important; padding: 0 !important; }
            .dashboard { display: block; }
            body { margin: 0; padding: 0; background: white; }

            .idcard-grid {
                display: block;
                margin: 0;
                padding: 0;
            }

            .card-page {
                width: <?= $cs_card_w ?>px;
                height: <?= $cs_card_h ?>px;
                margin: 0;
                padding: 0;
                border: none;
                border-radius: 0;
                box-shadow: none;
                overflow: hidden;
                break-after: page;
                page-break-after: always;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }

            .card-page:last-child {
                break-after: auto;
                page-break-after: auto;
            }

            .carte {
                width: 100%;
                height: 100%;
                margin: 0;
                border-radius: 0;
                box-shadow: none;
                border: none;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }

            .carte::before { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .carte-drapeau { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .carte-photo-initial { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .carte-infos { backdrop-filter: none; -webkit-backdrop-filter: none; }
        }

        #panelCustom.active { display: block !important; }
    </style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-id-card"></i> Cartes d\'identité'; include '../includes/topbar.php'; ?>
        <?= showFlash() ?>

        <!-- Formulaire de sélection -->
        <div class="card no-print">
            <div class="card-header"><span class="card-title"><i class="fas fa-filter"></i> Sélection</span></div>
            <form method="GET" style="display:flex;gap:.75rem;flex-wrap:wrap;align-items:end;">
                <div class="form-group" style="margin:0;flex:0 0 140px;">
                    <label>Type</label>
                    <select name="type" onchange="this.form.submit()">
                        <option value="students" <?= $type==='students'?'selected':'' ?>>Élèves</option>
                        <option value="teachers" <?= $type==='teachers'?'selected':'' ?>>Enseignants</option>
                    </select>
                </div>
                <?php if (isSuperAdmin()): ?>
                <div class="form-group" style="margin:0;flex:0 0 200px;">
                    <label>École</label>
                    <select name="school_id" onchange="this.form.submit()">
                        <option value="">Toutes</option>
                        <?php foreach ($schools as $sc): ?>
                        <option value="<?= $sc['id'] ?>" <?= $schoolFilter==$sc['id']?'selected':'' ?>><?= e($sc['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <?php if ($type === 'students'): ?>
                <div class="form-group" style="margin:0;flex:0 0 180px;">
                    <label>Classe</label>
                    <select name="class_id" onchange="this.form.submit()">
                        <option value="">Toutes les classes</option>
                        <?php foreach ($classes as $cl): ?>
                        <option value="<?= $cl['id'] ?>" <?= $classId==$cl['id']?'selected':'' ?>><?= e($cl['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <div class="form-group" style="margin:0;flex:0 0 120px;">
                    <label>Année</label>
                    <select name="academic_year" onchange="this.form.submit()">
                        <?php foreach ($academicYears as $y): ?>
                        <option value="<?= e($y) ?>" <?= $y===$currentYear?'selected':'' ?>><?= e($y) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <button type="submit" class="btn-action btn-view"><i class="fas fa-search"></i> Afficher</button>
                <div style="margin-left:auto;">
                    <a href="#" onclick="document.getElementById('panelCustom').classList.toggle('active');return false;" style="font-size:.78rem;color:#667eea;text-decoration:none;"><i class="fas fa-palette"></i> Personnaliser</a>
                </div>
            </form>
            <div id="panelCustom" style="display:none;margin-top:1rem;padding-top:1rem;border-top:1px solid #e2e8f0;">
                <form method="GET" style="display:flex;gap:1rem;flex-wrap:wrap;align-items:end;">
                    <?php foreach (['type','school_id','class_id','academic_year'] as $h): ?>
                    <?php if (isset($_GET[$h])): ?><input type="hidden" name="<?= $h ?>" value="<?= e($_GET[$h]) ?>"><?php endif; ?>
                    <?php endforeach; ?>
                    <div class="form-group" style="margin:0;flex:0 0 140px;">
                        <label>Couleur fond 1</label>
                        <input type="color" name="bg1" value="<?= e($cs_bg1) ?>" onchange="this.form.submit()">
                    </div>
                    <div class="form-group" style="margin:0;flex:0 0 140px;">
                        <label>Couleur fond 2</label>
                        <input type="color" name="bg2" value="<?= e($cs_bg2) ?>" onchange="this.form.submit()">
                    </div>
                    <div class="form-group" style="margin:0;flex:0 0 140px;">
                        <label>Titre / Texte</label>
                        <input type="color" name="title_color" value="<?= e($cs_title_color) ?>" onchange="this.form.submit()">
                    </div>
                    <div class="form-group" style="margin:0;flex:0 0 140px;">
                        <label>Étiquettes</label>
                        <input type="color" name="label_color" value="<?= e($cs_label_color) ?>" onchange="this.form.submit()">
                    </div>
                    <div class="form-group" style="margin:0;flex:0 0 60px;">
                        <label><input type="hidden" name="show_flag" value="0"><input type="checkbox" name="show_flag" value="1" <?= $cs_show_flag ? 'checked' : '' ?> onchange="this.form.submit()"> Drapeau</label>
                    </div>
                    <div class="form-group" style="margin:0;flex:0 0 60px;">
                        <label><input type="hidden" name="show_logo" value="0"><input type="checkbox" name="show_logo" value="1" <?= $cs_show_logo ? 'checked' : '' ?> onchange="this.form.submit()"> Logo</label>
                    </div>
                    <button type="submit" class="btn-action btn-view" style="font-size:.75rem;">Appliquer</button>
                </form>
                <?php if ($schoolFilter && hasRole(['super_admin','school_admin'])): ?>
                <div style="display:flex;gap:.5rem;margin-top:.6rem;">
                    <a href="?<?= http_build_query(array_merge($_GET,['save_settings'=>1,'csrf_token'=>$_SESSION['csrf_token']])) ?>" class="btn-action btn-success" style="font-size:.75rem;"><i class="fas fa-save"></i> Enregistrer</a>
                    <a href="?<?= http_build_query(array_merge($_GET,['reset_settings'=>1,'csrf_token'=>$_SESSION['csrf_token']])) ?>" class="btn-action btn-danger" style="font-size:.75rem;" onclick="return confirm('Réinitialiser tous les réglages ?')"><i class="fas fa-undo"></i> Réinitialiser</a>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <script>
        <?php
        $showPanel = isset($_GET['bg1']) || isset($_GET['bg2']) || isset($_GET['title_color']) || isset($_GET['label_color']) || isset($_GET['show_flag']) || isset($_GET['show_logo']);
        ?>
        <?php if ($showPanel): ?>
        document.getElementById('panelCustom').style.display = 'block';
        <?php endif; ?>
        </script>

        <!-- Résultats -->
        <?php if (!empty($cards)): ?>
        <div class="card no-print" style="margin-top:1rem;">
            <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:.5rem;">
                <span><strong><?= count($cards) ?></strong> carte(s) trouvée(s)</span>
                <button onclick="window.print()" class="btn-submit"><i class="fas fa-print"></i> Imprimer</button>
            </div>
        </div>

        <div class="idcard-grid">
            <?php foreach ($cards as $card):
                $genderLabel = $type === 'students'
                    ? (($card['gender'] ?? '') === 'F' ? 'F' : (($card['gender'] ?? '') === 'M' ? 'M' : '-'))
                    : (($card['gender'] ?? '') === 'F' ? 'Mme' : (($card['gender'] ?? '') === 'M' ? 'M.' : '-'));
                $photo = $card['photo'] ?? null;
                $hasPhoto = $photo && file_exists(__DIR__ . '/../uploads/users/' . $photo);
                $birthDate = !empty($card['birth_date']) ? date('d/m/Y', strtotime($card['birth_date'])) : '—';
                $lieuNaissance = $card['birth_place'] ?? '—';
                $matiereText = $type === 'teachers' ? ($card['subject'] ?? '-') : '';
                $phoneText = $type === 'teachers' ? ($card['phone'] ?? '-') : '';
                $emailText = $type === 'teachers' ? ($card['email'] ?? '-') : '';
            ?>
            <div class="card-page">
            <div class="carte">
                <div class="carte-contenu">
                    <?php if ($cs_show_flag): ?>
                    <div class="carte-drapeau">
                        <div class="bande verte"></div>
                        <div class="bande jaune"></div>
                        <div class="bande verte"></div>
                        <div class="bande jaune"></div>
                        <div class="bande verte"></div>
                        <div class="canton"><div class="etoile"></div></div>
                    </div>
                    <?php endif; ?>

                    <?php if ($card['has_imported']): ?>
                    <div class="carte-imported-badge"><i class="fas fa-check-circle"></i> Importée</div>
                    <?php endif; ?>

                    <!-- Titre + Logo école -->
                    <div class="carte-en-tete" style="display:flex;align-items:center;justify-content:center;gap:10px;">
                        <?php if ($cs_show_logo && !empty($card['school_logo'])): $logo = logoUrl($card['school_logo']); if ($logo): ?>
                        <img src="<?= $logo ?>" alt="" style="max-height:38px;border-radius:4px;background:white;padding:2px;">
                        <?php endif; endif; ?>
                        <h1 style="font-size:19px;">Carte d'Identité Scolaire</h1>
                    </div>
                    <div style="text-align:center;margin-top:-4px;margin-bottom:4px;font-size:11px;font-weight:bold;color:var(--title-color);">
                        <?= e(mb_strimwidth($card['school_name'], 0, 50, '…')) ?>
                    </div>

                    <!-- Corps -->
                    <div class="carte-corps">
                        <!-- Photo -->
                        <?php if ($hasPhoto): ?>
                        <div class="carte-photo">
                            <img src="<?= BASE_URL ?>uploads/users/<?= rawurlencode($photo) ?>" alt="">
                        </div>
                        <?php else: ?>
                        <div class="carte-photo-initial">
                            <?= strtoupper(mb_substr($card['first_name'], 0, 1)) . strtoupper(mb_substr($card['last_name'], 0, 1)) ?>
                        </div>
                        <?php endif; ?>

                        <!-- Infos -->
                        <div class="carte-infos">
                            <div class="carte-ligne">
                                <span class="label">Nom :</span>
                                <span class="valeur"><?= e(strtoupper($card['last_name'])) ?></span>
                            </div>
                            <div class="carte-ligne">
                                <span class="label">Prénom(s) :</span>
                                <span class="valeur"><?= e($card['first_name']) ?></span>
                            </div>
                            <div class="carte-ligne">
                                <span class="label">Sexe :</span>
                                <span class="valeur"><?= $genderLabel ?></span>
                            </div>
                            <?php if ($type === 'students'): ?>
                            <div class="carte-ligne">
                                <span class="label">Né(e) le :</span>
                                <span class="valeur"><?= $birthDate ?></span>
                            </div>
                            <div class="carte-ligne">
                                <span class="label">Classe :</span>
                                <span class="valeur"><?= e($card['class_name'] ?? '—') ?></span>
                            </div>
                            <?php else: ?>
                            <div class="carte-ligne">
                                <span class="label">Matière :</span>
                                <span class="valeur"><?= e($matiereText) ?></span>
                            </div>
                            <div class="carte-ligne">
                                <span class="label">Tél :</span>
                                <span class="valeur"><?= e($phoneText) ?></span>
                            </div>
                            <?php endif; ?>
                            <div class="carte-ligne">
                                <span class="label">Matricule :</span>
                                <span class="valeur"><?= $card['card_id'] ?></span>
                            </div>
                            <div class="carte-ligne">
                                <span class="label">Année scol. :</span>
                                <span class="valeur"><?= e($card['academic_year']) ?></span>
                            </div>
                        </div>
                    </div>

                    <!-- Pied -->
                    <div class="carte-pied">
                        <div class="carte-signature">
                            <div class="ligne"></div>
                            <div class="texte">Signature du Chef d'Établissement</div>
                        </div>
                        <div class="carte-cachet">Cachet de<br>l'École</div>
                    </div>
                </div>
            </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php elseif ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['type'])): ?>
        <div class="card" style="margin-top:1rem;text-align:center;padding:3rem;color:#999;">
            <i class="fas fa-id-card" style="font-size:3rem;margin-bottom:1rem;"></i><br>
            Aucun résultat pour cette sélection.
        </div>
        <?php else: ?>
        <div class="card" style="margin-top:1rem;text-align:center;padding:3rem;color:#999;">
            <i class="fas fa-id-card" style="font-size:3rem;margin-bottom:1rem;"></i><br>
            Sélectionnez un type et une classe pour générer les cartes.
        </div>
        <?php endif; ?>
    </div>
</div>
</body>
</html>
