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

// Association many-to-many entre formateurs et modules de formation.
$pdo->exec(
    "CREATE TABLE IF NOT EXISTS formateur_modules (
        id INT AUTO_INCREMENT PRIMARY KEY,
        formateur_id INT NOT NULL,
        formation_id INT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        CONSTRAINT fk_formateur_modules_formateur FOREIGN KEY (formateur_id) REFERENCES formateurs(id) ON DELETE CASCADE,
        CONSTRAINT fk_formateur_modules_formation FOREIGN KEY (formation_id) REFERENCES formations(id) ON DELETE CASCADE,
        UNIQUE KEY uq_formateur_formation (formateur_id, formation_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
);

$q = trim($_GET["q"] ?? "");
$export = $_GET["export"] ?? "";
$editId = (int) ($_GET["edit"] ?? 0);
$editFormateur = null;
$selectedModuleIds = [];
$formations = $pdo->query("SELECT id, titre FROM formations ORDER BY titre")->fetchAll();

function buildSpecialiteFromModules(PDO $pdo, array $moduleIds): string
{
    if (count($moduleIds) === 0) {
        return "";
    }
    $placeholders = implode(",", array_fill(0, count($moduleIds), "?"));
    $stmt = $pdo->prepare("SELECT titre FROM formations WHERE id IN ({$placeholders}) ORDER BY titre");
    foreach (array_values($moduleIds) as $index => $moduleId) {
        $stmt->bindValue($index + 1, (int) $moduleId, PDO::PARAM_INT);
    }
    $stmt->execute();
    $titles = $stmt->fetchAll(PDO::FETCH_COLUMN);
    return implode(", ", array_map(static fn ($v): string => (string) $v, $titles));
}
if ($editId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM formateurs WHERE id = :id");
    $stmt->execute(["id" => $editId]);
    $editFormateur = $stmt->fetch();
    if ($editFormateur) {
        $moduleStmt = $pdo->prepare("SELECT formation_id FROM formateur_modules WHERE formateur_id = :id");
        $moduleStmt->execute(["id" => $editId]);
        $selectedModuleIds = array_map("intval", $moduleStmt->fetchAll(PDO::FETCH_COLUMN));
    }
}

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

    $action = $_POST["action"] ?? "create";
    if ($action === "create") {
        $nom = normalize($_POST["nom"] ?? "");
        $email = normalize($_POST["email"] ?? "");
        $moduleIds = array_map("intval", (array) ($_POST["module_ids"] ?? []));
        $moduleIds = array_values(array_unique(array_filter($moduleIds, static fn (int $id): bool => $id > 0)));
        $specialiteText = buildSpecialiteFromModules($pdo, $moduleIds);
        if ($nom !== "") {
            $stmt = $pdo->prepare("INSERT INTO formateurs (nom, specialite, email) VALUES (:nom, :specialite, :email)");
            $stmt->execute(["nom" => $nom, "specialite" => $specialiteText, "email" => $email]);
            $formateurId = (int) $pdo->lastInsertId();
            if ($formateurId > 0 && count($moduleIds) > 0) {
                $insertModuleStmt = $pdo->prepare("INSERT INTO formateur_modules (formateur_id, formation_id) VALUES (:formateur_id, :formation_id)");
                foreach ($moduleIds as $moduleId) {
                    $insertModuleStmt->execute([
                        "formateur_id" => $formateurId,
                        "formation_id" => $moduleId,
                    ]);
                }
            }
            setFlash("success", "Formateur ajoute.");
        }
    }
    if ($action === "update") {
        $id = (int) ($_POST["id"] ?? 0);
        $moduleIds = array_map("intval", (array) ($_POST["module_ids"] ?? []));
        $moduleIds = array_values(array_unique(array_filter($moduleIds, static fn (int $moduleId): bool => $moduleId > 0)));
        $specialiteText = buildSpecialiteFromModules($pdo, $moduleIds);
        $stmt = $pdo->prepare("UPDATE formateurs SET nom=:nom, specialite=:specialite, email=:email WHERE id=:id");
        $stmt->execute([
            "nom" => normalize($_POST["nom"] ?? ""),
            "specialite" => $specialiteText,
            "email" => normalize($_POST["email"] ?? ""),
            "id" => $id,
        ]);
        $deleteModuleStmt = $pdo->prepare("DELETE FROM formateur_modules WHERE formateur_id = :formateur_id");
        $deleteModuleStmt->execute(["formateur_id" => $id]);
        if ($id > 0 && count($moduleIds) > 0) {
            $insertModuleStmt = $pdo->prepare("INSERT INTO formateur_modules (formateur_id, formation_id) VALUES (:formateur_id, :formation_id)");
            foreach ($moduleIds as $moduleId) {
                $insertModuleStmt->execute([
                    "formateur_id" => $id,
                    "formation_id" => $moduleId,
                ]);
            }
        }
        setFlash("success", "Formateur modifie.");
    }
    redirect("/PIS/formateurs/index.php");
}

