<?php
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']);

$schoolFilter = currentSchoolId();
$error = $success = '';

$action = $_POST['action'] ?? $_GET['action'] ?? 'list';
$id     = isset($_GET['id']) ? (int)$_GET['id'] : (isset($_POST['id']) ? (int)$_POST['id'] : 0);

// ── Suppression ─────────────────────────────────────────────────────────────
if ($action === 'delete' && $id) {
    verifyCsrf();
    $stmt = $pdo->prepare("SELECT filename FROM imported_idcards WHERE id=?");
    $stmt->execute([$id]);
    $row = $stmt->fetch();
    if ($row) {
        $filepath = __DIR__ . '/../uploads/idcards/' . $row['filename'];
        if (file_exists($filepath)) unlink($filepath);
        $pdo->prepare("DELETE FROM imported_idcards WHERE id=?")->execute([$id]);
        flashMessage('success', 'Carte supprimée.');
    }
    header('Location: import_idcards.php'); exit;
}

// ── Upload ─────────────────────────────────────────────────────────────────
if ($action === 'upload' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    if (empty($_FILES['files']['name'][0])) {
        flashMessage('error', 'Aucun fichier sélectionné.');
        header('Location: import_idcards.php'); exit;
    }

    $allowed = ['application/pdf', 'application/x-pdf'];
    $maxSize = 10 * 1024 * 1024;
    $uploadDir = __DIR__ . '/../uploads/idcards/';
    $imported = 0; $errors = [];

    $files = $_FILES['files'];
    $count = count($files['name']);

    for ($i = 0; $i < $count; $i++) {
        if ($files['error'][$i] !== UPLOAD_ERR_OK) continue;

        $ext = strtolower(pathinfo($files['name'][$i], PATHINFO_EXTENSION));
        if ($ext !== 'pdf') { $errors[] = $files['name'][$i] . ' : format non supporté (PDF requis)'; continue; }
        if ($files['size'][$i] > $maxSize) { $errors[] = $files['name'][$i] . ' : dépasse 10 MB'; continue; }

        $originalName = preg_replace('/[^a-zA-Z0-9._\-\s\(\)]/u', '', $files['name'][$i]);
        $safeName = uniqid('idc_', true) . '.pdf';
        $destPath = $uploadDir . $safeName;

        if (move_uploaded_file($files['tmp_name'][$i], $destPath)) {
            $personName = pathinfo($originalName, PATHINFO_FILENAME);
            $personName = str_replace(['_', '-'], ' ', $personName);

            $pdo->prepare("INSERT INTO imported_idcards (school_id, filename, original_name, file_size, person_name, status, uploaded_by, created_at) VALUES (?,?,?,?,?,'en_attente',?,NOW())")
                ->execute([$schoolFilter ?? 0, $safeName, $originalName, $files['size'][$i], $personName, $_SESSION['user_id'] ?? null]);
            $imported++;
        } else {
            $errors[] = $files['name'][$i] . ' : erreur lors de l\'enregistrement';
        }
    }

    $msg = "$imported carte(s) importée(s) avec succès.";
    if (!empty($errors)) $msg .= ' Erreurs : ' . implode(', ', $errors);
    flashMessage($imported > 0 ? 'success' : 'error', $msg);
    header('Location: import_idcards.php'); exit;
}

// ── Mise à jour (associer élève/enseignant/classe) ───────────────────────────
if ($action === 'update' && $id && $_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $person_id    = (int)($_POST['person_id'] ?? 0);
    $type         = $_POST['type'] ?? 'student';
    $class_id     = (int)($_POST['class_id'] ?? 0);
    $academic_year = trim($_POST['academic_year'] ?? '');
    $status       = $_POST['status'] ?? 'en_attente';

    if (!in_array($type, ['student','teacher'])) $type = 'student';
    if (!in_array($status, ['en_attente','valide','rejete'])) $status = 'en_attente';

    $className = '';
    $personName = '';
    if ($class_id) {
        $cs = $pdo->prepare("SELECT name FROM classes WHERE id=?");
        $cs->execute([$class_id]);
        $cr = $cs->fetch();
        $className = $cr ? $cr['name'] : '';
    }
    if ($person_id && $type === 'student') {
        $ss = $pdo->prepare("SELECT CONCAT(last_name,' ',first_name) AS name FROM students WHERE id=?");
        $ss->execute([$person_id]);
        $sr = $ss->fetch();
        $personName = $sr ? $sr['name'] : '';
    } elseif ($person_id && $type === 'teacher') {
        $ss = $pdo->prepare("SELECT CONCAT(last_name,' ',first_name) AS name FROM teachers WHERE id=?");
        $ss->execute([$person_id]);
        $sr = $ss->fetch();
        $personName = $sr ? $sr['name'] : '';
    }

    $pdo->prepare("UPDATE imported_idcards SET person_id=?, type=?, person_name=?, class_name=?, academic_year=?, status=?, updated_at=NOW() WHERE id=?")
        ->execute([$person_id ?: null, $type, $personName ?: null, $className ?: null, $academic_year ?: null, $status, $id]);
    flashMessage('success', 'Carte mise à jour.');
    header('Location: import_idcards.php'); exit;
}

