<?php
session_start();

// Vérification de l'authentification et des permissions
if (!isset($_SESSION['user'])) {
    header("Location: login.php");
    exit();
}

$isAdmin = ($_SESSION['user']['role'] === 'admin');
$isTeacher = ($_SESSION['user']['role'] === 'teacher');

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

// Initialisation des variables
$message = '';

// Suppression possible (uniquement pour l'admin)
if ($isAdmin && isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $stmt = $conn->prepare("DELETE FROM modules WHERE id = ?");
    $stmt->bind_param("i", $id);
    if ($stmt->execute()) {
        $message = "<script>Swal.fire('Supprimé','Module supprimé.','success');</script>";
    } else {
        $message = "<script>Swal.fire('Erreur','Suppression impossible.','error');</script>";
    }
    $stmt->close();
}

// Récupération des classes
$classes = $conn->query("SELECT id, nom FROM classes ORDER BY nom")->fetch_all(MYSQLI_ASSOC);

// Ajout ou modification (admin et teachers)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && ($isAdmin || $isTeacher)) {
    $nomModule = trim($_POST['nomModule']);
    $classeId = intval($_POST['classe']);
    $coefficient = intval($_POST['coefficient']);

    if (!empty($nomModule) && $classeId > 0 && $coefficient > 0) {
        if ($_POST['action'] === 'add') {
            $stmt = $conn->prepare("INSERT INTO modules(nom,coefficient,classe_id) VALUES(?,?,?)");
            $stmt->bind_param("sii", $nomModule, $coefficient, $classeId);
        } else {
            $stmt = $conn->prepare("UPDATE modules SET nom=?, coefficient=?, classe_id=? WHERE id=?");
            $stmt->bind_param("siii", $nomModule, $coefficient, $classeId, $_POST['id']);
        }
        
        if ($stmt->execute()) {
            $message = "<script>Swal.fire('Succès','Opération réussie.','success');</script>";
        } else {
            $message = "<script>Swal.fire('Erreur','Opération échouée.','error');</script>";
        }
        $stmt->close();
    } else {
        $message = "<script>Swal.fire('Attention','Veuillez remplir tous les champs.','warning');</script>";
    }
}

// Pagination
$items_par_page = 10;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $items_par_page;

// Requête comptage
$total_items = $conn->query("SELECT COUNT(*) FROM modules")->fetch_row()[0];
$total_pages = ceil($total_items / $items_par_page);

// Requête principale
$query = "SELECT m.id, m.nom, m.coefficient, c.nom AS classe_nom, c.id AS classe_id
          FROM modules m JOIN classes c ON m.classe_id=c.id
          ORDER BY c.nom, m.nom
          LIMIT ?, ?";

$stmt = $conn->prepare($query);
$stmt->bind_param("ii", $offset, $items_par_page);
$stmt->execute();
$modules = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
$conn->close();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Gestion des modules</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.0.0/css/all.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
:root {
  --vert: #2E8B57;
  --bleu: #1E88E5;
  --light-bg: #f5f5f5;
}

body {
  background: var(--light-bg);
  font-family: 'Roboto', sans-serif;
}

