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

// Rendre formateur optionnel et conserver l'integrite relationnelle.
try {
    $pdo->exec("ALTER TABLE formations DROP FOREIGN KEY fk_formations_formateur");
} catch (Throwable $e) {
}
try {
    $pdo->exec("ALTER TABLE formations MODIFY formateur_id INT NULL");
} catch (Throwable $e) {
}
try {
    $pdo->exec("ALTER TABLE formations ADD CONSTRAINT fk_formations_formateur FOREIGN KEY (formateur_id) REFERENCES formateurs(id) ON DELETE SET NULL");
} catch (Throwable $e) {
}

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

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (!isAdmin()) {
        setFlash("error", "Acces refuse.");
        redirect("/PIS/formations/index.php");
    }

    $action = $_POST["action"] ?? "create";
    $titre = normalize($_POST["titre"] ?? "");
    $duree = normalize($_POST["duree"] ?? "");
    $cout = (float) ($_POST["cout"] ?? 0);
    $formateurIdRaw = (int) ($_POST["formateur_id"] ?? 0);
    $formateurId = $formateurIdRaw > 0 ? $formateurIdRaw : null;
    $dateDebut = trim($_POST["date_debut"] ?? "");
    $dateFin = trim($_POST["date_fin"] ?? "");
    if ($action === "create" && $titre !== "") {
        $stmt = $pdo->prepare("INSERT INTO formations (titre, duree, cout, formateur_id, date_debut, date_fin) VALUES (:titre, :duree, :cout, :formateur_id, :date_debut, :date_fin)");
        $stmt->bindValue(":titre", $titre);
        $stmt->bindValue(":duree", $duree);
        $stmt->bindValue(":cout", $cout);
        $stmt->bindValue(":formateur_id", $formateurId, $formateurId === null ? PDO::PARAM_NULL : PDO::PARAM_INT);
        $stmt->bindValue(":date_debut", $dateDebut !== "" ? $dateDebut : null, $dateDebut !== "" ? PDO::PARAM_STR : PDO::PARAM_NULL);
        $stmt->bindValue(":date_fin", $dateFin !== "" ? $dateFin : null, $dateFin !== "" ? PDO::PARAM_STR : PDO::PARAM_NULL);
        $stmt->execute();
        setFlash("success", "Formation ajoutee.");
    }
    if ($action === "update") {
        $id = (int) ($_POST["id"] ?? 0);
        $stmt = $pdo->prepare("UPDATE formations SET titre=:titre, duree=:duree, cout=:cout, formateur_id=:formateur_id, date_debut=:date_debut, date_fin=:date_fin WHERE id=:id");
        $stmt->bindValue(":titre", $titre);
        $stmt->bindValue(":duree", $duree);
        $stmt->bindValue(":cout", $cout);
        $stmt->bindValue(":formateur_id", $formateurId, $formateurId === null ? PDO::PARAM_NULL : PDO::PARAM_INT);
        $stmt->bindValue(":date_debut", $dateDebut !== "" ? $dateDebut : null, $dateDebut !== "" ? PDO::PARAM_STR : PDO::PARAM_NULL);
        $stmt->bindValue(":date_fin", $dateFin !== "" ? $dateFin : null, $dateFin !== "" ? PDO::PARAM_STR : PDO::PARAM_NULL);
        $stmt->bindValue(":id", $id, PDO::PARAM_INT);
        $stmt->execute();
        setFlash("success", "Formation modifiee.");
    }
    redirect("/PIS/formations/index.php");
}

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

