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

include('includes/header.php');
require_once "includes/dbconn.php";

// Paramètres de pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10;
$offset = ($page - 1) * $perPage;

// Paramètres de recherche
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// Requête de base
$sql = "SELECT SQL_CALC_FOUND_ROWS 
            a.id,
            a.etudiant_id,
            a.classe_id,
            a.date_debut,
            a.date_fin,
            a.motif,
            a.date_enregistrement,
            e.noms AS etudiant_nom,
            e.prenom AS etudiant_prenom,
            c.nom AS classe_nom,
            CASE 
                WHEN a.date_fin < CURDATE() THEN 'expired'
                WHEN a.date_debut > CURDATE() THEN 'pending'
                ELSE 'active'
            END AS auth_status
        FROM 
            autorisations_absence a
        JOIN 
            etudiants e ON a.etudiant_id = e.id
        JOIN 
            classes c ON a.classe_id = c.id";

// Ajout de la condition de recherche si nécessaire
if (!empty($search)) {
    $sql .= " WHERE CONCAT(e.prenom, ' ', e.noms) LIKE ? OR c.nom LIKE ? OR a.motif LIKE ?";
}

$sql .= " ORDER BY a.date_debut DESC LIMIT ? OFFSET ?";

$stmt = $conn->prepare($sql);

// Liaison des paramètres
if (!empty($search)) {
    $searchParam = "%$search%";
    $stmt->bind_param("sssii", $searchParam, $searchParam, $searchParam, $perPage, $offset);
} else {
    $stmt->bind_param("ii", $perPage, $offset);
}

$stmt->execute();
$result = $stmt->get_result();
$absences = $result->fetch_all(MYSQLI_ASSOC);

// Récupération du nombre total d'enregistrements
$totalResult = $conn->query("SELECT FOUND_ROWS()");
$totalRows = $totalResult->fetch_row()[0];
$totalPages = ceil($totalRows / $perPage);