// ── Téléchargement PDF ──────────────────────────────────────────────────────
if ($action === 'download' && $id) {
    $stmt = $pdo->prepare("SELECT filename, original_name FROM imported_idcards WHERE id=?");
    $stmt->execute([$id]);
    $row = $stmt->fetch();
    if ($row) {
        $filepath = __DIR__ . '/../uploads/idcards/' . $row['filename'];
        if (file_exists($filepath)) {
            header('Content-Type: application/pdf');
            header('Content-Disposition: attachment; filename="' . $row['original_name'] . '"');
            header('Content-Length: ' . filesize($filepath));
            readfile($filepath);
            exit;
        }
    }
    flashMessage('error', 'Fichier introuvable.');
    header('Location: import_idcards.php'); exit;
}

// ── Consultation (inline) ───────────────────────────────────────────────────
if ($action === 'view' && $id) {
    $stmt = $pdo->prepare("SELECT filename, original_name FROM imported_idcards WHERE id=?");
    $stmt->execute([$id]);
    $row = $stmt->fetch();
    if ($row) {
        $filepath = __DIR__ . '/../uploads/idcards/' . $row['filename'];
        if (file_exists($filepath)) {
            header('Content-Type: application/pdf');
            header('Content-Disposition: inline; filename="' . $row['original_name'] . '"');
            readfile($filepath);
            exit;
        }
    }
    flashMessage('error', 'Fichier introuvable.');
    header('Location: import_idcards.php'); exit;
}

// ── Filtres ─────────────────────────────────────────────────────────────────
$filterType   = $_GET['filter_type'] ?? '';
$filterClasse = $_GET['filter_classe'] ?? '';
$filterYear   = $_GET['filter_year'] ?? '';
$filterSearch = $_GET['filter_search'] ?? '';

$conditions = [];
$params = [];

if ($schoolFilter) {
    $conditions[] = 'ic.school_id=?';
    $params[] = $schoolFilter;
}
if ($filterType !== '') {
    $conditions[] = 'ic.type=?';
    $params[] = $filterType;
}
if ($filterClasse !== '') {
    $conditions[] = 'ic.class_name LIKE ?';
    $params[] = '%' . $filterClasse . '%';
}
if ($filterYear !== '') {
    $conditions[] = 'ic.academic_year=?';
    $params[] = $filterYear;
}
if ($filterSearch !== '') {
    $conditions[] = '(ic.person_name LIKE ? OR ic.original_name LIKE ?)';
    $params[] = '%' . $filterSearch . '%';
    $params[] = '%' . $filterSearch . '%';
}

$where = $conditions ? 'WHERE ' . implode(' AND ', $conditions) : '';

// ── Pagination ──────────────────────────────────────────────────────────────
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 12;
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM imported_idcards ic $where");
$countStmt->execute($params);
$totalItems = (int)$countStmt->fetchColumn();
$totalPages = max(1, ceil($totalItems / $perPage));
$offset = ($page - 1) * $perPage;

$sort = resolveSort(['person_name','type','academic_year','file_size','created_at'], 'created_at', 'desc');
$sortMap = [
    'person_name'   => 'ic.person_name',
    'type'          => 'ic.type',
    'academic_year' => 'ic.academic_year',
    'file_size'     => 'ic.file_size',
    'created_at'    => 'ic.created_at',
];
$orderExpr = ($sortMap[$sort['col']] ?? 'ic.created_at') . ' ' . $sort['dir'];

