<?php
declare(strict_types=1);
require_once __DIR__ . "/../config/database.php";
require_once __DIR__ . "/../includes/auth.php";
require_once __DIR__ . "/../includes/helpers.php";
requireAuth();

$q = trim($_GET["q"] ?? "");
$export = $_GET["export"] ?? "";
$editId = (int) ($_GET["edit"] ?? 0);
$editInscription = null;
if ($editId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM inscriptions WHERE id = :id");
    $stmt->execute(["id" => $editId]);
    $editInscription = $stmt->fetch();
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    requireAdminOrSecretaire();
    $action = $_POST["action"] ?? "create";
    $stagiaireId = (int) ($_POST["stagiaire_id"] ?? 0);
    $formationId = (int) ($_POST["formation_id"] ?? 0);
    $date = $_POST["date_inscription"] ?? date("Y-m-d");

    if ($action === "create" && $stagiaireId > 0 && $formationId > 0) {
        $stmt = $pdo->prepare(
            "INSERT INTO inscriptions (stagiaire_id, formation_id, date_inscription)
             VALUES (:stagiaire_id, :formation_id, :date_inscription)"
        );
        $stmt->execute([
            "stagiaire_id" => $stagiaireId,
            "formation_id" => $formationId,
            "date_inscription" => $date,
        ]);
        setFlash("success", "Inscription enregistree.");
    }
    if ($action === "update") {
        $id = (int) ($_POST["id"] ?? 0);
        $stmt = $pdo->prepare("UPDATE inscriptions SET stagiaire_id=:stagiaire_id, formation_id=:formation_id, date_inscription=:date_inscription WHERE id=:id");
        $stmt->execute([
            "stagiaire_id" => $stagiaireId,
            "formation_id" => $formationId,
            "date_inscription" => $date,
            "id" => $id,
        ]);
        setFlash("success", "Inscription modifiee.");
    }
    redirect("/PIS/inscriptions/index.php");
}

if (isset($_GET["delete"])) {
    requireAdminOrSecretaire();
    $id = (int) $_GET["delete"];
    $stmt = $pdo->prepare("DELETE FROM inscriptions WHERE id = :id");
    $stmt->execute(["id" => $id]);
    setFlash("success", "Inscription supprimee.");
    redirect("/PIS/inscriptions/index.php");
}

$stagiaires = $pdo->query("SELECT id, CONCAT(nom, ' ', prenoms) AS nom_complet FROM stagiaires ORDER BY nom, prenoms")->fetchAll();
$formations = $pdo->query("SELECT id, titre FROM formations ORDER BY titre")->fetchAll();
$sql = "SELECT i.id, CONCAT(s.nom, ' ', s.prenoms) AS stagiaire, f.titre AS formation, i.date_inscription
     FROM inscriptions i
     JOIN stagiaires s ON i.stagiaire_id = s.id
     JOIN formations f ON i.formation_id = f.id";
$params = [];
if ($q !== "") {
    $sql .= " WHERE s.nom LIKE :q OR s.prenoms LIKE :q OR f.titre LIKE :q OR i.date_inscription LIKE :q";
    $params["q"] = "%{$q}%";
}
$sql .= " ORDER BY i.id DESC";
$countSql = "SELECT COUNT(*) FROM inscriptions i
     JOIN stagiaires s ON i.stagiaire_id = s.id
     JOIN formations f ON i.formation_id = f.id";
if ($q !== "") {
    $countSql .= " WHERE s.nom LIKE :q OR s.prenoms LIKE :q OR f.titre LIKE :q OR i.date_inscription LIKE :q";
}
$countStmt = $pdo->prepare($countSql);
$countStmt->execute($params);
$totalRows = (int) $countStmt->fetchColumn();
$pagination = paginate($totalRows, 8);
$sql .= " LIMIT :limit OFFSET :offset";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(":limit", $pagination["perPage"], PDO::PARAM_INT);
$stmt->bindValue(":offset", $pagination["offset"], PDO::PARAM_INT);
foreach ($params as $k => $v) {
    $stmt->bindValue(":{$k}", $v);
}
$stmt->execute();
$inscriptions = $stmt->fetchAll();