.header {
  background: linear-gradient(135deg, var(--vert), #1B5E20);
  color: white;
  padding: 1.5rem;
  margin-bottom: 2rem;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.table thead {
  background: var(--vert);
  color: white;
}

.btn-success {
  background: var(--vert);
  border: none;
}

.btn-success:hover {
  background: #2a7a4d;
}

.btn-primary {
  background: var(--bleu);
  border: none;
}

.btn-primary:hover {
  background: #1976D2;
}

.pagination .page-item.active .page-link {
  background: var(--vert);
  border-color: var(--vert);
}

/* Style pour les éléments désactivés */
button:disabled, input:disabled, select:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.card {
  border: none;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

.form-control:focus, .form-select:focus {
  border-color: var(--vert);
  box-shadow: 0 0 0 0.25rem rgba(46, 139, 87, 0.25);
}

.action-buttons {
  white-space: nowrap;
}

.badge {
  background-color: var(--bleu);
}
</style>
</head>
<body>
<div class="container py-4">
    <div class="header">
        <div class="d-flex justify-content-between align-items-center">
            <h2><i class="fas fa-book me-2"></i>Gestion des modules</h2>
            <?php if ($isAdmin || $isTeacher): ?>
            <button class="btn btn-light" onclick="resetForm()">
                <i class="fas fa-plus-circle me-1"></i> Nouveau module
            </button>
            <?php endif; ?>
        </div>
    </div>

    <?= $message ?>

    <!-- Formulaire -->
    <div class="card mb-4">
        <div class="card-body">
            <form id="modForm" method="POST">
                <input type="hidden" name="action" id="action" value="add">
                <input type="hidden" name="id" id="modId">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label">Nom du module</label>
                        <input type="text" name="nomModule" class="form-control" <?= !$isAdmin && !$isTeacher ? 'disabled' : '' ?> required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Classe</label>
                        <select name="classe" class="form-select" <?= !$isAdmin && !$isTeacher ? 'disabled' : '' ?> required>
                            <option value="">Sélectionner...</option>
                            <?php foreach ($classes as $c): ?>
                            <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['nom']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Coefficient</label>
                        <input type="number" name="coefficient" min="1" class="form-control" <?= !$isAdmin && !$isTeacher ? 'disabled' : '' ?> required>
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <button type="submit" class="btn btn-success me-2" id="submitBtn" <?= !$isAdmin && !$isTeacher ? 'disabled' : '' ?>>
                            <i class="fas fa-plus"></i> Ajouter
                        </button>
                        <button type="button" class="btn btn-secondary" id="cancelBtn" style="display:none;" <?= !$isAdmin && !$isTeacher ? 'disabled' : '' ?>>
                            <i class="fas fa-times"></i> Annuler
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Tableau -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-list-ul me-2"></i>Liste des modules</h5>
            <span class="badge"><?= $total_items ?> module(s)</span>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th width="5%">#</th>
                            <th width="30%">Module</th>
                            <th width="30%">Classe</th>
                            <th width="15%">Coefficient</th>
                            <th width="20%" class="text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($modules)): ?>
                        <tr>
                            <td colspan="5" class="text-center py-4 text-muted">
                                <i class="fas fa-exclamation-circle me-2"></i>Aucun module trouvé
                            </td>
                        </tr>
                        <?php else: 
                        $start_num = ($page - 1) * $items_par_page + 1;
                        foreach ($modules as $i => $m): ?>
                        <tr>
                            <td><?= $start_num + $i ?></td>
                            <td><?= htmlspecialchars($m['nom']) ?></td>
                            <td><?= htmlspecialchars($m['classe_nom']) ?></td>
                            <td><?= $m['coefficient'] ?></td>
                            <td class="text-center action-buttons">
                                <button class="btn btn-sm btn-primary me-2" 
                                        onclick="editModule(<?= $m['id'] ?>, '<?= htmlspecialchars(addslashes($m['nom'])) ?>', <?= $m['classe_id'] ?>, <?= $m['coefficient'] ?>)" 
                                        <?= !$isAdmin && !$isTeacher ? 'disabled' : '' ?>>
                                    <i class="fas fa-edit me-1"></i> Modifier
                                </button>
                                <button class="btn btn-sm btn-danger" 
                                        onclick="confirmDelete(<?= $m['id'] ?>)" 
                                        <?= !$isAdmin ? 'disabled' : '' ?>>
                                    <i class="fas fa-trash me-1"></i> Supprimer
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="card-footer">
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center mb-0">
                    <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                        <a class="page-link" href="?page=<?= $page - 1 ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    
                    <?php 
                    // Afficher un nombre limité de pages autour de la page courante
                    $start_page = max(1, $page - 2);
                    $end_page = min($total_pages, $page + 2);
                    
                    if ($start_page > 1) {
                        echo '<li class="page-item"><a class="page-link" href="?page=1">1</a></li>';
                        if ($start_page > 2) {
                            echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                        }
                    }
                    
                    for ($i = $start_page; $i <= $end_page; $i++): ?>
                    <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                        <a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a>
                    </li>
                    <?php endfor;
                    
                    if ($end_page < $total_pages) {
                        if ($end_page < $total_pages - 1) {
                            echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                        }
                        echo '<li class="page-item"><a class="page-link" href="?page='.$total_pages.'">'.$total_pages.'</a></li>';
                    }
                    ?>
                    
                    <li class="page-item <?= $page >= $total_pages ? 'disabled' : '' ?>">
                        <a class="page-link" href="?page=<?= $page + 1 ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
            <div class="text-center text-muted mt-2">
                Page <?= $page ?> sur <?= $total_pages ?> | Total: <?= $total_items ?> modules
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Édition d'un module
function editModule(id, nom, classeId, coefficient) {
    // Mettre à jour le formulaire avec les valeurs du module
    document.getElementById('action').value = 'edit';
    document.getElementById('modId').value = id;
    document.querySelector('input[name="nomModule"]').value = nom;
    document.querySelector('select[name="classe"]').value = classeId;
    document.querySelector('input[name="coefficient"]').value = coefficient;
    
    // Changer le texte et le style du bouton de soumission
    const submitBtn = document.getElementById('submitBtn');
    submitBtn.innerHTML = '<i class="fas fa-save me-1"></i> Enregistrer';
    submitBtn.classList.remove('btn-success');
    submitBtn.classList.add('btn-primary');
    
    // Afficher le bouton d'annulation
    document.getElementById('cancelBtn').style.display = 'inline-block';
    
    // Faire défiler vers le formulaire
    document.getElementById('modForm').scrollIntoView({behavior: 'smooth'});
}

// Réinitialiser le formulaire
function resetForm() {
    document.getElementById('modForm').reset();
    document.getElementById('action').value = 'add';
    document.getElementById('modId').value = '';
    
    // Remettre le bouton en mode "Ajouter"
    const submitBtn = document.getElementById('submitBtn');
    submitBtn.innerHTML = '<i class="fas fa-plus me-1"></i> Ajouter';
    submitBtn.classList.remove('btn-primary');
    submitBtn.classList.add('btn-success');
    
    // Cacher le bouton d'annulation
    document.getElementById('cancelBtn').style.display = 'none';
    
    // Faire défiler vers le formulaire
    document.getElementById('modForm').scrollIntoView({behavior: 'smooth'});
}

// Annuler l'édition
document.getElementById('cancelBtn').addEventListener('click', resetForm);

// Confirmation de suppression
function confirmDelete(id) {
    Swal.fire({
        title: 'Confirmer la suppression',
        text: "Cette action est irréversible!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#1E88E5',
        confirmButtonText: 'Oui, supprimer',
        cancelButtonText: 'Annuler',
        backdrop: true
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = '?delete=' + id;
        }
    });
}

// Désactiver la soumission si non autorisé
document.getElementById('modForm').addEventListener('submit', function(e) {
    if (<?= !$isAdmin && !$isTeacher ? 'true' : 'false' ?>) {
        e.preventDefault();
        Swal.fire({
            title: 'Erreur',
            text: 'Vous n\'avez pas les permissions nécessaires',
            icon: 'error',
            confirmButtonColor: '#2E8B57'
        });
    }
});
</script>
</body>
</html>