<?php
declare(strict_types=1);
require_once __DIR__ . "/../config/database.php";
require_once __DIR__ . "/../includes/auth.php";
require_once __DIR__ . "/../includes/helpers.php";
requireAuth();
if (!hasRole(["admin", "secretaire"])) {
    header("Location: /PIS/attestations/list.php");
    exit;
}

$formations = $pdo->query("SELECT id, titre FROM formations ORDER BY titre")->fetchAll();
$stagiaires = $pdo->query("SELECT id, nom, prenoms FROM stagiaires ORDER BY nom, prenoms")->fetchAll();
require_once __DIR__ . "/../includes/header.php";
?>
<h2>Production des attestations</h2>
<p>Generez des attestations en lot pour tous les apprenants, pour un module de formation, ou par personne.</p>

<?php if (hasRole(["admin", "secretaire"])): ?>
    <form method="GET" action="/PIS/attestations/print.php" target="_blank">
        <select name="mode" required>
            <option value="all">Tous les apprenants inscrits</option>
            <option value="module">Par module de formation</option>
            <option value="person">Par personne</option>
            <option value="date">Par date d'inscription</option>
        </select>
        <select name="formation_id">
            <option value="">Choisir un module (pour mode = module ou date)</option>
            <?php foreach ($formations as $f): ?>
                <option value="<?= (int) $f["id"] ?>"><?= htmlspecialchars($f["titre"]) ?></option>
            <?php endforeach; ?>
        </select>
        <input type="date" name="date_debut" placeholder="Date debut">
        <input type="date" name="date_fin" placeholder="Date fin">
        <label for="stagiaireInput" style="position:absolute;left:-9999px;top:auto;width:1px;height:1px;overflow:hidden;">Choisir une personne</label>
        <input type="text" id="stagiaireInput" list="stagiaireList" placeholder="Choisir une personne (si mode = personne)" autocomplete="off">
        <datalist id="stagiaireList">
            <?php foreach ($stagiaires as $s): ?>
                <?php $stagiaireName = trim(((string) ($s["nom"] ?? "")) . " " . ((string) ($s["prenoms"] ?? ""))); ?>
                <option value="<?= htmlspecialchars($stagiaireName) ?>" data-id="<?= (int) $s["id"] ?>"></option>
            <?php endforeach; ?>
        </datalist>
        <input type="hidden" name="stagiaire_id" id="stagiaireId" value="">
        <input type="text" name="signataire" placeholder="Nom du signataire (manuel)">
        <button type="submit">Generer les attestations</button>
    </form>
<?php endif; ?>
<script>
    (function () {
        var stagiaireInput = document.getElementById("stagiaireInput");
        var stagiaireId = document.getElementById("stagiaireId");
        var stagiaireList = document.getElementById("stagiaireList");
        if (!stagiaireInput || !stagiaireId || !stagiaireList) {
            return;
        }

        var mapping = {};
        Array.from(stagiaireList.querySelectorAll("option")).forEach(function (option) {
            var name = option.value;
            var id = option.getAttribute("data-id");
            if (name && id) {
                mapping[name] = id;
            }
        });

        stagiaireInput.addEventListener("input", function () {
            var value = stagiaireInput.value.trim();
            if (mapping[value]) {
                stagiaireId.value = mapping[value];
            } else {
                stagiaireId.value = "";
            }
        });
    })();
</script>
<?php require_once __DIR__ . "/../includes/footer.php"; ?>