if ($export === "csv") {
    $rows = [];
    foreach ($inscriptions as $i) {
        $rows[] = [$i["stagiaire"], $i["formation"], $i["date_inscription"]];
    }
    exportCsv("inscriptions.csv", ["Apprenant", "Formation", "Date"], $rows);
}
require_once __DIR__ . "/../includes/header.php";
?>
<h2>Gestion des inscriptions</h2>
<form method="GET">
    <input type="text" name="q" value="<?= htmlspecialchars($q) ?>" placeholder="Rechercher une inscription">
    <button type="submit">Rechercher</button>
</form>
<div class="actions">
    <a href="/PIS/inscriptions/index.php?<?= http_build_query(["q" => $q, "export" => "csv"]) ?>">Exporter Excel (CSV)</a>
    <a href="/PIS/exports/print_inscriptions.php?<?= http_build_query(["q" => $q]) ?>" target="_blank">Exporter PDF</a>
</div>
<?php if (hasRole(["admin", "secretaire"])): ?>
<form method="POST">
    <input type="hidden" name="action" value="<?= $editInscription ? "update" : "create" ?>">
    <?php if ($editInscription): ?><input type="hidden" name="id" value="<?= (int) $editInscription["id"] ?>"><?php endif; ?>
    <select name="stagiaire_id" required>
        <option value="">Choisir un apprenant</option>
        <?php foreach ($stagiaires as $s): ?>
            <option value="<?= (int) $s["id"] ?>" <?= (int) ($editInscription["stagiaire_id"] ?? 0) === (int) $s["id"] ? "selected" : "" ?>><?= htmlspecialchars($s["nom_complet"]) ?></option>
        <?php endforeach; ?>
    </select>
    <select name="formation_id" required>
        <option value="">Choisir une formation</option>
        <?php foreach ($formations as $f): ?>
            <option value="<?= (int) $f["id"] ?>" <?= (int) ($editInscription["formation_id"] ?? 0) === (int) $f["id"] ? "selected" : "" ?>><?= htmlspecialchars($f["titre"]) ?></option>
        <?php endforeach; ?>
    </select>
    <input type="date" name="date_inscription" value="<?= htmlspecialchars((string) ($editInscription["date_inscription"] ?? date("Y-m-d"))) ?>" required>
    <button type="submit"><?= $editInscription ? "Mettre a jour" : "Enregistrer l'inscription" ?></button>
</form>
<?php else: ?>
    <!-- <p class="subtitle">Vous pouvez consulter les inscriptions, mais vous n'avez pas le droit de modifier ou d'ajouter.</p> -->
<?php endif; ?>
<div class="table-wrap">
<table>
    <thead>
    <tr>
        <th>Apprenant</th>
        <th>Formation</th>
        <th>Date</th>
        <th>Action</th>
    </tr>
    </thead>
    <tbody>
    <?php foreach ($inscriptions as $i): ?>
        <tr>
            <td><?= htmlspecialchars($i["stagiaire"]) ?></td>
            <td><?= htmlspecialchars($i["formation"]) ?></td>
            <td><?= htmlspecialchars($i["date_inscription"]) ?></td>
            <td class="actions">
                <?php if (hasRole(["admin", "secretaire"])): ?>
                    <a href="/PIS/inscriptions/index.php?edit=<?= (int) $i["id"] ?>">Modifier</a>
                    <a class="btn-danger"
                       href="/PIS/inscriptions/index.php?delete=<?= (int) $i["id"] ?>"
                       onclick="return confirm('Supprimer cette inscription ?');">Supprimer</a>
                <?php else: ?>
                    &mdash;
                <?php endif; ?>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>
<?= renderPagination($pagination["page"], $pagination["totalPages"], "/PIS/inscriptions/index.php", ["q" => $q]) ?>
<?php require_once __DIR__ . "/../includes/footer.php"; ?>
