<?php
session_start();
include 'config/connexion.php';

$message = '';
$agent = isset($_SESSION['user_name']) ? $_SESSION['user_name'] : 'inconnu';
$today = date('Y-m-d');

// Traitement Effectué
if (isset($_POST['effectuer_id'])) {
    $id = intval($_POST['effectuer_id']);
    $stmt = $conn->prepare("DELETE FROM rappels_table WHERE id = ? AND agent = ?");
    $stmt->bind_param("is", $id, $agent);
    $stmt->execute();
    $stmt->close();
    header('Location: rappels.php');
    exit;
}

// Traitement Reporter
if (isset($_POST['reporter_id'], $_POST['nouvelle_date'])) {
    $id = intval($_POST['reporter_id']);
    $nouvelle_date = $_POST['nouvelle_date'];
    $stmt = $conn->prepare("UPDATE rappels_table SET date_rappel = ? WHERE id = ? AND agent = ?");
    $stmt->bind_param("sis", $nouvelle_date, $id, $agent);
    $stmt->execute();
    $stmt->close();
    header('Location: rappels.php');
    exit;
}

// Traitement ajout rappel
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['date_rappel'], $_POST['objet'])) {
    $date_rappel = $_POST['date_rappel'];
    $objet = trim($_POST['objet']);
    if ($date_rappel && $objet) {
        $stmt = $conn->prepare("INSERT INTO rappels_table (date_rappel, objet, agent) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $date_rappel, $objet, $agent);
        if ($stmt->execute()) {
            $message = "Rappel enregistré avec succès.";
        } else {
            $message = "Erreur lors de l'enregistrement.";
        }
        $stmt->close();
    } else {
        $message = "Veuillez remplir tous les champs.";
    }
}

// Filtre: affichage des rappels expirés si demandé
$filter = isset($_GET['filter']) ? $_GET['filter'] : '';
if ($filter === 'expired') {
  $res = $conn->prepare("SELECT id, date_rappel, objet, agent FROM rappels_table WHERE agent = ? AND date_rappel < ? ORDER BY date_rappel ASC, id DESC");
  $res->bind_param("ss", $agent, $today);
} else {
  // Récupérer tous les rappels de l'utilisateur connecté
  $res = $conn->prepare("SELECT id, date_rappel, objet, agent FROM rappels_table WHERE agent = ? ORDER BY date_rappel DESC, id DESC");
  $res->bind_param("s", $agent);
}
$res->execute();
$res->bind_result($id, $date_rappel, $objet, $agent_result);
$rappels = [];
while ($res->fetch()) {
    $rappels[] = [
        'id' => $id,
        'date_rappel' => $date_rappel,
        'objet' => $objet,
        'agent' => $agent_result
    ];
}
$res->close();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <?php include('includes/head.php'); ?>
    <title>Gestion des rappels</title>
</head>
<body id="page-top">
<div id="wrapper">
    <?php include('includes/sidebar.php'); ?>
    <div id="content-wrapper" class="d-flex flex-column">
        <div id="content">
            <?php include('includes/topbar.php'); ?>
            <div class="container-fluid" id="container-wrapper">
                <div class="d-sm-flex align-items-center justify-content-between mb-4">
                    <h1 class="h3 mb-0 text-gray-800">Gestion des rappels</h1>
                </div>
                <?php if ($message): ?>
                    <div class="alert alert-info"><?php echo htmlspecialchars($message); ?></div>
                <?php endif; ?>
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Ajouter un rappel</h6>
                    </div>
                    <div class="card-body">
                        <form method="post" class="row g-3">
                            <div class="form-group col-md-4">
                                <label for="date_rappel">Date du rappel</label>
                                <input type="date" class="form-control" name="date_rappel" id="date_rappel" required>
                            </div>
                            <div class="form-group col-md-6">
                                <label for="objet">Objet du rappel</label>
                                <input type="text" class="form-control" name="objet" id="objet" required maxlength="255">
                            </div>
                            <div class="form-group col-md-2 align-self-end">
                                <button type="submit" class="btn btn-primary">Enregistrer</button>
                            </div>
                        </form>
                    </div>
                </div>
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Liste des rappels <?php echo ($filter==='expired')? '- Rappels expirés' : ''; ?></h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="rappelsTable" class="table table-bordered table-hover">
                                <thead class="thead-light">
                                    <tr>
                                        <th>Date</th>
                                        <th>Objet</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <?php if ($rappels): foreach ($rappels as $rappel): ?>
                                    <?php $isExpired = (strtotime($rappel['date_rappel']) < strtotime($today)); ?>
                                    <tr class="<?php echo $isExpired ? 'table-danger' : ''; ?>">
                                        <td>
                                          <?php echo date('d/m/Y', strtotime($rappel['date_rappel'])); ?>
                                          <?php if ($isExpired): ?>
                                            <span class="badge badge-danger ml-2"><i class="fas fa-exclamation-circle"></i> Expiré</span>
                                          <?php endif; ?>
                                        </td>
                                        <td><?php echo htmlspecialchars($rappel['objet']); ?></td>
                                        <td class="d-flex align-items-center">
                                          <?php if (!$isExpired): ?>
                                            <form method="post" class="effectuer-form" style="display:inline;">
                                                <input type="hidden" name="effectuer_id" value="<?php echo $rappel['id']; ?>">
                                                <button type="button" class="btn btn-success btn-sm btn-effectuer" data-id="<?php echo $rappel['id']; ?>">Effectué</button>
                                            </form>
                                            <button type="button" class="btn btn-warning btn-sm ml-2" data-toggle="modal" data-target="#reporterModal" data-id="<?php echo $rappel['id']; ?>" data-date="<?php echo htmlspecialchars($rappel['date_rappel']); ?>">Reporter</button>
                                          <?php else: ?>
                                            <form method="post" class="ml-2" onsubmit="return confirm('Supprimer ce rappel ?');">
                                              <input type="hidden" name="effectuer_id" value="<?php echo $rappel['id']; ?>">
                                              <button type="submit" class="btn btn-danger btn-sm" title="Supprimer"><i class="fas fa-trash"></i></button>
                                            </form>
                                          <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; endif; ?>
                                </tbody>
                        <!-- Modal Effectué (global) -->
                        <div class="modal fade" id="effectuerModal" tabindex="-1" role="dialog" aria-labelledby="effectuerModalLabel" aria-hidden="true">
                          <div class="modal-dialog" role="document">
                            <div class="modal-content">
                              <div class="modal-header">
                                <h5 class="modal-title" id="effectuerModalLabel">Confirmer l'action</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                  <span aria-hidden="true">&times;</span>
                                </button>
                              </div>
                              <div class="modal-body">
                                <div id="rappelDetails" class="mb-2"></div>
                                Êtes-vous sûr de vouloir marquer ce rappel comme effectué ?
                              </div>
                              <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button>
                                <button type="button" id="confirmEffectuer" class="btn btn-success">Confirmer</button>
                              </div>
                            </div>
                          </div>
                        </div>

                        <!-- Modal Reporter (global) -->
                        <div class="modal fade" id="reporterModal" tabindex="-1" role="dialog" aria-labelledby="reporterModalLabel" aria-hidden="true">
                          <div class="modal-dialog" role="document">
                            <div class="modal-content">
                              <form method="post">
                                <div class="modal-header">
                                  <h5 class="modal-title" id="reporterModalLabel">Reporter le rappel</h5>
                                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                  </button>
                                </div>
                                <div class="modal-body">
                                  <input type="hidden" name="reporter_id" id="reporter_id">
                                  <div class="form-group">
                                    <label for="nouvelle_date">Nouvelle date</label>
                                    <input type="date" class="form-control" name="nouvelle_date" id="nouvelle_date" required>
                                  </div>
                                </div>
                                <div class="modal-footer">
                                  <button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button>
                                  <button type="submit" class="btn btn-primary">Enregistrer</button>
                                </div>
                              </form>
                            </div>
                          </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <?php include('includes/footer.php'); ?>
    </div>
</div>
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<script src="js/ruang-admin.min.js"></script>
<!-- DataTables -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
  $('#rappelsTable').DataTable({
    language: {
      url: '//cdn.datatables.net/plug-ins/1.13.7/i18n/fr-FR.json'
    },
    order: [[0, 'desc']]
  });

  $('#reporterModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var id = button.data('id');
    var date = button.data('date');
    var modal = $(this);
    modal.find('#reporter_id').val(id);
    modal.find('#nouvelle_date').val(date);
  });

  // Gestion du bouton Effectué avec confirmation et affichage des détails
  let formToSubmit = null;
  $('.btn-effectuer').on('click', function() {
    formToSubmit = $(this).closest('form');
    // Chercher la ligne du rappel
    var row = $(this).closest('tr');
    var date = row.find('td').eq(0).text();
    var objet = row.find('td').eq(1).text();
    // Afficher les détails dans le modal
    var detailsHtml = '<strong>Date :</strong> ' + date + '<br><strong>Objet :</strong> ' + objet;
    $('#rappelDetails').html(detailsHtml);
    $('#effectuerModal').modal('show');
  });
  $('#confirmEffectuer').on('click', function() {
    if (formToSubmit) {
      formToSubmit.submit();
    }
    $('#effectuerModal').modal('hide');
  });
});
</script>
</body>
</html>
