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

// Mise à jour étudiant
if (isset($_POST['update_student'])) {
    $id = $_POST['edit_id'];
    $prenom = mysqli_real_escape_string($conn, $_POST['prenom']);
    $noms = mysqli_real_escape_string($conn, $_POST['noms']);
    $classe_id = $_POST['classe_id'];

    if (!empty($_FILES['photo']['name'])) {
        $photo_name = time() . '_' . basename($_FILES["photo"]["name"]);
        $target_path = "studentimages/" . $photo_name;
        move_uploaded_file($_FILES["photo"]["tmp_name"], $target_path);
        $sql_update = "UPDATE etudiants SET prenom='$prenom', noms='$noms', classe_id='$classe_id', photo='$photo_name' WHERE id='$id'";
    } else {
        $sql_update = "UPDATE etudiants SET prenom='$prenom', noms='$noms', classe_id='$classe_id' WHERE id='$id'";
    }

    if (mysqli_query($conn, $sql_update)) {
        echo "<script>
            setTimeout(() => {
                Swal.fire({
                    icon: 'success',
                    title: 'Mise à jour réussie',
                    showConfirmButton: false,
                    timer: 2000
                }).then(() => { location.href = 'views-student.php'; });
            }, 200);
        </script>";
    } else {
        echo "<script>
            Swal.fire({
                icon: 'error',
                title: 'Erreur',
                text: '".mysqli_error($conn)."'
            });
        </script>";
    }
}