$dataStmt = $pdo->prepare("
    SELECT ic.*
    FROM imported_idcards ic
    $where
    ORDER BY $orderExpr
    LIMIT $perPage OFFSET $offset
");
$dataStmt->execute($params);
$cardsList = $dataStmt->fetchAll();
if (!is_array($cardsList)) $cardsList = [];

// ── Données pour les filtres ───────────────────────────────────────────────
$classes = $pdo->query("SELECT id,name FROM classes c ORDER BY " . getClassSortSQL('c'))->fetchAll();

$years = $pdo->prepare("SELECT DISTINCT academic_year FROM imported_idcards WHERE school_id=? AND academic_year IS NOT NULL AND academic_year!='' ORDER BY academic_year DESC");
$years->execute([$schoolFilter ?? 0]);
$years = $years->fetchAll(PDO::FETCH_COLUMN);

$currentYear = getDefaultAcademicYear($pdo, $schoolFilter);

// ── Stats ──────────────────────────────────────────────────────────────────
$statsStmt = $pdo->prepare("
    SELECT
        COUNT(*) AS total,
        SUM(CASE WHEN status='valide' THEN 1 ELSE 0 END) AS valides,
        SUM(CASE WHEN status='en_attente' THEN 1 ELSE 0 END) AS en_attente,
        COALESCE(SUM(file_size),0) AS total_size
    FROM imported_idcards WHERE school_id=?
");
$statsStmt->execute([$schoolFilter ?? 0]);
$stats = $statsStmt->fetch();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Import de 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{--primary:#1F4E79;--accent:#2E75B6;--light:#D6E4F0;--bg:#F1F5F9;--white:#FFFFFF;--text:#1E293B;--success:#10B981;--warning:#F59E0B;--danger:#EF4444;--info:#3B82F6;}
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;background:var(--bg);color:var(--text);line-height:1.6;}
.main-content{padding-top:0;}
.content{padding:30px;}
.section{background:var(--white);border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,0.06);padding:24px 30px;margin-bottom:25px;}
.section-title{font-family:Georgia,serif;color:var(--primary);font-size:1.2rem;margin-bottom:20px;padding-bottom:10px;border-bottom:2px solid var(--light);display:flex;align-items:center;gap:10px;}

/* Upload zone */
.upload-zone{border:2px dashed var(--accent);border-radius:12px;padding:40px 30px;text-align:center;background:linear-gradient(180deg,#f8fbff 0%,#eef4fc 100%);transition:all .3s ease;cursor:pointer;position:relative;}
.upload-zone:hover{border-color:var(--primary);background:linear-gradient(180deg,#f0f7ff 0%,#e4eef8 100%);}
.upload-zone.dragover{border-color:var(--success);background:linear-gradient(180deg,#e8f5e9 0%,#dcedc8 100%);}
.upload-zone .icon{font-size:3rem;margin-bottom:12px;display:block;color:var(--primary);}
.upload-zone h3{color:var(--primary);font-size:1.1rem;margin-bottom:6px;}
.upload-zone p{color:#6B7280;font-size:.9rem;margin-bottom:16px;}
.upload-zone .btn-upload{display:inline-block;padding:10px 24px;background:var(--primary);color:white;border:none;border-radius:6px;font-size:.9rem;font-weight:600;cursor:pointer;transition:all .2s;}
.upload-zone .btn-upload:hover{background:var(--accent);transform:translateY(-1px);box-shadow:0 4px 12px rgba(31,78,121,0.25);}
.upload-zone input[type="file"]{position:absolute;left:0;top:0;width:100%;height:100%;opacity:0;cursor:pointer;}
.upload-formats{display:flex;justify-content:center;gap:12px;margin-top:12px;flex-wrap:wrap;}
.format-tag{display:flex;align-items:center;gap:6px;padding:5px 12px;background:white;border-radius:20px;font-size:.82rem;color:#6B7280;border:1px solid #E5E7EB;}
.format-tag .dot{width:8px;height:8px;border-radius:50%;background:var(--danger);}

/* Stats bar */
.stats-bar{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:16px;margin-bottom:25px;}
.stat-card{background:white;border-radius:10px;padding:20px;box-shadow:0 2px 12px rgba(0,0,0,0.06);display:flex;align-items:center;gap:14px;transition:transform .2s;}
.stat-card:hover{transform:translateY(-2px);}
.stat-icon{width:48px;height:48px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:1.4rem;flex-shrink:0;}
.stat-icon.blue{background:#E3F2FD;color:var(--info);}
.stat-icon.green{background:#E8F5E9;color:var(--success);}
.stat-icon.orange{background:#FFF3E0;color:var(--warning);}
.stat-icon.purple{background:#F3E5F5;color:#7B1FA2;}
.stat-info h4{font-size:1.5rem;color:var(--primary);margin-bottom:2px;}
.stat-info p{font-size:.82rem;color:#6B7280;}

/* Filter bar */
.filter-bar{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:18px;align-items:center;}
.filter-bar select,.filter-bar input{padding:9px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:.85rem;background:white;color:var(--text);}
.filter-bar select{min-width:140px;cursor:pointer;}
.filter-bar input{min-width:180px;}
.btn-filter{padding:9px 18px;border:none;border-radius:6px;font-size:.85rem;font-weight:600;cursor:pointer;transition:all .2s;}
.btn-filter-primary{background:var(--primary);color:white;}
.btn-filter-primary:hover{background:var(--accent);}
.btn-filter-reset{background:#E5E7EB;color:#374151;}
.btn-filter-reset:hover{background:#D1D5DB;}

/* Table */
.card-table{width:100%;border-collapse:collapse;margin-top:8px;}
.card-table th,.card-table td{padding:12px 14px;text-align:left;border-bottom:1px solid #E5E7EB;}
.card-table th{background:var(--primary);color:white;font-weight:600;font-size:.85rem;position:sticky;top:0;}
.card-table tr:nth-child(even){background:#F9FAFB;}
.card-table tr:hover{background:#F0F7FF;}
.card-table td{font-size:.85rem;color:#374151;}
.cell-name{font-weight:600;color:var(--primary);}
.cell-type{display:inline-block;padding:3px 10px;border-radius:20px;font-size:.78rem;font-weight:600;}
.cell-type-student{background:#E3F2FD;color:var(--info);}
.cell-type-teacher{background:#E8F5E9;color:var(--success);}
.cell-annee{color:#6B7280;font-size:.82rem;}
.cell-date{color:#9CA3AF;font-size:.82rem;}
.cell-size{color:#6B7280;font-size:.82rem;}
.cell-status{display:inline-block;padding:3px 10px;border-radius:20px;font-size:.75rem;font-weight:600;}
.status-valide{background:#E8F5E9;color:var(--success);}
.status-attente{background:#FFF3E0;color:var(--warning);}
.status-rejete{background:#FEE2E2;color:var(--danger);}
.cell-actions{display:flex;gap:6px;flex-wrap:wrap;}
.btn-action{padding:5px 10px;border:none;border-radius:5px;font-size:.78rem;cursor:pointer;display:inline-flex;align-items:center;gap:4px;transition:all .2s;text-decoration:none;}
.btn-view{background:#E3F2FD;color:var(--info);}
.btn-view:hover{background:#BBDEFB;}
.btn-download{background:#E8F5E9;color:var(--success);}
.btn-download:hover{background:#C8E6C9;}
.btn-edit-action{background:#FFF3E0;color:var(--warning);}
.btn-edit-action:hover{background:#FFE0B2;}
.btn-delete{background:#FEE2E2;color:var(--danger);}
.btn-delete:hover{background:#FECACA;}

/* Pagination */
.pagination{display:flex;justify-content:center;align-items:center;gap:6px;margin-top:20px;}
.pagination a,.pagination span{padding:7px 12px;border:1px solid #D1D5DB;background:white;border-radius:6px;font-size:.82rem;color:var(--primary);text-decoration:none;transition:all .2s;}
.pagination a:hover{background:var(--light);}
.pagination .active{background:var(--primary);color:white;border-color:var(--primary);}
.pagination .disabled{opacity:.4;pointer-events:none;}

/* Modal */
.modal-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:1500;align-items:center;justify-content:center;}
.modal-overlay.active{display:flex;}
.modal{background:white;border-radius:12px;width:90%;max-width:500px;padding:28px;box-shadow:0 8px 32px rgba(0,0,0,.2);animation:modalSlide .3s ease;max-height:90vh;overflow-y:auto;}
@keyframes modalSlide{from{transform:translateY(-30px);opacity:0;}to{transform:translateY(0);opacity:1;}}
.modal h3{color:var(--primary);font-size:1.1rem;margin-bottom:16px;display:flex;align-items:center;gap:8px;}
.modal .form-group{margin-bottom:14px;}
.modal .form-group label{display:block;font-weight:600;color:var(--primary);font-size:.82rem;margin-bottom:4px;}
.modal .form-group select,.modal .form-group input{padding:9px 12px;border:1px solid #D1D5DB;border-radius:6px;font-size:.85rem;width:100%;}
.modal-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:20px;}
.modal-actions button{padding:9px 20px;border-radius:6px;border:none;font-size:.85rem;cursor:pointer;transition:all .2s;}
.btn-cancel{background:#E5E7EB;color:#374151;}
.btn-cancel:hover{background:#D1D5DB;}
.btn-save{background:var(--primary);color:white;}
.btn-save:hover{background:var(--accent);}
.btn-confirm-del{background:var(--danger);color:white;}
.btn-confirm-del:hover{background:#DC2626;}

/* Empty state */
.empty-state{text-align:center;padding:50px 20px;}
.empty-state .icon{font-size:3.5rem;margin-bottom:12px;color:#CBD5E1;}
.empty-state h3{color:var(--primary);margin-bottom:6px;}
.empty-state p{color:#9CA3AF;font-size:.9rem;}

/* Toast */
.toast-container{position:fixed;top:20px;right:20px;z-index:2000;display:flex;flex-direction:column;gap:8px;}
.toast{padding:12px 18px;border-radius:8px;color:white;font-size:.88rem;display:flex;align-items:center;gap:10px;box-shadow:0 4px 16px rgba(0,0,0,.15);transform:translateX(120%);transition:transform .4s ease;min-width:260px;}
.toast.show{transform:translateX(0);}
.toast.success{background:var(--success);}
.toast.error{background:var(--danger);}
.toast.info{background:var(--info);}
.toast.warning{background:var(--warning);}

/* Upload progress */
.upload-progress{display:none;margin-top:16px;}
.upload-progress.active{display:block;}
.progress-bar{height:6px;background:#E5E7EB;border-radius:3px;overflow:hidden;}
.progress-fill{height:100%;background:linear-gradient(90deg,var(--primary),var(--accent));border-radius:3px;transition:width .3s ease;width:0%;}
.progress-text{text-align:center;margin-top:6px;font-size:.82rem;color:#6B7280;}
.file-list{margin-top:14px;display:none;}
.file-list.active{display:block;}
.file-item{display:flex;align-items:center;gap:10px;padding:10px 14px;background:#F9FAFB;border-radius:8px;margin-bottom:6px;}
.file-item .file-icon{font-size:1.3rem;}
.file-item .file-info{flex:1;}
.file-item .file-name{font-weight:600;color:var(--primary);font-size:.85rem;}
.file-item .file-status{padding:3px 10px;border-radius:20px;font-size:.72rem;font-weight:600;}
.file-status.pending{background:#FFF3E0;color:var(--warning);}
.file-status.success{background:#E8F5E9;color:var(--success);}
.file-status.error{background:#FEE2E2;color:var(--danger);}
.sort-link{color:inherit;text-decoration:none;display:inline-flex;align-items:center;gap:4px;}
.sort-link:hover{color:#DBEAFE;}

@media(max-width:768px){
.content{padding:16px;}
.stats-bar{grid-template-columns:repeat(2,1fr);}
.filter-bar{flex-direction:column;align-items:stretch;}
.filter-bar select,.filter-bar input{width:100%;}
.card-table{font-size:.78rem;}
.card-table th,.card-table td{padding:8px 6px;}
.cell-actions{flex-direction:column;}
}
@media(max-width:480px){
.stats-bar{grid-template-columns:1fr;}
}
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-file-upload"></i> Import de cartes d\'identité'; include '../includes/topbar.php'; ?>
        <?= showFlash() ?>

        <div class="content">

        <!-- ═══ STATS BAR ═══ -->
        <div class="stats-bar">
            <div class="stat-card">
                <div class="stat-icon blue"><i class="fas fa-id-card"></i></div>
                <div class="stat-info">
                    <h4><?= (int)$stats['total'] ?></h4>
                    <p>Cartes importées</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon green"><i class="fas fa-check-circle"></i></div>
                <div class="stat-info">
                    <h4><?= (int)$stats['valides'] ?></h4>
                    <p>Cartes validées</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon orange"><i class="fas fa-clock"></i></div>
                <div class="stat-info">
                    <h4><?= (int)$stats['en_attente'] ?></h4>
                    <p>En attente</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon purple"><i class="fas fa-database"></i></div>
                <div class="stat-info">
                    <h4><?= formatFileSize((int)$stats['total_size']) ?></h4>
                    <p>Espace utilisé</p>
                </div>
            </div>
        </div>

        <!-- ═══ SECTION UPLOAD ═══ -->
        <div class="section">
            <div class="section-title"><i class="fas fa-cloud-upload-alt"></i> Importer des cartes PDF</div>
            <form method="POST" enctype="multipart/form-data" id="uploadForm">
                <input type="hidden" name="action" value="upload">
                <?= csrfField() ?>
                <div class="upload-zone" id="uploadZone">
                    <input type="file" name="files[]" multiple accept=".pdf" id="fileInput" onchange="handleFiles(this.files)">
                    <span class="icon"><i class="fas fa-file-pdf"></i></span>
                    <h3>Glissez-déposez vos fichiers PDF ici</h3>
                    <p>ou cliquez pour parcourir vos documents</p>
                    <button type="button" class="btn-upload" onclick="document.getElementById('fileInput').click()">Choisir des fichiers</button>
                    <div class="upload-formats">
                        <span class="format-tag"><span class="dot"></span> PDF uniquement</span>
                        <span class="format-tag">Taille max : 10 MB</span>
                        <span class="format-tag">Multi-fichiers acceptés</span>
                    </div>
                </div>
                <div class="upload-progress" id="uploadProgress">
                    <div class="progress-bar"><div class="progress-fill" id="progressFill"></div></div>
                    <div class="progress-text" id="progressText">Importation en cours... 0%</div>
                </div>
                <div class="file-list" id="fileList"></div>
            </form>
        </div>

        <!-- ═══ SECTION LISTE ═══ -->
        <div class="section">
            <div class="section-title"><i class="fas fa-list"></i> Cartes importées</div>

            <form method="GET" class="filter-bar">
                <select name="filter_type">
                    <option value="">Tous les types</option>
                    <option value="student" <?= $filterType === 'student' ? 'selected' : '' ?>>Élèves</option>
                    <option value="teacher" <?= $filterType === 'teacher' ? 'selected' : '' ?>>Enseignants</option>
                </select>
                <select name="filter_classe">
                    <option value="">Toutes les classes</option>
                    <?php foreach ($classes as $c): ?>
                    <option value="<?= $c['name'] ?>" <?= $filterClasse === $c['name'] ? 'selected' : '' ?>><?= e($c['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="filter_year">
                    <option value="">Toutes les années</option>
                    <?php foreach ($years as $y): ?>
                    <option value="<?= e($y) ?>" <?= $filterYear === $y ? 'selected' : '' ?>><?= e($y) ?></option>
                    <?php endforeach; ?>
                    <option value="<?= e($currentYear) ?>" <?= $filterYear === $currentYear ? 'selected' : '' ?>><?= e($currentYear) ?></option>
                </select>
                <input type="text" name="filter_search" placeholder="Rechercher un élève..." value="<?= e($filterSearch) ?>">
                <button type="submit" class="btn-filter btn-filter-primary"><i class="fas fa-filter"></i> Filtrer</button>
                <a href="import_idcards.php" class="btn-filter btn-filter-reset"><i class="fas fa-undo"></i> Réinitialiser</a>
            </form>

            <?php if (empty($cardsList)): ?>
            <div class="empty-state">
                <div class="icon"><i class="fas fa-inbox"></i></div>
                <h3>Aucune carte trouvée</h3>
                <p>Importez des cartes PDF ou modifiez vos critères de recherche.</p>
            </div>
            <?php else: ?>
            <div style="overflow-x:auto;">
            <table class="card-table">
                <thead>
                    <tr>
                        <th><a href="<?= sortUrl('person_name', $sort) ?>" class="sort-link"><i class="fas fa-user"></i> Personne <?= sortIcon('person_name', $sort) ?></a></th>
                        <th><a href="<?= sortUrl('type', $sort) ?>" class="sort-link"><i class="fas fa-tag"></i> Type <?= sortIcon('type', $sort) ?></a></th>
                        <th>Classe</th>
                        <th><a href="<?= sortUrl('academic_year', $sort) ?>" class="sort-link"><i class="fas fa-calendar"></i> Année <?= sortIcon('academic_year', $sort) ?></a></th>
                        <th><a href="<?= sortUrl('file_size', $sort) ?>" class="sort-link"><i class="fas fa-weight"></i> Taille <?= sortIcon('file_size', $sort) ?></a></th>
                        <th>Statut</th>
                        <th><a href="<?= sortUrl('created_at', $sort) ?>" class="sort-link"><i class="fas fa-clock"></i> Import <?= sortIcon('created_at', $sort) ?></a></th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($cardsList as $c): ?>
                    <tr>
                        <td class="cell-name">
                            <?= e($c['person_name'] ?: pathinfo($c['original_name'], PATHINFO_FILENAME)) ?>
                            <?php if (!$c['person_id']): ?><small style="color:#F59E0B;font-size:.7rem;"> (non associé)</small><?php endif; ?>
                        </td>
                        <td><span class="cell-type cell-type-<?= $c['type'] ?>"><?= $c['type'] === 'student' ? 'Élève' : 'Enseignant' ?></span></td>
                        <td><?= $c['class_name'] ? '<span class="cell-classe" style="display:inline-block;padding:3px 10px;background:var(--light);color:var(--primary);border-radius:20px;font-size:.78rem;font-weight:600;">' . e($c['class_name']) . '</span>' : '<span style="color:#9CA3AF;font-size:.78rem;">—</span>' ?></td>
                        <td class="cell-annee"><?= e($c['academic_year'] ?: '—') ?></td>
                        <td class="cell-size"><?= formatFileSize((int)$c['file_size']) ?></td>
                        <td><span class="cell-status status-<?= $c['status'] === 'valide' ? 'valide' : ($c['status'] === 'rejete' ? 'rejete' : 'attente') ?>"><?= $c['status'] === 'valide' ? 'Validé' : ($c['status'] === 'rejete' ? 'Rejeté' : 'En attente') ?></span></td>
                        <td class="cell-date"><?= formatDate($c['created_at']) ?></td>
                        <td class="cell-actions">
                            <a href="?action=view&id=<?= $c['id'] ?>" target="_blank" class="btn-action btn-view" title="Voir"><i class="fas fa-eye"></i></a>
                            <a href="?action=download&id=<?= $c['id'] ?>" class="btn-action btn-download" title="Télécharger"><i class="fas fa-download"></i></a>
                            <button onclick="openEditModal(<?= $c['id'] ?>)" class="btn-action btn-edit-action" title="Associer"><i class="fas fa-link"></i></button>
                            <button onclick="openDeleteModal(<?= $c['id'] ?>)" class="btn-action btn-delete" title="Supprimer"><i class="fas fa-trash"></i></button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            </div>

            <?php if ($totalPages > 1): ?>
            <div class="pagination">
                <a href="?page=1<?= $filterType ? '&filter_type='.$filterType : '' ?><?= $filterClasse ? '&filter_classe='.urlencode($filterClasse) : '' ?><?= $filterYear ? '&filter_year='.urlencode($filterYear) : '' ?><?= $filterSearch ? '&filter_search='.urlencode($filterSearch) : '' ?>" class="<?= $page <= 1 ? 'disabled' : '' ?>">«</a>
                <a href="?page=<?= max(1, $page-1) ?><?= $filterType ? '&filter_type='.$filterType : '' ?><?= $filterClasse ? '&filter_classe='.urlencode($filterClasse) : '' ?><?= $filterYear ? '&filter_year='.urlencode($filterYear) : '' ?><?= $filterSearch ? '&filter_search='.urlencode($filterSearch) : '' ?>" class="<?= $page <= 1 ? 'disabled' : '' ?>">&lsaquo;</a>
                <?php for ($i = max(1, $page-2); $i <= min($totalPages, $page+2); $i++): ?>
                <a href="?page=<?= $i ?><?= $filterType ? '&filter_type='.$filterType : '' ?><?= $filterClasse ? '&filter_classe='.urlencode($filterClasse) : '' ?><?= $filterYear ? '&filter_year='.urlencode($filterYear) : '' ?><?= $filterSearch ? '&filter_search='.urlencode($filterSearch) : '' ?>" class="<?= $i === $page ? 'active' : '' ?>"><?= $i ?></a>
                <?php endfor; ?>
                <a href="?page=<?= min($totalPages, $page+1) ?><?= $filterType ? '&filter_type='.$filterType : '' ?><?= $filterClasse ? '&filter_classe='.urlencode($filterClasse) : '' ?><?= $filterYear ? '&filter_year='.urlencode($filterYear) : '' ?><?= $filterSearch ? '&filter_search='.urlencode($filterSearch) : '' ?>" class="<?= $page >= $totalPages ? 'disabled' : '' ?>">&rsaquo;</a>
                <a href="?page=<?= $totalPages ?><?= $filterType ? '&filter_type='.$filterType : '' ?><?= $filterClasse ? '&filter_classe='.urlencode($filterClasse) : '' ?><?= $filterYear ? '&filter_year='.urlencode($filterYear) : '' ?><?= $filterSearch ? '&filter_search='.urlencode($filterSearch) : '' ?>" class="<?= $page >= $totalPages ? 'disabled' : '' ?>">»</a>
            </div>
            <?php endif; ?>
            <?php endif; ?>
        </div>

        </div>
    </div>
</div>

<!-- ═══ MODAL ASSOCIER ═══ -->
<div class="modal-overlay" id="editModal">
    <div class="modal">
        <h3><i class="fas fa-link"></i> Associer la carte</h3>
        <form method="POST" id="editForm">
            <input type="hidden" name="action" value="update">
            <input type="hidden" name="id" id="editId" value="">
            <?= csrfField() ?>
            <div class="form-group">
                <label>Type</label>
                <select name="type" id="editType" onchange="togglePersonField()">
                    <option value="student">Élève</option>
                    <option value="teacher">Enseignant</option>
                </select>
            </div>
            <div class="form-group" id="personGroup">
                <label id="personLabel">Élève</label>
                <select name="person_id" id="editPerson">
                    <option value="">Non spécifié</option>
                    <?php
                    $allStudents = $schoolFilter
                        ? $pdo->prepare("SELECT s.id, CONCAT(s.last_name,' ',s.first_name) AS name FROM students s WHERE s.school_id=? ORDER BY s.last_name, s.first_name")
                        : $pdo->query("SELECT id, CONCAT(last_name,' ',first_name) AS name FROM students ORDER BY last_name, first_name");
                    if ($schoolFilter) $allStudents->execute([$schoolFilter]);
                    foreach ($allStudents as $st):
                    ?>
                    <option value="<?= $st['id'] ?>"><?= e($st['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Classe</label>
                <select name="class_id">
                    <option value="">Non spécifié</option>
                    <?php foreach ($classes as $c): ?>
                    <option value="<?= $c['id'] ?>"><?= e($c['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Année scolaire</label>
                <input type="text" name="academic_year" value="<?= e($currentYear) ?>" placeholder="ex: 2025-2026">
            </div>
            <div class="form-group">
                <label>Statut</label>
                <select name="status">
                    <option value="en_attente">En attente</option>
                    <option value="valide">Validé</option>
                    <option value="rejete">Rejeté</option>
                </select>
            </div>
            <div class="modal-actions">
                <button type="button" class="btn-cancel" onclick="closeEditModal()">Annuler</button>
                <button type="submit" class="btn-save"><i class="fas fa-save"></i> Enregistrer</button>
            </div>
        </form>
    </div>
</div>

<!-- ═══ MODAL SUPPRESSION ═══ -->
<div class="modal-overlay" id="deleteModal">
    <div class="modal">
        <h3><i class="fas fa-trash-alt"></i> Confirmer la suppression</h3>
        <p style="color:#6B7280;font-size:.9rem;margin-bottom:16px;">Êtes-vous sûr de vouloir supprimer cette carte ? Cette action est irréversible.</p>
        <form method="POST" id="deleteForm">
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="id" id="deleteId" value="">
            <?= csrfField() ?>
            <div class="modal-actions">
                <button type="button" class="btn-cancel" onclick="closeDeleteModal()">Annuler</button>
                <button type="submit" class="btn-confirm-del"><i class="fas fa-trash"></i> Supprimer</button>
            </div>
        </form>
    </div>
</div>

<div class="toast-container" id="toastContainer"></div>

<script>
/* ═══ TYPE SWITCH ═══ */
const teachersData = <?php
    $allTeachers = $schoolFilter
        ? $pdo->prepare("SELECT id, CONCAT(last_name,' ',first_name) AS name FROM teachers t WHERE t.school_id=? ORDER BY t.last_name, t.first_name")
        : $pdo->query("SELECT id, CONCAT(last_name,' ',first_name) AS name FROM teachers ORDER BY last_name, first_name");
    if ($schoolFilter) $allTeachers->execute([$schoolFilter]);
    echo json_encode($allTeachers->fetchAll());
?>;
const studentsData = <?php
    $allStudents2 = $schoolFilter
        ? $pdo->prepare("SELECT id, CONCAT(last_name,' ',first_name) AS name FROM students s WHERE s.school_id=? ORDER BY s.last_name, s.first_name")
        : $pdo->query("SELECT id, CONCAT(last_name,' ',first_name) AS name FROM students ORDER BY last_name, first_name");
    if ($schoolFilter) $allStudents2->execute([$schoolFilter]);
    echo json_encode($allStudents2->fetchAll());
?>;

function togglePersonField() {
    const type = document.getElementById('editType').value;
    const select = document.getElementById('editPerson');
    const label = document.getElementById('personLabel');
    select.innerHTML = '<option value="">Non spécifié</option>';
    const data = type === 'teacher' ? teachersData : studentsData;
    label.textContent = type === 'teacher' ? 'Enseignant' : 'Élève';
    data.forEach(p => {
        const opt = document.createElement('option');
        opt.value = p.id;
        opt.textContent = p.name;
        select.appendChild(opt);
    });
}

/* ═══ UPLOAD ═══ */
const uploadZone = document.getElementById('uploadZone');
uploadZone.addEventListener('dragover', e => { e.preventDefault(); uploadZone.classList.add('dragover'); });
uploadZone.addEventListener('dragleave', () => uploadZone.classList.remove('dragover'));
uploadZone.addEventListener('drop', e => { e.preventDefault(); uploadZone.classList.remove('dragover'); handleFiles(e.dataTransfer.files); });

function handleFiles(files) {
    if (!files.length) return;
    const list = document.getElementById('fileList');
    const progress = document.getElementById('uploadProgress');
    list.classList.add('active');
    progress.classList.add('active');
    list.innerHTML = '';
    const form = document.getElementById('uploadForm');
    const fileInput = document.getElementById('fileInput');

    const dt = new DataTransfer();
    for (const f of files) dt.items.add(f);
    fileInput.files = dt.files;

    let processed = 0;
    Array.from(files).forEach((file, idx) => {
        addFileToList(file.name, file.type === 'application/pdf' ? 'En cours...' : 'Format non supporté', file.type === 'application/pdf' ? 'pending' : 'error');
        if (file.type !== 'application/pdf') { processed++; updateProgress(processed, files.length); return; }
        setTimeout(() => {
            updateFileStatus(file.name, 'success');
            processed++;
            updateProgress(processed, files.length);
            if (processed === files.length) {
                document.querySelector('.progress-text').textContent = 'Importation terminée - Envoi...';
                setTimeout(() => form.submit(), 500);
            }
        }, 800 + idx * 300);
    });
}

function addFileToList(name, statusText, statusClass) {
    const list = document.getElementById('fileList');
    const div = document.createElement('div');
    div.className = 'file-item';
    div.dataset.filename = name;
    div.innerHTML = '<span class="file-icon"><i class="fas fa-file-pdf"></i></span><div class="file-info"><div class="file-name">' + name + '</div></div><span class="file-status ' + statusClass + '">' + statusText + '</span>';
    list.appendChild(div);
}

function updateFileStatus(name, statusClass) {
    document.querySelectorAll('.file-item').forEach(item => {
        if (item.dataset.filename === name) {
            const badge = item.querySelector('.file-status');
            badge.className = 'file-status ' + statusClass;
            badge.textContent = statusClass === 'success' ? 'Importé' : 'Échec';
        }
    });
}

function updateProgress(current, total) {
    const pct = Math.round((current / total) * 100);
    document.getElementById('progressFill').style.width = pct + '%';
    document.getElementById('progressText').textContent = 'Importation en cours... ' + pct + '%';
}

/* ═══ MODALS ═══ */
function openEditModal(id) {
    document.getElementById('editId').value = id;
    document.getElementById('editModal').classList.add('active');
}
function closeEditModal() {
    document.getElementById('editModal').classList.remove('active');
}
function openDeleteModal(id) {
    document.getElementById('deleteId').value = id;
    document.getElementById('deleteModal').classList.add('active');
}
function closeDeleteModal() {
    document.getElementById('deleteModal').classList.remove('active');
}
document.querySelectorAll('.modal-overlay').forEach(m => {
    m.addEventListener('click', e => { if (e.target === m) m.classList.remove('active'); });
});

/* ═══ TOAST ═══ */
function showToast(message, type) {
    const c = document.getElementById('toastContainer');
    const t = document.createElement('div');
    t.className = 'toast ' + (type||'success');
    const icons = { success: '&#x2705;', error: '&#x274C;', info: '&#x2139;&#xFE0F;', warning: '&#x26A0;&#xFE0F;' };
    t.innerHTML = '<span>' + (icons[type] || '&#x2705;') + '</span> ' + message;
    c.appendChild(t);
    setTimeout(() => t.classList.add('show'), 10);
    setTimeout(() => { t.classList.remove('show'); setTimeout(() => t.remove(), 400); }, 3500);
}
</script>
</body>
</html>
