<?php 
ob_start();
session_start();
if (!isset($_SESSION['user'])) {
    header("Location: login.php");
    exit();
}
require_once "includes/dbconn.php";
include('includes/header.php');

// Récupérer la liste des classes pour le filtre
$classes_query = mysqli_query($conn, "SELECT id, nom FROM classes ORDER BY nom");
$classes = [];
while ($classe = mysqli_fetch_assoc($classes_query)) {
    $classes[$classe['id']] = $classe['nom'];
}

// Traitement des actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['mark_as_retrieved']) || isset($_POST['cancel_retrieval'])) {
        $id = mysqli_real_escape_string($conn, $_POST['student_id']);
        
        if (isset($_POST['mark_as_retrieved'])) {
            $date_retrait = date('Y-m-d H:i:s');
            $sql = "UPDATE etudiants SET diplome_retire = 1, date_retrait = '$date_retrait' WHERE id = '$id'";
            $message = "Diplôme marqué comme retiré";
        } else {
            $sql = "UPDATE etudiants SET diplome_retire = 0, date_retrait = NULL WHERE id = '$id'";
            $message = "Retrait de diplôme annulé";
        }
        
        if (mysqli_query($conn, $sql)) {
            $_SESSION['flash_message'] = [
                'type' => 'success',
                'message' => $message
            ];
        } else {
            $_SESSION['flash_message'] = [
                'type' => 'error',
                'message' => mysqli_error($conn)
            ];
        }
        
        header("Location: ".$_SERVER['PHP_SELF']);
        exit();
    }
}

// Afficher les messages flash
if (isset($_SESSION['flash_message'])) {
    $flash_type = $_SESSION['flash_message']['type'];
    $flash_message = $_SESSION['flash_message']['message'];
    unset($_SESSION['flash_message']);
    
    echo "<script>
        document.addEventListener('DOMContentLoaded', function() {
            Swal.fire({
                icon: '$flash_type',
                title: '$flash_type'.charAt(0).toUpperCase() + '$flash_type'.slice(1),
                text: '$flash_message',
                showConfirmButton: false,
                timer: 2000,
                background: '#f8fafc',
                color: '#1e293b'
            });
        });
    </script>";
}

// Récupérer le filtre de classe sélectionné
$selected_class = isset($_GET['classe']) ? intval($_GET['classe']) : 0;
$class_filter = $selected_class > 0 ? "AND e.classe_id = '$selected_class'" : "";
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="utf-8" />
    <title>Gestion des diplômes</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://cdn.datatables.net/1.13.5/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        :root {
            --primary-teal: #0d9488;
            --primary-light: #5eead4;
            --primary-lighter: #ccfbf1;
            --secondary-blue: #0369a1;
            --dark-blue: #1e3a8a;
            --light-bg: #f0fdfa;
            --text-dark: #1e293b;
            --text-light: #f8fafc;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: var(--light-bg);
            color: var(--text-dark);
        }
        
        .page-title {
            color: var(--dark-blue);
            font-weight: 600;
            margin: 15px 0;
            padding-bottom: 8px;
            border-bottom: 2px solid var(--primary-light);
            font-size: 1.5rem;
        }
        
        .filter-container {
            background-color: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
            border-left: 3px solid var(--primary-teal);
        }
        
        .nav-tabs .nav-link {
            color: var(--text-dark);
            border: none;
            padding: 10px 15px;
            font-weight: 500;
            font-size: 0.9rem;
            transition: all 0.3s;
        }
        
        .nav-tabs .nav-link.active {
            color: var(--primary-teal);
            background-color: transparent;
            border-bottom: 3px solid var(--primary-teal);
        }
        
        .nav-tabs .nav-link:hover:not(.active) {
            color: var(--secondary-blue);
        }
        
        .table-container {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            padding: 15px;
            margin-bottom: 20px;
            border-top: 2px solid var(--primary-teal);
        }
        
        .table thead th {
            background-color: var(--primary-teal);
            color: white;
            font-weight: 500;
            border-bottom: none;
            padding: 10px 12px;
            font-size: 0.85rem;
        }
        
        .table tbody td {
            padding: 10px 12px;
            vertical-align: middle;
            border-top: 1px solid #e2e8f0;
            font-size: 0.9rem;
        }
        
        .table-hover tbody tr:hover {
            background-color: var(--primary-lighter);
        }
        
        .badge-retired {
            background-color: var(--primary-teal);
            color: white;
        }
        
        .badge-not-retired {
            background-color: #94a3b8;
            color: white;
        }
        
        .btn-primary {
            background-color: var(--primary-teal);
            border-color: var(--primary-teal);
            padding: 0.25rem 0.5rem;
            font-size: 0.8rem;
        }
        
        .btn-primary:hover {
            background-color: var(--secondary-blue);
            border-color: var(--secondary-blue);
        }
        
        .btn-outline-secondary {
            color: var(--primary-teal);
            border-color: var(--primary-teal);
            padding: 0.25rem 0.5rem;
            font-size: 0.8rem;
        }
        
        .btn-outline-secondary:hover {
            background-color: var(--primary-teal);
            color: white;
        }
        
        .btn-success, .btn-warning, .btn-info {
            padding: 0.25rem 0.5rem;
            font-size: 0.8rem;
        }
        
        .btn-success {
            background-color: var(--primary-teal);
            border-color: var(--primary-teal);
        }
        
        .btn-warning {
            background-color: #f59e0b;
            border-color: #f59e0b;
        }
        
        .btn-info {
            background-color: var(--secondary-blue);
            border-color: var(--secondary-blue);
        }
        
        .container.py-4 {
            padding-top: 1rem !important;
            padding-bottom: 1rem !important;
        }
        
        .d-flex.justify-content-between.align-items-center.mb-4 {
            margin-bottom: 1rem !important;
        }
    </style>