// Suppression
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete-student'])) {
    $id_student = mysqli_real_escape_string($conn, $_POST['delete-student']);
    mysqli_query($conn, "DELETE FROM etudiants WHERE id = '$id_student'");
    header("Location: ".$_SERVER['PHP_SELF']);
    exit();
}
?>
<?php ob_end_flush(); ?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="utf-8" />
    <title>Liste des étudiants</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" />
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        :root {
            --primary: #2B7A78;
            --primary-light: #3AAFA9;
            --primary-lighter: #DEF2F1;
            --secondary: #17252A;
            --accent: #FEFFFF;
            --success: #28a745;
            --danger: #dc3545;
            --warning: #fd7e14;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background-color: #f8fafc;
            color: var(--secondary);
        }
        
        .page-title {
            color: var(--secondary);
            font-weight: 600;
            margin: 20px 0;
            padding-bottom: 10px;
            border-bottom: 2px solid var(--primary-lighter);
        }
        
        .table-container {
            background-color: var(--accent);
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            padding: 20px;
            margin-bottom: 30px;
        }
        
        .table {
            margin-bottom: 0;
            border-radius: 8px;
            overflow: hidden;
        }
        
        .table thead th {
            background-color: var(--primary);
            color: white;
            font-weight: 500;
            border-bottom: none;
            padding: 12px 15px;
        }
        
        .table tbody td {
            padding: 10px 15px;
            vertical-align: middle;
        }
        
        .table-hover tbody tr:hover {
            background-color: rgba(58, 175, 169, 0.1);
        }
        
        .btn-action {
            width: 32px;
            height: 32px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            margin: 0 3px;
            transition: all 0.2s;
        }
        
        .btn-outline-primary {
            border-color: var(--primary);
            color: var(--primary);
        }
        
        .btn-outline-primary:hover {
            background-color: var(--primary);
            color: white;
        }
        
        .btn-outline-warning {
            border-color: var(--warning);
            color: var(--warning);
        }
        
        .btn-outline-warning:hover {
            background-color: var(--warning);
            color: white;
        }
        
        .btn-outline-danger {
            border-color: var(--danger);
            color: var(--danger);
        }
        
        .btn-outline-danger:hover {
            background-color: var(--danger);
            color: white;
        }
        
        .btn-add {
            background-color: var(--primary);
            border-color: var(--primary);
            color: white;
            transition: all 0.2s;
        }
        
        .btn-add:hover {
            background-color: var(--primary-light);
            border-color: var(--primary-light);
            transform: translateY(-1px);
        }
        
        .breadcrumb {
            background-color: transparent;
            padding: 8px 0;
        }
        
        .breadcrumb-item a {
            color: var(--primary);
            text-decoration: none;
        }
        
        .breadcrumb-item.active {
            color: var(--secondary);
        }
        
        .img-thumbnail {
            max-height: 100px;
            border-radius: 6px;
            border: 1px solid var(--primary-lighter);
        }
        
        /* Modal styles */
        .modal-header {
            background-color: var(--primary);
            color: white;
            border-bottom: none;
        }
        
        .btn-close-white {
            filter: invert(1);
        }
        
        .modal-footer {
            border-top: 1px solid var(--primary-lighter);
        }
        
        /* DataTable customizations */
        .dataTables_wrapper .dataTables_paginate .paginate_button {
            padding: 5px 10px;
            border-radius: 4px;
            margin: 0 2px;
        }
        
        .dataTables_wrapper .dataTables_paginate .paginate_button.current {
            background: var(--primary) !important;
            color: white !important;
            border: none;
        }
        
        .dataTables_wrapper .dataTables_paginate .paginate_button:hover {
            background: var(--primary-lighter) !important;
            color: var(--secondary) !important;
            border: none;
        }
        
        /* Responsive adjustments */
        @media (max-width: 768px) {
            .table-container {
                padding: 10px;
            }
            
            .btn-action {
                width: 28px;
                height: 28px;
                font-size: 12px;
            }
        }
    </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-users me-2"></i>Gestion des étudiants</h4>
        <a href="add-student.php" class="btn btn-add">
            <i class="fas fa-user-plus me-2"></i>Nouvelle inscription
        </a>
    </div>

    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Accueil</a></li>
            <li class="breadcrumb-item active" aria-current="page">Liste des étudiants</li>
        </ol>
    </nav>

    <div class="table-container">
        <table id="maTable" class="table table-hover">
            <thead>
                <tr>
                    <th>Matricule</th>
                    <th>Prénom</th>
                    <th>Nom</th>
                    <th>Classe</th>
                    <th>Niveau</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php  
                $query = "
                    SELECT e.id, e.matricule, e.prenom, e.noms, e.photo,
                           c.nom AS classe_nom,
                           c.id AS classe_id,
                           n.nom_niveau AS niveau_nom
                    FROM etudiants e
                    LEFT JOIN classes c ON e.classe_id = c.id
                    LEFT JOIN niveaux n ON c.niveau_id = n.id
                ";
                $query_run = mysqli_query($conn, $query);

                if (mysqli_num_rows($query_run) > 0) {
                    foreach($query_run as $etudiant) {
                        ?>
                        <tr>
                            <td><?= $etudiant['matricule']; ?></td>
                            <td><?= htmlspecialchars($etudiant['prenom']); ?></td>
                            <td><?= htmlspecialchars($etudiant['noms']); ?></td>
                            <td><?= htmlspecialchars($etudiant['classe_nom']); ?></td>
                            <td><?= htmlspecialchars($etudiant['niveau_nom']); ?></td>
                            <td>
                                <a href="etudiant-detail.php?id=<?= $etudiant['id']; ?>" class="btn btn-outline-primary btn-action" title="Voir fiche">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <button class="btn btn-outline-warning btn-action" title="Modifier" data-bs-toggle="modal" data-bs-target="#editModal<?= $etudiant['id']; ?>">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-outline-danger btn-action" onclick="confirmDelete(<?= $etudiant['id']; ?>)" title="Supprimer">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </td>
                        </tr>

                        <!-- Modal Modification -->
                        <div class="modal fade" id="editModal<?= $etudiant['id']; ?>" tabindex="-1" aria-labelledby="editModalLabel<?= $etudiant['id']; ?>" aria-hidden="true">
                          <div class="modal-dialog modal-lg">
                            <form method="POST" enctype="multipart/form-data">
                              <input type="hidden" name="edit_id" value="<?= $etudiant['id']; ?>">
                              <div class="modal-content">
                                <div class="modal-header">
                                  <h5 class="modal-title"><i class="fas fa-edit me-2"></i>Modifier l'étudiant</h5>
                                  <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fermer"></button>
                                </div>
                                <div class="modal-body row g-3">
                                  <div class="col-md-6">
                                    <label class="form-label">Matricule</label>
                                    <input type="text" class="form-control" value="<?= htmlspecialchars($etudiant['matricule']); ?>" readonly>
                                  </div>
                                  <div class="col-md-6">
                                    <label class="form-label">Prénom</label>
                                    <input type="text" name="prenom" class="form-control" value="<?= htmlspecialchars($etudiant['prenom']); ?>" required>
                                  </div>
                                  <div class="col-md-6">
                                    <label class="form-label">Nom</label>
                                    <input type="text" name="noms" class="form-control" value="<?= htmlspecialchars($etudiant['noms']); ?>" required>
                                  </div>
                                  <div class="col-md-6">
                                    <label class="form-label">Classe</label>
                                    <select name="classe_id" class="form-select" required>
                                      <?php 
                                      $classes = mysqli_query($conn, "SELECT * FROM classes");
                                      while ($c = mysqli_fetch_assoc($classes)) {
                                          $selected = ($etudiant['classe_id'] == $c['id']) ? 'selected' : '';
                                          echo "<option value='{$c['id']}' $selected>{$c['nom']}</option>";
                                      }
                                      ?>
                                    </select>
                                  </div>
                                  <div class="col-md-6">
                                    <label class="form-label">Niveau</label>
                                    <input type="text" class="form-control" value="<?= htmlspecialchars($etudiant['niveau_nom']); ?>" readonly>
                                  </div>
                                  <div class="col-md-6">
                                    <label class="form-label">Photo actuelle</label><br>
                                    <img src="studentimages/<?= $etudiant['photo']; ?>" alt="Photo" class="img-thumbnail">
                                  </div>
                                  <div class="col-md-12">
                                    <label class="form-label">Nouvelle photo (laisser vide si inchangé)</label>
                                    <input type="file" name="photo" class="form-control">
                                  </div>
                                </div>
                                <div class="modal-footer">
                                  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
                                  <button type="submit" name="update_student" class="btn btn-primary">Enregistrer</button>
                                </div>
                              </div>
                            </form>
                          </div>
                        </div>
                        <?php
                    }
                } else {
                    echo "<tr><td colspan='6' class='text-center py-4'>Aucun étudiant trouvé</td></tr>";
                }
                ?>
            </tbody>
        </table>
    </div>

<!-- Formulaire suppression caché -->
<form id="deleteForm" method="POST" style="display:none;">
    <input type="hidden" name="delete-student" id="deleteId">
</form>

<!-- 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() {
    $('#maTable').DataTable({
        responsive: true,
        autoWidth: false,
        language: {
            url: "//cdn.datatables.net/plug-ins/1.13.5/i18n/fr-FR.json"
        },
        pageLength: 5,
        lengthMenu: [[5, 10, 25, 50, -1], [5, 10, 25, 50, "Tous"]]
    });
});

function confirmDelete(id) {
    Swal.fire({
        title: 'Confirmation',
        text: "Voulez-vous vraiment supprimer cet étudiant ?",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc3545',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Oui, supprimer',
        cancelButtonText: 'Annuler',
        backdrop: 'rgba(0,0,0,0.4)'
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById('deleteId').value = id;
            document.getElementById('deleteForm').submit();
        }
    });
}
</script>

</body>
</html>