<?php 
ob_start();
session_start();
$userprofil = $_SESSION['user'];
if ($userprofil == true) {
    $role = $userprofil['role'] ?? 'caissier';
    include('includes/header.php');
    require_once "includes/dbconn.php";
} else {
    header("Location: login.php");
    exit();
}

// Traitement modification
if (isset($_POST['edit_class'])) {
    if ($role !== 'admin') die("Accès non autorisé");
    $id = intval($_POST['class_id']);
    $nom = mysqli_real_escape_string($conn, $_POST['nom']);
    $niveau_id = intval($_POST['niveau_id']);
    mysqli_query($conn, "UPDATE classes SET nom = '$nom', niveau_id = $niveau_id WHERE id = $id");
    header("Location: listClasse.php?updated=1");
    exit;
}

// Traitement suppression
if (isset($_GET['delete'])) {
    if ($role !== 'admin') die("Accès non autorisé");
    $id = intval($_GET['delete']);
    mysqli_query($conn, "DELETE FROM classes WHERE id = $id");
    header("Location: listClasse.php?deleted=1");
    exit;
}

// Récupération des niveaux
$niveau_result = mysqli_query($conn, "SELECT id, nom_niveau FROM niveaux ORDER BY nom_niveau");
$niveau_options = [];
while ($niveau = mysqli_fetch_assoc($niveau_result)) {
    $niveau_options[$niveau['id']] = $niveau['nom_niveau'];
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestion des Classes</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">
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <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: #f5f7fa;
            color: #333;
        }
        
        .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;
        }
        
        .table thead th {
            background-color: var(--primary);
            color: white;
            font-weight: 500;
            border-bottom: none;
        }
        
        .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-edit {
            background-color: rgba(40, 167, 69, 0.1);
            color: var(--success);
            border: none;
        }
        
        .btn-edit:hover {
            background-color: var(--success);
            color: white;
        }
        
        .btn-view {
            background-color: rgba(13, 110, 253, 0.1);
            color: #0d6efd;
            border: none;
        }
        
        .btn-view:hover {
            background-color: #0d6efd;
            color: white;
        }
        
        .btn-delete {
            background-color: rgba(220, 53, 69, 0.1);
            color: var(--danger);
            border: none;
        }
        
        .btn-delete:hover {
            background-color: var(--danger);
            color: white;
        }
        
        .empty-state {
            text-align: center;
            padding: 40px 0;
            color: #6c757d;
        }
        
        .empty-state i {
            font-size: 50px;
            color: var(--primary-lighter);
            margin-bottom: 15px;
        }
        
        .badge.bg-secondary {
            background-color: #e9ecef !important;
            color: #495057;
        }
        
        /* 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);
        }
        
        /* Custom buttons */
        .btn-success {
            background-color: var(--primary);
            border-color: var(--primary);
            transition: all 0.2s;
        }
        
        .btn-success:hover {
            background-color: var(--primary-light);
            border-color: var(--primary-light);
            transform: translateY(-1px);
        }
        
        /* 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">
    <h1 class="page-title"><i class="fas fa-chalkboard me-2"></i>Gestion des Classes</h1>

    <?php if ($role === 'admin'): ?>
        <a href="addClasse.php" class="btn btn-success mb-4">
            <i class="fas fa-plus-circle me-1"></i> Ajouter une classe
        </a>
    <?php endif; ?>

    <?php if (isset($_GET['updated'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i> Classe modifiée avec succès !
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php elseif (isset($_GET['deleted'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i> Classe supprimée avec succès !
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <div class="table-container">
        <table class="table table-hover" id="classesTable">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Nom de la classe</th>
                    <th>Niveau</th>
                    <th>Date de création</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php
            $res = mysqli_query($conn, "
                SELECT c.id, c.nom, n.nom_niveau AS nom_niveau, c.niveau_id, c.date_creation
                FROM classes c
                JOIN niveaux n ON c.niveau_id = n.id
                ORDER BY c.id DESC
            ");
            
            if (mysqli_num_rows($res) === 0): ?>
                <tr>
                    <td colspan="5" class="empty-state">
                        <i class="far fa-folder-open"></i>
                        <p class="mt-2">Aucune classe trouvée</p>
                    </td>
                </tr>
            <?php else: 
                while ($row = mysqli_fetch_assoc($res)): ?>
                    <tr data-id="<?= $row['id'] ?>" data-niveau="<?= $row['niveau_id'] ?>" data-nom="<?= htmlspecialchars($row['nom'], ENT_QUOTES) ?>">
                        <td><?= $row['id'] ?></td>
                        <td><strong><?= htmlspecialchars($row['nom']) ?></strong></td>
                        <td><?= htmlspecialchars($row['nom_niveau']) ?></td>
                        <td><?= date('d/m/Y', strtotime($row['date_creation'])) ?></td>
                        <td>
                            <?php if ($role === 'admin'): ?>
                                <button class="btn btn-edit btn-action btn-edit-class" title="Modifier">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <a href="info_classe.php?id=<?= $row['id'] ?>" class="btn btn-view btn-action" title="Voir détails">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <button class="btn btn-delete btn-action btn-delete-class" title="Supprimer">
                                    <i class="fas fa-trash-alt"></i>
                                </button>
                            <?php else: ?>
                                <a href="info_classe.php?id=<?= $row['id'] ?>" class="btn btn-view btn-action" title="Voir détails">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <span class="badge bg-secondary">Accès limité</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endwhile;
            endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Modal Modification - Admin seulement -->
<?php if ($role === 'admin'): ?>
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <form method="POST" id="editForm" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="editModalLabel"><i class="fas fa-edit me-2"></i>Modifier la classe</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="class_id" id="class_id">
        <div class="mb-3">
          <label for="nom" class="form-label">Nom de la classe</label>
          <input type="text" class="form-control" id="nom" name="nom" required>
        </div>
        <div class="mb-3">
          <label for="niveau_id" class="form-label">Niveau</label>
          <select class="form-select" name="niveau_id" id="niveau_id" required>
            <option value="">-- Choisir un niveau --</option>
            <?php foreach($niveau_options as $id => $nom_niveau): ?>
              <option value="<?= $id ?>"><?= htmlspecialchars($nom_niveau) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="submit" name="edit_class" class="btn btn-primary">
          <i class="fas fa-save me-1"></i> Enregistrer
        </button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          <i class="fas fa-times me-1"></i> Annuler
        </button>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>

<!-- Scripts JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
$(document).ready(function () {
    $('#classesTable').DataTable({
        language: {
            url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/fr-FR.json'
        },
        responsive: true,
        columnDefs: [
            <?php if ($role !== 'admin'): ?>
            { targets: [4], searchable: false, orderable: false }
            <?php endif; ?>
        ]
    });

    <?php if ($role === 'admin'): ?>
    // Suppression d'une classe
    $(document).on('click', '.btn-delete-class', function() {
        const classeId = $(this).closest('tr').data('id');
        Swal.fire({
            title: 'Confirmer la suppression ?',
            text: "Cette action est irréversible !",
            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) {
                window.location.href = 'listClasse.php?delete=' + classeId;
            }
        });
    });

    // Modification d'une classe
    $(document).on('click', '.btn-edit-class', function() {
        const row = $(this).closest('tr');
        const id = row.data('id');
        const nom = row.data('nom');
        const niveau = row.data('niveau');

        $('#class_id').val(id);
        $('#nom').val(nom);
        $('#niveau_id').val(niveau);

        const editModal = new bootstrap.Modal(document.getElementById('editModal'));
        editModal.show();
    });
    <?php endif; ?>
});
</script>
</body>
</html>