<?php 
session_start();
$userprofil = $_SESSION['user'] ?? null;
$role = $userprofil['role'] ?? 'caissier';

if (!$userprofil) {
    header("Location: login.php");
    exit();
}

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

$flash = '';
if (isset($_GET['updated']) && $_GET['updated'] == '1') {
    $flash = "L'enseignant a été modifié avec succès.";
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($role !== 'admin') {
        echo json_encode(['success' => false, 'error' => 'Accès non autorisé']);
        exit;
    }
    $id = intval($_POST['id']);
    if ($_POST['action'] === 'delete') {
        $stmt = $conn->prepare("DELETE FROM enseignants WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        echo json_encode(['success' => true]);
        exit;
    } elseif ($_POST['action'] === 'update') {
        $nom = trim($_POST['nom']);
        $prenom = trim($_POST['prenom']);
        $email = trim($_POST['email']);
        $telephone = trim($_POST['telephone']);
        $matiere = trim($_POST['matiere']);
        $grade = trim($_POST['grade']);
        if ($nom && $prenom && $email && $matiere && $grade) {
            $stmt = $conn->prepare("UPDATE enseignants SET nom=?, prenom=?, email=?, telephone=?, matiere=?, grade=? WHERE id=?");
            $stmt->bind_param("ssssssi", $nom, $prenom, $email, $telephone, $matiere, $grade, $id);
            $stmt->execute();
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Champs manquants.']);
        }
        exit;
    }
}

// Pagination configuration
$itemsPerPage = 10;
$currentPage = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($currentPage - 1) * $itemsPerPage;

// Get total count of teachers
$countResult = $conn->query("SELECT COUNT(*) as total FROM enseignants");
$totalItems = $countResult->fetch_assoc()['total'];
$totalPages = ceil($totalItems / $itemsPerPage);

// Get teachers for current page
$result = $conn->query("SELECT * FROM enseignants ORDER BY date_ajout DESC LIMIT $offset, $itemsPerPage");
$enseignants = $result->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <title>Gestion des enseignants</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <style>
    :root {
      --primary-color: #1a5276; /* Bleu foncé */
      --secondary-color: #27ae60; /* Vert */
      --accent-color: #e74c3c; /* Rouge pour les actions dangereuses */
      --cream: #f8f9fa;
      --gray-light: #e9ecef;
    }
    body {
      background-color: var(--cream);
      font-family: 'Roboto', sans-serif;
    }
    .title-container {
      background-color: white;
      padding: 1.5rem;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
      margin-bottom: 2rem;
      border-left: 5px solid var(--primary-color);
    }
    .page-title {
      color: var(--primary-color);
      font-weight: 600;
      margin: 0;
    }
    .card {
      border: none;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.08);
      margin-bottom: 2rem;
    }
    .card-header {
      background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
      color: white;
      font-weight: 500;
      border-radius: 8px 8px 0 0 !important;
      padding: 1rem 1.5rem;
    }
    .table {
      margin-bottom: 0;
    }
    .table th {
      background-color: var(--primary-color) !important;
      color: white;
      font-weight: 500;
      text-align: center;
      vertical-align: middle;
      padding: 1rem;
    }
    .table td {
      vertical-align: middle;
      padding: 0.75rem 1rem;
    }
    .table tr:nth-child(even) {
      background-color: rgba(26, 82, 118, 0.03);
    }
    .table tr:hover {
      background-color: rgba(26, 82, 118, 0.08);
    }
    .btn-edit {
      background-color: var(--primary-color);
      color: white;
      border: none;
      border-radius: 4px;
      padding: 0.35rem 0.75rem;
    }
    .btn-edit:hover {
      background-color: #154360;
      color: white;
    }
    .btn-delete {
      background-color: var(--accent-color);
      color: white;
      border: none;
      border-radius: 4px;
      padding: 0.35rem 0.75rem;
    }
    .btn-delete:hover {
      background-color: #c0392b;
      color: white;
    }
    .badge-access {
      background-color: var(--gray-light);
      color: #6c757d;
      font-weight: normal;
      font-size: 0.75rem;
    }
    .alert-success {
      background-color: rgba(39, 174, 96, 0.15);
      border-left: 4px solid var(--secondary-color);
    }
    .modal-header {
      background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
      color: white;
    }
    .btn-primary {
      background-color: var(--primary-color);
      border: none;
    }
    .btn-primary:hover {
      background-color: #154360;
    }
    .form-control:focus, .form-select:focus {
      border-color: var(--primary-color);
      box-shadow: 0 0 0 0.25rem rgba(26, 82, 118, 0.25);
    }
    .pagination .page-item.active .page-link {
      background-color: var(--primary-color);
      border-color: var(--primary-color);
    }
    .pagination .page-link {
      color: var(--primary-color);
    }
    .pagination .page-item.disabled .page-link {
      color: #6c757d;
    }
    .btn-add {
      background-color: var(--secondary-color);
      border: none;
    }
    .btn-add:hover {
      background-color: #219653;
    }
  </style>