if (isset($_GET["delete"])) {
    requireRole(["admin"]);
    $id = (int) $_GET["delete"];
    $stmt = $pdo->prepare("DELETE FROM formateurs WHERE id = :id");
    $stmt->execute(["id" => $id]);
    setFlash("success", "Formateur supprime.");
    redirect("/PIS/formateurs/index.php");
}

$sql = "SELECT f.*,
               COALESCE(
                   GROUP_CONCAT(DISTINCT fo.titre ORDER BY fo.titre SEPARATOR ', '),
                   ''
               ) AS modules
        FROM formateurs f
        LEFT JOIN formateur_modules fm ON fm.formateur_id = f.id
        LEFT JOIN formations fo ON fo.id = fm.formation_id";
$params = [];
if ($q !== "") {
    $sql .= " WHERE f.nom LIKE :q OR f.specialite LIKE :q OR f.email LIKE :q OR fo.titre LIKE :q";
    $params["q"] = "%{$q}%";
}
$sql .= " GROUP BY f.id ORDER BY f.id DESC";
$countSql = "SELECT COUNT(*)
             FROM formateurs f
             WHERE 1=1";
if ($q !== "") {
    $countSql .= " AND (f.nom LIKE :q OR f.specialite LIKE :q OR f.email 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();
$formateurs = $stmt->fetchAll();

if ($export === "csv") {
    $rows = [];
    foreach ($formateurs as $f) {
        $rows[] = [$f["nom"], $f["modules"], $f["email"]];
    }
    exportCsv("formateurs.csv", ["Nom", "Specialite", "Email"], $rows);
}
require_once __DIR__ . "/../includes/header.php";
?>
<h2>Gestion des formateurs</h2>
<form method="GET">
    <input type="text" name="q" value="<?= htmlspecialchars($q) ?>" placeholder="Rechercher">
    <button type="submit">Rechercher</button>
</form>
<div class="actions">
    <a href="/PIS/formateurs/index.php?<?= http_build_query(["q" => $q, "export" => "csv"]) ?>">Exporter Excel (CSV)</a>
    <a href="/PIS/exports/print_formateurs.php?<?= http_build_query(["q" => $q]) ?>" target="_blank">Exporter PDF</a>
</div>
<?php if (isAdmin()): ?>
<form method="POST">
    <input type="hidden" name="action" value="<?= $editFormateur ? "update" : "create" ?>">
    <?php if ($editFormateur): ?><input type="hidden" name="id" value="<?= (int) $editFormateur["id"] ?>"><?php endif; ?>
    <input type="text" name="nom" placeholder="Nom complet" required value="<?= htmlspecialchars((string) ($editFormateur["nom"] ?? "")) ?>">
    <div class="modules-picker" id="modulesPicker">
        <button type="button" class="modules-picker-toggle" id="modulesPickerToggle">
            veuillez selectionner un ou plusieurs formations
        </button>
        <div class="modules-picker-menu" id="modulesPickerMenu">
            <?php foreach ($formations as $formation): ?>
                <?php $formationId = (int) $formation["id"]; ?>
                <label class="modules-picker-item">
                    <input
                        type="checkbox"
                        name="module_ids[]"
                        value="<?= $formationId ?>"
                        <?= in_array($formationId, $selectedModuleIds, true) ? "checked" : "" ?>
                    >
                    <span><?= htmlspecialchars($formation["titre"]) ?></span>
                </label>
            <?php endforeach; ?>
        </div>
    </div>
    <input type="email" name="email" placeholder="Email" value="<?= htmlspecialchars((string) ($editFormateur["email"] ?? "")) ?>">
    <button type="submit"><?= $editFormateur ? "Mettre a jour" : "Ajouter un formateur" ?></button>
</form>
<?php else: ?>
    <!-- <p class="subtitle">Vous pouvez consulter les formateurs, mais vous n'avez pas le droit de modifier ou d'ajouter.</p> -->
<?php endif; ?>
<style>
    .modules-picker { position: relative; width: 520px; max-width: 100%; }
    .modules-picker-toggle {
        width: 100%;
        text-align: left;
        padding: 10px;
        border: 1px solid #cbd5e1;
        border-radius: 4px;
        background: #fff;
        cursor: pointer;
        font-size: 14px;
        color: #6b7280;
        font-weight: 400;
    }
    .modules-picker-toggle.has-selection { color: #0f172a; }
    .modules-picker-menu {
        display: none;
        position: absolute;
        top: calc(100% + 4px);
        left: 0;
        width: 100%;
        max-height: 220px;
        overflow: auto;
        border: 1px solid #cbd5e1;
        border-radius: 4px;
        background: #fff;
        z-index: 30;
        padding: 0;
    }
    .modules-picker.open .modules-picker-menu { display: block; }
    .modules-picker-item {
        display: flex;
        align-items: center;
        gap: 0;
        padding: 2px 0;
        cursor: pointer;
        font-size: 12px;
        line-height: 1.2;
        text-align: left;
        justify-content: flex-start;
        margin: 0;
        font-weight: 400;
    }
    .modules-picker-item input[type="checkbox"] {
        margin: 0 0 0 0 !important;
        padding: 0;
        flex: 0 0 auto;
    }
    .modules-picker-item span {
        margin-left: 0;
        padding-left: 0;
        font-size: 12px;
        white-space: normal;
        word-break: break-word;
        text-align: left;
        flex: 1 1 auto;
        font-weight: 400;
    }
</style>
<script>
    (function () {
        var picker = document.getElementById("modulesPicker");
        var toggle = document.getElementById("modulesPickerToggle");
        var menu = document.getElementById("modulesPickerMenu");
        if (!picker || !toggle || !menu) return;

        function updateLabel() {
            var checked = menu.querySelectorAll("input[type='checkbox']:checked");
            if (!checked.length) {
                toggle.textContent = "veuillez selectionner un ou plusieurs formations";
                toggle.classList.remove("has-selection");
                return;
            }
            var labels = [];
            for (var i = 0; i < checked.length; i++) {
                var label = checked[i].parentElement.querySelector("span");
                if (label && label.textContent) {
                    labels.push(label.textContent.trim());
                }
            }
            toggle.textContent = labels.join(", ");
            toggle.classList.add("has-selection");
        }

        toggle.addEventListener("click", function () {
            picker.classList.toggle("open");
        });
        menu.addEventListener("change", updateLabel);
        document.addEventListener("click", function (event) {
            if (!picker.contains(event.target)) {
                picker.classList.remove("open");
            }
        });
        updateLabel();
    })();
</script>
<div class="table-wrap">
<table>
    <thead>
    <tr>
        <th>Nom</th>
        <th>Specialite</th>
        <th>Email</th>
        <th>Action</th>
    </tr>
    </thead>
    <tbody>
    <?php foreach ($formateurs as $f): ?>
        <tr>
            <td><?= htmlspecialchars($f["nom"]) ?></td>
            <td><?= htmlspecialchars((string) ($f["modules"] ?? "")) ?></td>
            <td><?= htmlspecialchars($f["email"]) ?></td>
            <td class="actions">
                <?php if (isAdmin()): ?>
                    <a href="/PIS/formateurs/index.php?edit=<?= (int) $f["id"] ?>">Modifier</a>
                    <a class="btn-danger"
                       href="/PIS/formateurs/index.php?delete=<?= (int) $f["id"] ?>"
                       onclick="return confirm('Supprimer ce formateur ?');">Supprimer</a>
                <?php else: ?>
                    &mdash;
                <?php endif; ?>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>
<?= renderPagination($pagination["page"], $pagination["totalPages"], "/PIS/formateurs/index.php", ["q" => $q]) ?>
<?php require_once __DIR__ . "/../includes/footer.php"; ?>