// Traitement de la suppression
if (isset($_POST['delete_id'])) {
    $deleteId = (int)$_POST['delete_id'];
    $deleteStmt = $conn->prepare("DELETE FROM autorisations_absence WHERE id = ?");
    $deleteStmt->bind_param("i", $deleteId);
    if ($deleteStmt->execute()) {
        $_SESSION['message'] = "L'absence a été supprimée avec succès.";
        header("Location: ".$_SERVER['PHP_SELF']);
        exit();
    }
}
?>
<?php ob_end_flush(); ?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Gestion des Absences</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        :root {
            --primary-color: #2a6f6b; /* Vert-bleu foncé */
            --secondary-color: #3a7ca5; /* Bleu-vert */
            --light-color: #f0fdfa; /* Vert très clair */
            --danger-color: #e74c3c;
            --success-color: #2ecc71;
            --warning-color: #f39c12;
        }
        
        body {
            background-color: #f8f9fa;
        }
        
        .table-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
            border: 1px solid rgba(0,0,0,0.05);
        }
        
        .badge-expired { background-color: var(--danger-color); }
        .badge-active { background-color: var(--success-color); }
        .badge-pending { background-color: var(--warning-color); }
        
        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .btn-primary:hover {
            background-color: #1d4d4a;
            border-color: #1d4d4a;
        }
        
        .btn-secondary {
            background-color: var(--secondary-color);
            border-color: var(--secondary-color);
        }
        
        .btn-secondary:hover {
            background-color: #2c5f7d;
            border-color: #2c5f7d;
        }
        
        .btn-edit {
            background-color: #f39c12;
            border-color: #f39c12;
            color: white;
        }
        
        .btn-edit:hover {
            background-color: #d68910;
            border-color: #d68910;
            color: white;
        }
        
        .btn-delete {
            background-color: var(--danger-color);
            border-color: var(--danger-color);
            color: white;
        }
        
        .btn-delete:hover {
            background-color: #c0392b;
            border-color: #c0392b;
            color: white;
        }
        
        .pagination .page-item.active .page-link {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .pagination .page-link {
            color: var(--primary-color);
        }
        
        .card-header {
            background-color: var(--primary-color);
            color: white;
        }
        
        .table thead {
            background-color: var(--primary-color);
            color: white;
        }
        
        .status-badge {
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }
    </style>
</head>
<body>
<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="mb-0"><i class="fas fa-calendar-times me-2"></i>Gestion des Absences</h1>
        <a href="add_absence.php" class="btn btn-primary">
            <i class="fas fa-plus me-1"></i> Nouvelle absence
        </a>
    </div>
    
    <!-- Barre de recherche -->
    <div class="card mb-4 border-0 shadow-sm">
        <div class="card-body p-3" style="background-color: var(--light-color);">
            <form method="get" class="row g-3 align-items-center">
                <div class="col-md-8">
                    <div class="input-group">
                        <span class="input-group-text bg-white"><i class="fas fa-search text-muted"></i></span>
                        <input type="text" name="search" class="form-control border-start-0" placeholder="Rechercher par nom étudiant, classe ou motif..." value="<?= htmlspecialchars($search) ?>">
                    </div>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-search me-1"></i> Rechercher
                    </button>
                </div>
                <div class="col-md-2">
                    <a href="?search=" class="btn btn-secondary w-100">
                        <i class="fas fa-sync-alt me-1"></i> Réinitialiser
                    </a>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Tableau des absences -->
    <div class="table-container overflow-hidden">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead>
                    <tr>
                        <th style="width: 5%;">ID</th>
                        <th style="width: 20%;">Étudiant</th>
                        <th style="width: 15%;">Classe</th>
                        <th style="width: 20%;">Période</th>
                        <th style="width: 20%;">Motif</th>
                        <th style="width: 10%;">Statut</th>
                        <th style="width: 10%;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($absences)): ?>
                        <tr>
                            <td colspan="7" class="text-center py-5">
                                <i class="fas fa-info-circle fa-2x mb-3" style="color: var(--secondary-color);"></i>
                                <p class="text-muted">Aucune absence trouvée</p>
                                <a href="add_absence.php" class="btn btn-primary mt-2">
                                    <i class="fas fa-plus me-1"></i> Ajouter une absence
                                </a>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($absences as $abs): ?>
                            <tr>
                                <td><?= $abs['id'] ?></td>
                                <td>
                                    <div class="fw-semibold"><?= htmlspecialchars($abs['etudiant_prenom'] . ' ' . $abs['etudiant_nom']) ?></div>
                                    <small class="text-muted">ID: <?= $abs['etudiant_id'] ?></small>
                                </td>
                                <td>
                                    <div class="fw-semibold"><?= htmlspecialchars($abs['classe_nom']) ?></div>
                                    <small class="text-muted">ID: <?= $abs['classe_id'] ?></small>
                                </td>
                                <td>
                                    <div>
                                        <span class="fw-semibold"><?= date('d/m/Y', strtotime($abs['date_debut'])) ?></span> - 
                                        <span class="fw-semibold"><?= date('d/m/Y', strtotime($abs['date_fin'])) ?></span>
                                    </div>
                                    <small class="text-muted">
                                        <?php
                                        $today = new DateTime();
                                        $dateFin = new DateTime($abs['date_fin']);
                                        
                                        if ($abs['auth_status'] === 'expired') {
                                            echo '<i class="fas fa-exclamation-circle me-1"></i> Expirée depuis ' . $today->diff($dateFin)->format('%a jours');
                                        } elseif ($abs['auth_status'] === 'pending') {
                                            echo '<i class="fas fa-clock me-1"></i> Débute dans ' . (new DateTime($abs['date_debut']))->diff($today)->format('%a jours');
                                        } else {
                                            echo '<i class="fas fa-check-circle me-1"></i> Jours restants: ' . $today->diff($dateFin)->format('%a');
                                        }
                                        ?>
                                    </small>
                                </td>
                                <td>
                                    <div class="text-truncate" style="max-width: 200px;" title="<?= htmlspecialchars($abs['motif']) ?>">
                                        <?= htmlspecialchars($abs['motif']) ?>
                                    </div>
                                </td>
                                <td>
                                    <?php if ($abs['auth_status'] === 'expired'): ?>
                                        <span class="badge badge-expired status-badge">
                                            <i class="fas fa-exclamation-circle me-1"></i> Expirée
                                        </span>
                                    <?php elseif ($abs['auth_status'] === 'active'): ?>
                                        <span class="badge badge-active status-badge">
                                            <i class="fas fa-check-circle me-1"></i> Active
                                        </span>
                                    <?php else: ?>
                                        <span class="badge badge-pending status-badge">
                                            <i class="fas fa-clock me-1"></i> En attente
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="d-flex">
                                        <a href="edit_absence.php?id=<?= $abs['id'] ?>" class="btn btn-sm btn-edit me-2">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <button class="btn btn-sm btn-delete delete-btn" data-id="<?= $abs['id'] ?>">
                                            <i class="fas fa-trash-alt"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php if ($totalPages > 1): ?>
            <div class="card-footer bg-transparent">
                <nav aria-label="Page navigation">
                    <ul class="pagination justify-content-center mb-0">
                        <?php if ($page > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?= $page-1 ?>&search=<?= urlencode($search) ?>" aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                        <?php endif; ?>
                        
                        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                            <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                                <a class="page-link" href="?page=<?= $i ?>&search=<?= urlencode($search) ?>"><?= $i ?></a>
                            </li>
                        <?php endfor; ?>
                        
                        <?php if ($page < $totalPages): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?= $page+1 ?>&search=<?= urlencode($search) ?>" aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        <?php endif; ?>
                    </ul>
                </nav>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Formulaire caché pour la suppression -->
<form id="deleteForm" method="post" style="display:none;">
    <input type="hidden" name="delete_id" id="delete_id">
</form>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Confirmation de suppression
document.querySelectorAll('.delete-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const absenceId = this.getAttribute('data-id');
        
        Swal.fire({
            title: 'Confirmer la suppression',
            text: "Vous êtes sur le point de supprimer cette absence. Cette action est irréversible.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#e74c3c',
            cancelButtonColor: '#3a7ca5',
            confirmButtonText: 'Oui, supprimer',
            cancelButtonText: 'Annuler',
            backdrop: `
                rgba(42, 111, 107, 0.1)
                url("data:image/svg+xml,%3Csvg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zM32 63c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm57-13c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-9-21c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM60 91c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM35 41c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM12 60c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2z' fill='%232a6f6b' fill-opacity='0.05' fill-rule='evenodd'/%3E%3C/svg%3E")
            `
        }).then((result) => {
            if (result.isConfirmed) {
                document.getElementById('delete_id').value = absenceId;
                document.getElementById('deleteForm').submit();
            }
        });
    });
});

// Affichage des messages de session
<?php if (isset($_SESSION['message'])): ?>
    Swal.fire({
        icon: 'success',
        title: 'Succès',
        text: '<?= $_SESSION['message'] ?>',
        timer: 3000,
        showConfirmButton: false,
        background: 'white',
        backdrop: `
            rgba(42, 111, 107, 0.1)
        `
    });
    <?php unset($_SESSION['message']); ?>
<?php endif; ?>
</script>
</body>
</html>