</head>
<body>
<div class="container py-4">
  <div class="title-container">
    <div class="d-flex justify-content-between align-items-center">
      <h1 class="page-title"><i class="bi bi-person-video3 me-2"></i>Gestion des enseignants</h1>
      <?php if ($role === 'admin'): ?>
        <a href="ajout_prof.php" class="btn btn-add text-white">
          <i class="bi bi-plus-circle"></i> Ajouter un enseignant
        </a>
      <?php endif; ?>
    </div>
  </div>

  <?php if ($flash): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
      <i class="bi bi-check-circle-fill me-2"></i>
      <?= htmlspecialchars($flash) ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
  <?php endif; ?>

  <div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
      <div><i class="bi bi-list-ul me-2"></i>Liste des enseignants</div>
      <div class="text-white">
        <?= ($offset + 1) ?> - <?= min($offset + $itemsPerPage, $totalItems) ?> sur <?= $totalItems ?>
      </div>
    </div>
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-hover mb-0">
          <thead>
            <tr>
              <th width="5%">ID</th>
              <th width="15%">Nom</th>
              <th width="15%">Prénom</th>
              <th width="20%">Email</th>
              <th width="12%">Téléphone</th>
              <th width="15%">Matière</th>
              <th width="10%">Grade</th>
              <th width="8%">Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php $isAdmin = ($role === 'admin');
            if (empty($enseignants)): ?>
              <tr>
                <td colspan="8" class="text-center py-4 text-muted">
                  <i class="bi bi-exclamation-circle me-2"></i>Aucun enseignant enregistré
                </td>
              </tr>
            <?php else: foreach ($enseignants as $e): ?>
              <tr id="row-<?= $e['id'] ?>">
                <td class="text-center"><?= $e['id'] ?></td>
                <td><?= htmlspecialchars($e['nom']) ?></td>
                <td><?= htmlspecialchars($e['prenom']) ?></td>
                <td><?= htmlspecialchars($e['email']) ?></td>
                <td><?= htmlspecialchars($e['telephone']) ?></td>
                <td><?= htmlspecialchars($e['matiere']) ?></td>
                <td><?= htmlspecialchars($e['grade']) ?></td>
                <td class="text-center">
                  <div class="d-flex gap-2 justify-content-center">
                    <button class="btn btn-edit" <?= $isAdmin ? '' : 'disabled' ?> <?= $isAdmin ? "onclick='openEditModal(".json_encode($e).")'" : '' ?>>
                      <i class="bi bi-pencil-square"></i>
                    </button>
                    <button class="btn btn-delete" <?= $isAdmin ? '' : 'disabled' ?> <?= $isAdmin ? "onclick='deleteProf({$e['id']})'" : '' ?>>
                      <i class="bi bi-trash3"></i>
                    </button>
                  </div>
                  <?php if (!$isAdmin): ?>
                    <span class="badge badge-access mt-1">Accès restreint</span>
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>
      
      <!-- Pagination -->
      <?php if ($totalPages > 1): ?>
      <div class="card-footer">
        <nav aria-label="Page navigation">
          <ul class="pagination justify-content-center mb-0">
            <li class="page-item <?= $currentPage <= 1 ? 'disabled' : '' ?>">
              <a class="page-link" href="?page=<?= $currentPage - 1 ?>" aria-label="Previous">
                <span aria-hidden="true">&laquo;</span>
              </a>
            </li>
            
            <?php 
            // Show page numbers
            $startPage = max(1, $currentPage - 2);
            $endPage = min($totalPages, $currentPage + 2);
            
            // Always show first page
            if ($startPage > 1) {
                echo '<li class="page-item"><a class="page-link" href="?page=1">1</a></li>';
                if ($startPage > 2) {
                    echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                }
            }
            
            for ($i = $startPage; $i <= $endPage; $i++): ?>
              <li class="page-item <?= $i == $currentPage ? 'active' : '' ?>">
                <a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a>
              </li>
            <?php endfor;
            
            // Always show last page
            if ($endPage < $totalPages) {
                if ($endPage < $totalPages - 1) {
                    echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                }
                echo '<li class="page-item"><a class="page-link" href="?page='.$totalPages.'">'.$totalPages.'</a></li>';
            }
            ?>
            
            <li class="page-item <?= $currentPage >= $totalPages ? 'disabled' : '' ?>">
              <a class="page-link" href="?page=<?= $currentPage + 1 ?>" aria-label="Next">
                <span aria-hidden="true">&raquo;</span>
              </a>
            </li>
          </ul>
        </nav>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <form id="editForm" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="bi bi-pencil-square me-2"></i>Modifier l'enseignant</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="id" id="edit-id">
        <input type="hidden" name="action" value="update">
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label">Nom</label>
            <input type="text" name="nom" id="edit-nom" class="form-control" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Prénom</label>
            <input type="text" name="prenom" id="edit-prenom" class="form-control" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Email</label>
            <input type="email" name="email" id="edit-email" class="form-control" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Téléphone</label>
            <input type="tel" name="telephone" id="edit-telephone" class="form-control">
          </div>
          <div class="col-md-6">
            <label class="form-label">Matière</label>
            <input type="text" name="matiere" id="edit-matiere" class="form-control" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Grade</label>
            <select name="grade" id="edit-grade" class="form-select" required>
              <option value="">-- Sélectionner --</option>
              <option>Maître assistant</option>
              <option>Maître de conférences</option>
              <option>Professeur</option>
            </select>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          <i class="bi bi-x-circle me-1"></i> Annuler
        </button>
        <button type="submit" class="btn btn-primary">
          <i class="bi bi-check-circle me-1"></i> Enregistrer
        </button>
      </div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function deleteProf(id) {
  Swal.fire({
    title: 'Confirmer la suppression',
    text: "Êtes-vous sûr de vouloir supprimer cet enseignant ? Cette action est irréversible.",
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#1a5276',
    cancelButtonColor: '#6c757d',
    confirmButtonText: 'Oui, supprimer',
    cancelButtonText: 'Annuler',
    backdrop: true
  }).then(res => {
    if (res.isConfirmed) {
      fetch('', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({ action: 'delete', id })
      }).then(r => r.json()).then(data => {
        if (data.success) {
          document.getElementById('row-' + id).remove();
          Swal.fire({
            title: 'Supprimé!',
            text: "L'enseignant a été supprimé avec succès.",
            icon: 'success',
            confirmButtonColor: '#1a5276',
            timer: 2000
          });
          // Reload the page to update pagination
          setTimeout(() => window.location.reload(), 2000);
        } else {
          Swal.fire({
            title: 'Erreur',
            text: data.error || 'Une erreur est survenue.',
            icon: 'error',
            confirmButtonColor: '#1a5276'
          });
        }
      });
    }
  });
}

function openEditModal(data) {
  const modal = new bootstrap.Modal(document.getElementById('editModal'));
  for (const key of ['id','nom','prenom','email','telephone','matiere','grade']) {
    document.getElementById('edit-' + key).value = data[key] ?? '';
  }
  modal.show();
}

document.getElementById('editForm').addEventListener('submit', function (e) {
  e.preventDefault();
  const formData = new FormData(this);
  fetch('', {
    method: 'POST',
    body: new URLSearchParams(formData)
  }).then(r => r.json()).then(data => {
    if (data.success) {
      window.location.href = window.location.pathname + '?updated=1';
    } else {
      Swal.fire({
        title: 'Erreur',
        text: data.error || 'Une erreur est survenue lors de la mise à jour.',
        icon: 'error',
        confirmButtonColor: '#1a5276'
      });
    }
  });
});

// Auto-dismiss alerts
setTimeout(() => {
  const alert = document.querySelector('.alert');
  if (alert) {
    const bsAlert = bootstrap.Alert.getOrCreateInstance(alert);
    bsAlert.close();
  }
}, 5000);
</script>
</body>
</html>