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

<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <title>Gestion des vacations</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body class="p-4">

<h3 class="mb-4">Gestion des vacations</h3>

<!-- Bouton Ajouter -->
<button class="btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#ajoutVacationModal">
  Ajouter une vacation
</button>

<!-- Modal Ajout -->
<div class="modal fade" id="ajoutVacationModal" tabindex="-1">
  <div class="modal-dialog">
    <form method="POST" action="">
      <div class="modal-content">
        <div class="modal-header"><h5 class="modal-title">Nouvelle vacation</h5></div>
        <div class="modal-body">
          <div class="mb-2">
            <label>Professeur</label>
            <select name="enseignant_id" class="form-select" required>
              <option value="">Sélectionner</option>
              <?php
              $ens = $conn->query("SELECT * FROM enseignants");
              while($e = $ens->fetch()){ echo "<option value='{$e['id']}'>{$e['nom']} {$e['prenom']}</option>"; }
              ?>
            </select>
          </div>
          <div class="mb-2">
            <label>Classe</label>
            <select name="classe_id" class="form-select" required>
              <option value="">Sélectionner</option>
              <?php
              $cls = $conn->query("SELECT * FROM classes");
              while($c = $cls->fetch()){ echo "<option value='{$c['id']}'>{$c['nom_classe']}</option>"; }
              ?>
            </select>
          </div>
          <div class="mb-2">
            <label>Date du cours</label>
            <input type="date" name="date_cours" class="form-control" required>
          </div>
          <div class="mb-2">
            <label>Heure d’arrivée</label>
            <input type="time" name="heure_arrivee" class="form-control" required>
          </div>
          <div class="mb-2">
            <label>Heures effectuées</label>
            <input type="number" name="heures" step="0.25" class="form-control" required>
          </div>
          <div class="mb-2">
            <label>Mois</label>
            <input type="month" name="mois" class="form-control" required>
          </div>
          <div class="mb-2">
            <label>Taux horaire (FCFA)</label>
            <input type="number" name="taux_horaire" class="form-control" required>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-success" name="ajouter_vacation">Ajouter</button>
        </div>
      </div>
    </form>
  </div>
</div>

<?php
// Ajout
if (isset($_POST['ajouter_vacation'])) {
  extract($_POST);
  $revenu = $heures * $taux_horaire;
  $stmt = $conn->prepare("INSERT INTO vacations (enseignant_id, classe_id, date_cours, heure_arrivee, heures, mois, taux_horaire, revenu) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
  $stmt->execute([$enseignant_id, $classe_id, $date_cours, $heure_arrivee, $heures, $mois, $taux_horaire, $revenu]);
  echo "<script>Swal.fire('Succès','Vacation ajoutée','success');</script>";
}
?>

<!-- Tableau -->
<table class="table table-bordered table-striped">
  <thead>
    <tr>
      <th>Professeur</th>
      <th>Classe</th>
      <th>Date</th>
      <th>Heure arrivée</th>
      <th>Heures</th>
      <th>Mois</th>
      <th>Revenu</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody>
    <?php
    $req = $conn->query("SELECT v.*, e.nom, e.prenom, c.nom_classe FROM vacations v 
                         JOIN enseignants e ON v.enseignant_id = e.id 
                         JOIN classes c ON v.classe_id = c.id 
                         ORDER BY v.date_cours DESC");
    while($v = $req->fetch()):
    ?>
    <tr>
      <td><?= $v['nom'].' '.$v['prenom'] ?></td>
      <td><?= $v['nom_classe'] ?></td>
      <td><?= $v['date_cours'] ?></td>
      <td><?= substr($v['heure_arrivee'], 0, 5) ?></td>
      <td><?= $v['heures'] ?></td>
      <td><?= $v['mois'] ?></td>
      <td><?= number_format($v['revenu'], 0, ',', ' ') ?> FCFA</td>
      <td>
        <button class="btn btn-sm btn-warning" onclick="openEditModal(<?= htmlspecialchars(json_encode($v)) ?>)">Modifier</button>
        <button class="btn btn-sm btn-danger" onclick="supprimerVacation(<?= $v['id'] ?>)">Supprimer</button>
        <button class="btn btn-sm btn-secondary" onclick="imprimerVacation(<?= htmlspecialchars(json_encode($v)) ?>)">Lettre</button>
      </td>
    </tr>
    <?php endwhile; ?>
  </tbody>
</table>

<!-- Modal Modification -->
<div class="modal fade" id="editModal" tabindex="-1">
  <div class="modal-dialog">
    <form method="POST" action="">
      <div class="modal-content">
        <div class="modal-header"><h5>Modifier la vacation</h5></div>
        <div class="modal-body">
          <input type="hidden" name="id" id="edit_id">
          <input type="time" name="heure_arrivee" id="edit_heure_arrivee" class="form-control mb-2" required>
          <input type="number" name="heures" id="edit_heures" step="0.25" class="form-control mb-2" required>
          <input type="number" name="taux_horaire" id="edit_taux" class="form-control mb-2" required>
        </div>
        <div class="modal-footer">
          <button class="btn btn-success" name="modifier_vacation">Enregistrer</button>
        </div>
      </div>
    </form>
  </div>
</div>

<?php
// Modification
if (isset($_POST['modifier_vacation'])) {
  extract($_POST);
  $revenu = $heures * $taux_horaire;
  $stmt = $conn->prepare("UPDATE vacations SET heure_arrivee=?, heures=?, taux_horaire=?, revenu=? WHERE id=?");
  $stmt->execute([$heure_arrivee, $heures, $taux_horaire, $revenu, $id]);
  echo "<script>Swal.fire('Modifié','Vacation mise à jour','success');</script>";
}
?>

<!-- JS -->
<script>
function openEditModal(vacation) {
  $('#edit_id').val(vacation.id);
  $('#edit_heure_arrivee').val(vacation.heure_arrivee);
  $('#edit_heures').val(vacation.heures);
  $('#edit_taux').val(vacation.taux_horaire);
  new bootstrap.Modal(document.getElementById('editModal')).show();
}

function supprimerVacation(id) {
  Swal.fire({
    title: 'Supprimer ?',
    icon: 'warning',
    showCancelButton: true,
    confirmButtonText: 'Oui',
    cancelButtonText: 'Non'
  }).then((res) => {
    if (res.isConfirmed) {
      $.post('', { delete_id: id }, function() {
        Swal.fire('Supprimé', '', 'success').then(() => location.reload());
      });
    }
  });
}

function imprimerVacation(data) {
  let win = window.open('', '', 'width=800,height=600');
  win.document.write(`
    <h4>Lettre de vacation</h4>
    <p><strong>Professeur:</strong> ${data.nom} ${data.prenom}</p>
    <p><strong>Classe:</strong> ${data.nom_classe}</p>
    <p><strong>Date du cours:</strong> ${data.date_cours}</p>
    <p><strong>Heure d'arrivée:</strong> ${data.heure_arrivee}</p>
    <p><strong>Durée:</strong> ${data.heures} heures</p>
    <p><strong>Taux horaire:</strong> ${data.taux_horaire} FCFA</p>
    <p><strong>Revenu:</strong> ${data.revenu} FCFA</p>
    <hr><p>Signature du Directeur</p>
  `);
  win.document.close();
  win.print();
}
</script>

<?php
// Suppression
if (isset($_POST['delete_id'])) {
  $conn->prepare("DELETE FROM vacations WHERE id=?")->execute([$_POST['delete_id']]);
  exit;
}
?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