</head>
<body>

<div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="page-title"><i class="fas fa-graduation-cap me-2"></i>Gestion des diplômes</h4>
        <div class="btn-group">
            <a href="views-student.php" class="btn btn-outline-secondary">
                <i class="fas fa-users me-2"></i>Liste des étudiants
            </a>
        </div>
    </div>

    <!-- Filtre par classe -->
    <div class="filter-container">
        <form method="GET" class="row g-3 align-items-center">
            <div class="col-md-6">
                <label for="classe" class="form-label">Filtrer par classe</label>
                <select name="classe" id="classe" class="form-select">
                    <option value="0">Toutes les classes</option>
                    <?php foreach ($classes as $id => $nom): ?>
                        <option value="<?= $id ?>" <?= $selected_class == $id ? 'selected' : '' ?>>
                            <?= htmlspecialchars($nom) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3 d-flex align-items-end">
                <button type="submit" class="btn btn-primary me-2">
                    <i class="fas fa-filter me-1"></i>Filtrer
                </button>
                <?php if ($selected_class > 0): ?>
                    <a href="<?= $_SERVER['PHP_SELF'] ?>" class="btn btn-outline-secondary">
                        <i class="fas fa-times me-1"></i>Réinitialiser
                    </a>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <ul class="nav nav-tabs mb-4" id="myTab" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="retired-tab" data-bs-toggle="tab" data-bs-target="#retired" type="button" role="tab">
                <i class="fas fa-check-circle me-2"></i>Retirés <span class="badge bg-white text-primary ms-2">
                    <?php 
                    $count = mysqli_fetch_assoc(mysqli_query($conn, 
                        "SELECT COUNT(*) as total FROM etudiants e 
                         WHERE e.diplome_retire = 1 $class_filter"));
                    echo $count['total'];
                    ?>
                </span>
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="not-retired-tab" data-bs-toggle="tab" data-bs-target="#not-retired" type="button" role="tab">
                <i class="fas fa-clock me-2"></i>Non retirés <span class="badge bg-white text-secondary ms-2">
                    <?php 
                    $count = mysqli_fetch_assoc(mysqli_query($conn, 
                        "SELECT COUNT(*) as total FROM etudiants e 
                         WHERE e.diplome_retire = 0 OR e.diplome_retire IS NULL $class_filter"));
                    echo $count['total'];
                    ?>
                </span>
            </button>
        </li>
    </ul>

    <div class="tab-content" id="myTabContent">
        <!-- Onglet Diplômes retirés -->
        <div class="tab-pane fade show active" id="retired" role="tabpanel">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Matricule</th>
                            <th>Nom complet</th>
                            <th>Classe</th>
                            <th>Date de retrait</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $query = "SELECT e.id, e.matricule, e.prenom, e.noms, e.date_retrait, 
                                 c.nom AS classe_nom
                                 FROM etudiants e
                                 LEFT JOIN classes c ON e.classe_id = c.id
                                 WHERE e.diplome_retire = 1 $class_filter
                                 ORDER BY e.date_retrait DESC";
                        $result = mysqli_query($conn, $query);
                        
                        if (mysqli_num_rows($result) > 0) {
                            while($row = mysqli_fetch_assoc($result)) {
                                echo "<tr>
                                    <td>{$row['matricule']}</td>
                                    <td>{$row['prenom']} {$row['noms']}</td>
                                    <td>{$row['classe_nom']}</td>
                                    <td>".date('d/m/Y H:i', strtotime($row['date_retrait']))."</td>
                                    <td class='d-flex'>
                                        <form method='POST' class='me-2'>
                                            <input type='hidden' name='student_id' value='{$row['id']}'>
                                            <button type='submit' name='cancel_retrieval' class='btn btn-warning btn-sm'>
                                                <i class='fas fa-undo me-1'></i>Annuler
                                            </button>
                                        </form>
                                        <a href='etudiant-detail.php?id={$row['id']}' class='btn btn-info btn-sm'>
                                            <i class='fas fa-eye me-1'></i>Voir
                                        </a>
                                    </td>
                                </tr>";
                            }
                        } else {
                            echo "<tr><td colspan='5' class='text-center py-4'>Aucun diplôme retiré</td></tr>";
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Onglet Diplômes non retirés -->
        <div class="tab-pane fade" id="not-retired" role="tabpanel">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Matricule</th>
                            <th>Nom complet</th>
                            <th>Classe</th>
                            <th>Statut</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $query = "SELECT e.id, e.matricule, e.prenom, e.noms, 
                                 c.nom AS classe_nom, e.diplome_retire
                                 FROM etudiants e
                                 LEFT JOIN classes c ON e.classe_id = c.id
                                 WHERE (e.diplome_retire = 0 OR e.diplome_retire IS NULL) $class_filter
                                 ORDER BY e.noms, e.prenom";
                        $result = mysqli_query($conn, $query);
                        
                        if (mysqli_num_rows($result) > 0) {
                            while($row = mysqli_fetch_assoc($result)) {
                                echo "<tr>
                                    <td>{$row['matricule']}</td>
                                    <td>{$row['prenom']} {$row['noms']}</td>
                                    <td>{$row['classe_nom']}</td>
                                    <td>
                                        <span class='badge badge-not-retired'>
                                            ".(is_null($row['diplome_retire']) ? 'Non précisé' : 'Non retiré')."
                                        </span>
                                    </td>
                                    <td class='d-flex'>
                                        <form method='POST' class='me-2'>
                                            <input type='hidden' name='student_id' value='{$row['id']}'>
                                            <button type='submit' name='mark_as_retrieved' class='btn btn-success btn-sm'>
                                                <i class='fas fa-check me-1'></i>Retiré
                                            </button>
                                        </form>
                                        <a href='etudiant-detail.php?id={$row['id']}' class='btn btn-info btn-sm'>
                                            <i class='fas fa-eye me-1'></i>Voir
                                        </a>
                                    </td>
                                </tr>";
                            }
                        } else {
                            echo "<tr><td colspan='5' class='text-center py-4'>Tous les diplômes ont été retirés</td></tr>";
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- JS scripts -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.5/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(document).ready(function() {
    // Initialisation DataTables
    $('.table').DataTable({
        language: {
            url: '//cdn.datatables.net/plug-ins/1.13.5/i18n/fr-FR.json'
        },
        dom: '<"top"f>rt<"bottom"lip><"clear">',
        responsive: true
    });
    
    // Gestion des onglets avec persistance
    $('a[data-bs-toggle="tab"]').on('shown.bs.tab', function(e) {
        localStorage.setItem('lastTab', $(e.target).attr('href'));
    });
    
    var lastTab = localStorage.getItem('lastTab');
    if (lastTab) {
        $('[href="' + lastTab + '"]').tab('show');
    }
});

function confirmAction() {
    return Swal.fire({
        title: 'Confirmation',
        text: "Êtes-vous sûr de vouloir effectuer cette action ?",
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#0d9488',
        cancelButtonColor: '#94a3b8',
        confirmButtonText: 'Oui, confirmer',
        cancelButtonText: 'Annuler'
    }).then((result) => {
        return result.isConfirmed;
    });
}
</script>

</body>
</html>
<?php ob_end_flush(); ?>