$formateurs = $pdo->query("SELECT id, nom, COALESCE(specialite, '') AS specialite FROM formateurs ORDER BY nom")->fetchAll();
$sql = "SELECT fo.*, fr.nom AS formateur FROM formations fo LEFT JOIN formateurs fr ON fo.formateur_id = fr.id";
$params = [];
if ($q !== "") {
    $sql .= " WHERE fo.titre LIKE :q OR fo.duree LIKE :q OR fr.nom LIKE :q";
    $params["q"] = "%{$q}%";
}
$sql .= " ORDER BY fo.id DESC";
$countSql = "SELECT COUNT(*) FROM formations fo LEFT JOIN formateurs fr ON fo.formateur_id = fr.id";
if ($q !== "") {
    $countSql .= " WHERE fo.titre LIKE :q OR fo.duree LIKE :q OR fr.nom 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();
$formations = $stmt->fetchAll();

if ($export === "csv") {
    $rows = [];
    foreach ($formations as $fo) {
        $rows[] = [$fo["titre"], $fo["duree"], $fo["cout"], $fo["formateur"]];
    }
    exportCsv("formations.csv", ["Titre", "Duree", "Cout", "Formateur"], $rows);
}
require_once __DIR__ . "/../includes/header.php";
?>
<h2>Gestion des formations</h2>
<form method="GET">
    <input type="text" name="q" value="<?= htmlspecialchars($q) ?>" placeholder="Rechercher une formation">
    <button type="submit">Rechercher</button>
</form>
<div class="actions">
    <a href="/PIS/formations/index.php?<?= http_build_query(["q" => $q, "export" => "csv"]) ?>">Exporter Excel (CSV)</a>
    <a href="/PIS/exports/print_formations.php?<?= http_build_query(["q" => $q]) ?>" target="_blank">Exporter PDF</a>
</div>
<?php if (isAdmin()): ?>
<form method="POST">
    <input type="hidden" name="action" value="<?= $editFormation ? "update" : "create" ?>">
    <?php if ($editFormation): ?><input type="hidden" name="id" value="<?= (int) $editFormation["id"] ?>"><?php endif; ?>
    <input type="text" name="titre" placeholder="Titre de la formation" required value="<?= htmlspecialchars((string) ($editFormation["titre"] ?? "")) ?>">
    <input type="text" name="duree" placeholder="Duree (ex: 3 mois)" value="<?= htmlspecialchars((string) ($editFormation["duree"] ?? "")) ?>">
    <input type="number" step="0.01" name="cout" placeholder="Cout" value="<?= htmlspecialchars((string) ($editFormation["cout"] ?? "")) ?>">
    <input type="date" name="date_debut" placeholder="Date debut" value="<?= htmlspecialchars((string) ($editFormation["date_debut"] ?? "")) ?>">
    <input type="date" name="date_fin" placeholder="Date fin" value="<?= htmlspecialchars((string) ($editFormation["date_fin"] ?? "")) ?>">
    <select name="formateur_id" id="formateurSelect">
        <option value="">Choisir un formateur (optionnel)</option>
        <?php foreach ($formateurs as $f): ?>
            <option
                value="<?= (int) $f["id"] ?>"
                data-specialite="<?= htmlspecialchars(strtolower((string) $f["specialite"])) ?>"
                <?= (int) ($editFormation["formateur_id"] ?? 0) === (int) $f["id"] ? "selected" : "" ?>
            >
                <?= htmlspecialchars($f["nom"]) ?>
            </option>
        <?php endforeach; ?>
    </select>
    <button type="submit"><?= $editFormation ? "Mettre a jour" : "Ajouter une formation" ?></button>
</form>
<?php else: ?>
    <!-- <p class="subtitle">Vous pouvez consulter les formations, mais vous n'avez pas le droit de modifier ou d'ajouter.</p> -->
<?php endif; ?>
<script>
    (function () {
        var titreInput = document.querySelector("input[name='titre']");
        var formateurSelect = document.getElementById("formateurSelect");
        if (!titreInput || !formateurSelect) return;

        function filterFormateursBySpecialite() {
            var search = (titreInput.value || "").toLowerCase().trim();
            var options = formateurSelect.querySelectorAll("option[data-specialite]");
            options.forEach(function (option) {
                var specialite = (option.getAttribute("data-specialite") || "").toLowerCase();
                if (search === "" || specialite.indexOf(search) !== -1) {
                    option.hidden = false;
                } else {
                    option.hidden = true;
                }
            });
        }

        titreInput.addEventListener("input", filterFormateursBySpecialite);
        filterFormateursBySpecialite();
    })();
</script>
<div class="table-wrap">
<table>
    <thead>
    <tr>
        <th>Titre</th>
        <th>Duree</th>
        <th>Cout</th>
        <th>Formateur</th>
        <th>Periode</th>
        <th>Action</th>
    </tr>
    </thead>
    <tbody>
    <?php foreach ($formations as $fo): ?>
        <tr>
            <td><?= htmlspecialchars($fo["titre"]) ?></td>
            <td><?= htmlspecialchars($fo["duree"]) ?></td>
            <td><?= number_format((float) $fo["cout"], 2, ",", " ") ?> FCFA</td>
            <td><?= htmlspecialchars((string) ($fo["formateur"] ?? "Non attribue")) ?></td>
            <td>
                <?php
                $deb = $fo["date_debut"] ?? "";
                $fin = $fo["date_fin"] ?? "";
                if ($deb || $fin) {
                    $parts = [];
                    if ($deb) $parts[] = (new DateTime($deb))->format("d/m/Y");
                    if ($fin) $parts[] = (new DateTime($fin))->format("d/m/Y");
                    echo htmlspecialchars(implode(" - ", $parts));
                } else {
                    echo "-";
                }
                ?>
            </td>
            <td class="actions">
                <?php if (isAdmin()): ?>
                    <a href="/PIS/formations/index.php?edit=<?= (int) $fo["id"] ?>">Modifier</a>
                    <a class="btn-danger"
                       href="/PIS/formations/index.php?delete=<?= (int) $fo["id"] ?>"
                       onclick="return confirm('Supprimer cette formation ?');">Supprimer</a>
                <?php else: ?>
                    &mdash;
                <?php endif; ?>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>
<?= renderPagination($pagination["page"], $pagination["totalPages"], "/PIS/formations/index.php", ["q" => $q]) ?>
<?php require_once __DIR__ . "/../includes/footer.php"; ?>
