<?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);
$editStagiaire = null;
$formations = $pdo->query("SELECT id, titre FROM formations ORDER BY titre")->fetchAll();
$stagiairesHasEmailColumn = false;
$emailColumnCheck = $pdo->query("SHOW COLUMNS FROM stagiaires LIKE 'email'");
if ($emailColumnCheck !== false) {
    $stagiairesHasEmailColumn = $emailColumnCheck->fetch() !== false;
}

if ($editId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM stagiaires WHERE id = :id");
    $stmt->execute(["id" => $editId]);
    $editStagiaire = $stmt->fetch();
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    requireAdminOrSecretaire();
    $action = $_POST["action"] ?? "create";

    if ($action === "create") {
        $nom = normalize($_POST["nom"] ?? "");
        $prenoms = normalize($_POST["prenoms"] ?? "");
        $sexe = normalize($_POST["sexe"] ?? "");
        $numero = normalize($_POST["numero"] ?? "");
        $dateNaissance = normalize($_POST["date_naissance"] ?? "");
        $lieuNaissance = normalize($_POST["lieu_naissance"] ?? "");
        $formationId = (int) ($_POST["formation_id"] ?? 0);
        if ($numero !== "") {
            $checkStmt = $pdo->prepare("SELECT id FROM stagiaires WHERE numero = :numero LIMIT 1");
            $checkStmt->execute(["numero" => $numero]);
            if ($checkStmt->fetch() !== false) {
                setFlash("error", "Ce numero ($numero) existe deja pour un autre apprenant.");
                redirect("/PIS/stagiaires/index.php");
            }
        }
        if ($nom !== "" && $prenoms !== "" && $formationId > 0) {
            $insertSql = "INSERT INTO stagiaires (nom, prenoms, sexe, numero, date_naissance, lieu_naissance";
            if ($stagiairesHasEmailColumn) {
                $insertSql .= ", email";
            }
            $insertSql .= ") VALUES (:nom, :prenoms, :sexe, :numero, :date_naissance, :lieu_naissance";
            if ($stagiairesHasEmailColumn) {
                $insertSql .= ", :email";
            }
            $insertSql .= ")";
            $stmt = $pdo->prepare($insertSql);
            $payload = [
                "nom" => $nom,
                "prenoms" => $prenoms,
                "sexe" => in_array($sexe, ["M", "F"], true) ? $sexe : null,
                "numero" => $numero !== "" ? $numero : null,
                "date_naissance" => $dateNaissance !== "" ? $dateNaissance : null,
                "lieu_naissance" => $lieuNaissance !== "" ? $lieuNaissance : null,
            ];
            if ($stagiairesHasEmailColumn) {
                $emailPrefix = strtolower((string) preg_replace("/[^a-z0-9]+/i", ".", $nom . "." . $prenoms));
                $emailPrefix = trim($emailPrefix, ".");
                if ($emailPrefix === "") {
                    $emailPrefix = "stagiaire";
                }
                $emailSuffix = strtolower(str_replace(".", "", uniqid("", true)));
                $payload["email"] = "{$emailPrefix}.{$emailSuffix}@stagiaire.local";
            }
            $stmt->execute($payload);
            $stagiaireId = (int) $pdo->lastInsertId();
            if ($formationId > 0) {
                $inscriptionStmt = $pdo->prepare(
                    "INSERT INTO inscriptions (stagiaire_id, formation_id, date_inscription)
                     SELECT :stagiaire_id, :formation_id, :date_inscription
                     WHERE NOT EXISTS (
                        SELECT 1 FROM inscriptions WHERE stagiaire_id = :stagiaire_id_check AND formation_id = :formation_id_check
                     )"
                );
                $inscriptionStmt->execute([
                    "stagiaire_id" => $stagiaireId,
                    "formation_id" => $formationId,
                    "date_inscription" => date("Y-m-d"),
                    "stagiaire_id_check" => $stagiaireId,
                    "formation_id_check" => $formationId,
                ]);
            }
            setFlash("success", "Apprenant ajoute avec succes.");
        } else {
            setFlash("error", "Veuillez renseigner nom, prenoms et choisir un module pour l'inscription automatique.");
        }
    }

    if ($action === "update") {
        $id = (int) ($_POST["id"] ?? 0);
        $nom = normalize($_POST["nom"] ?? "");
        $prenoms = normalize($_POST["prenoms"] ?? "");
        $sexe = normalize($_POST["sexe"] ?? "");
        $numero = normalize($_POST["numero"] ?? "");
        $dateNaissance = normalize($_POST["date_naissance"] ?? "");
        $lieuNaissance = normalize($_POST["lieu_naissance"] ?? "");
        $stmt = $pdo->prepare("UPDATE stagiaires SET nom = :nom, prenoms = :prenoms, sexe=:sexe, numero=:numero, date_naissance=:date_naissance, lieu_naissance=:lieu_naissance WHERE id = :id");
        $stmt->execute([
            "nom" => $nom,
            "prenoms" => $prenoms,
            "sexe" => in_array($sexe, ["M", "F"], true) ? $sexe : null,
            "numero" => $numero !== "" ? $numero : null,
            "date_naissance" => $dateNaissance !== "" ? $dateNaissance : null,
            "lieu_naissance" => $lieuNaissance !== "" ? $lieuNaissance : null,
            "id" => $id,
        ]);
        setFlash("success", "Apprenant modifie.");
    }

    if ($action === "import" && isset($_FILES["fichier"])) {
        $file = $_FILES["fichier"];
        $formationId = (int) ($_POST["formation_id"] ?? 0);
        $ext = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));
        if ($formationId <= 0) {
            setFlash("error", "Veuillez choisir un module avant l'import pour inscrire automatiquement les apprenants.");
        } elseif (in_array($ext, ["xlsx", "csv"], true)) {
            $rows = readSpreadsheetRows($file["tmp_name"], $ext);
            $imported = 0;
            $inscrits = 0;
            $ignored = 0;
            $invalid = 0;
            foreach ($rows as $index => $row) {
                if ($index === 0 && stripos((string) ($row[0] ?? ""), "nom") !== false) {
                    continue;
                }
                $nom = normalize((string) ($row[0] ?? ""));
                $prenoms = normalize((string) ($row[1] ?? ""));
                $sexeRaw = strtoupper(normalize((string) ($row[2] ?? "")));
                $numero = normalize((string) ($row[3] ?? ""));
                $dateNaissance = normalize((string) ($row[4] ?? ""));
                $lieuNaissance = normalize((string) ($row[5] ?? ""));
                if ($nom === "" || $prenoms === "") {
                    $invalid++;
                    continue;
                }
                $sexe = in_array($sexeRaw, ["M", "F"], true) ? $sexeRaw : null;
                $importSql = "INSERT INTO stagiaires (nom, prenoms, sexe, numero, date_naissance, lieu_naissance";
                if ($stagiairesHasEmailColumn) {
                    $importSql .= ", email";
                }
                $importSql .= ") VALUES (:nom, :prenoms, :sexe, :numero, :date_naissance, :lieu_naissance";
                if ($stagiairesHasEmailColumn) {
                    $importSql .= ", :email";
                }
                $importSql .= ")";
                $stmt = $pdo->prepare($importSql);
                $importPayload = [
                    "nom" => $nom,
                    "prenoms" => $prenoms,
                    "sexe" => $sexe,
                    "numero" => $numero !== "" ? $numero : null,
                    "date_naissance" => $dateNaissance !== "" ? $dateNaissance : null,
                    "lieu_naissance" => $lieuNaissance !== "" ? $lieuNaissance : null,
                ];
                if ($stagiairesHasEmailColumn) {
                    $emailPrefix = strtolower((string) preg_replace("/[^a-z0-9]+/i", ".", $nom . "." . $prenoms));
                    $emailPrefix = trim($emailPrefix, ".");
                    if ($emailPrefix === "") {
                        $emailPrefix = "stagiaire";
                    }
                    $importPayload["email"] = "{$emailPrefix}.{$index}." . strtolower(str_replace(".", "", uniqid("", true))) . "@stagiaire.local";
                }
                $stagiaireId = 0;
                try {
                    $stmt->execute($importPayload);
                    $imported += $stmt->rowCount();
                    $stagiaireId = (int) $pdo->lastInsertId();
                } catch (PDOException $e) {
                    if (($e->getCode() ?? "") === "23000") {
                        $ignored++;
                        if ($numero !== "") {
                            $existingStmt = $pdo->prepare("SELECT id FROM stagiaires WHERE numero = :numero ORDER BY id DESC LIMIT 1");
                            $existingStmt->execute(["numero" => $numero]);
                        } else {
                            $existingStmt = $pdo->prepare(
                                "SELECT id FROM stagiaires
                                 WHERE nom = :nom AND prenoms = :prenoms
                                 ORDER BY id DESC LIMIT 1"
                            );
                            $existingStmt->execute([
                                "nom" => $nom,
                                "prenoms" => $prenoms,
                            ]);
                        }
                        $existing = $existingStmt->fetch();
                        $stagiaireId = (int) ($existing["id"] ?? 0);
                        if ($stagiaireId <= 0) {
                            continue;
                        }
                    } else {
                        throw $e;
                    }
                }

                if ($formationId > 0) {
                    if ($stagiaireId > 0) {
                        $inscriptionStmt = $pdo->prepare(
                            "INSERT INTO inscriptions (stagiaire_id, formation_id, date_inscription)
                             SELECT :stagiaire_id, :formation_id, :date_inscription
                             WHERE NOT EXISTS (
                                SELECT 1 FROM inscriptions WHERE stagiaire_id = :stagiaire_id_check AND formation_id = :formation_id_check
                             )"
                        );
                        $inscriptionStmt->execute([
                            "stagiaire_id" => $stagiaireId,
                            "formation_id" => $formationId,
                            "date_inscription" => date("Y-m-d"),
                            "stagiaire_id_check" => $stagiaireId,
                            "formation_id_check" => $formationId,
                        ]);
                        $inscrits += $inscriptionStmt->rowCount();
                    }
                }
            }
            setFlash("success", "Import termine. {$imported} apprenant(s) ajoutes, {$inscrits} inscription(s) creee(s), {$ignored} doublon(s) ignore(s), {$invalid} ligne(s) invalide(s).");
        } else {
            setFlash("error", "Format non supporte. Utiliser .xlsx ou .csv.");
        }
    }

    if ($action === "bulk_manage") {
        $selectedIds = array_map(
            static fn ($id): int => (int) $id,
            (array) ($_POST["selected_ids"] ?? [])
        );
        $selectedIds = array_values(array_filter($selectedIds, static fn (int $id): bool => $id > 0));
        $bulkAction = normalize($_POST["bulk_action"] ?? "");
        $formationId = (int) ($_POST["bulk_formation_id"] ?? 0);

        if (empty($selectedIds)) {
            setFlash("error", "Veuillez selectionner au moins un apprenant.");
        } elseif (!in_array($bulkAction, ["delete", "enroll", "unenroll"], true)) {
            setFlash("error", "Action groupee invalide.");
        } else {
            $placeholders = implode(",", array_fill(0, count($selectedIds), "?"));

            if ($bulkAction === "delete") {
                $deleteStmt = $pdo->prepare("DELETE FROM stagiaires WHERE id IN ({$placeholders})");
                $deleteStmt->execute($selectedIds);
                setFlash("success", $deleteStmt->rowCount() . " apprenant(s) supprime(s).");
            }

            if ($bulkAction === "enroll") {
                if ($formationId <= 0) {
                    setFlash("error", "Veuillez choisir le module pour l'inscription groupee.");
                } else {
                    $inscriptionStmt = $pdo->prepare(
                        "INSERT INTO inscriptions (stagiaire_id, formation_id, date_inscription)
                         SELECT s.id, ?, ?
                         FROM stagiaires s
                         WHERE s.id IN ({$placeholders})
                           AND NOT EXISTS (
                               SELECT 1 FROM inscriptions i
                               WHERE i.stagiaire_id = s.id AND i.formation_id = ?
                           )"
                    );
                    $params = array_merge([$formationId, date("Y-m-d")], $selectedIds, [$formationId]);
                    $inscriptionStmt->execute($params);
                    setFlash("success", $inscriptionStmt->rowCount() . " inscription(s) creee(s) pour le module selectionne.");
                }
            }

            if ($bulkAction === "unenroll") {
                if ($formationId <= 0) {
                    setFlash("error", "Veuillez choisir le module pour la desinscription groupee.");
                } else {
                    $deleteInscriptionStmt = $pdo->prepare(
                        "DELETE FROM inscriptions
                         WHERE formation_id = ?
                           AND stagiaire_id IN ({$placeholders})"
                    );
                    $params = array_merge([$formationId], $selectedIds);
                    $deleteInscriptionStmt->execute($params);
                    setFlash("success", $deleteInscriptionStmt->rowCount() . " inscription(s) retiree(s) du module selectionne.");
                }
            }
        }
    }

    redirect("/PIS/stagiaires/index.php");
}

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

$sql = "SELECT * FROM stagiaires";
$params = [];
if ($q !== "") {
    $sql .= " WHERE nom LIKE :q OR prenoms LIKE :q OR numero LIKE :q OR lieu_naissance LIKE :q";
    $params["q"] = "%{$q}%";
}
$sql .= " ORDER BY id DESC";
$countStmt = $pdo->prepare(str_replace("SELECT *", "SELECT COUNT(*)", $sql));
$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();
$stagiaires = $stmt->fetchAll();

if ($export === "csv") {
    $rows = [];
    foreach ($stagiaires as $s) {
        $rows[] = [$s["nom"], $s["prenoms"], $s["sexe"], $s["numero"], $s["date_naissance"], $s["lieu_naissance"]];
    }
    exportCsv("apprenants.csv", ["Nom", "Prenoms", "Sexe", "Numero", "Date de naissance", "Lieu de naissance"], $rows);
}
require_once __DIR__ . "/../includes/header.php";
?>
<h2>Gestion des apprenants</h2>

<div class="toolbar">
    <form method="GET">
        <input type="text" name="q" value="<?= htmlspecialchars($q) ?>" placeholder="Rechercher un apprenant">
        <button type="submit">Rechercher</button>
    </form>
    <div class="actions">
        <a href="/PIS/stagiaires/index.php?<?= http_build_query(["q" => $q, "export" => "csv"]) ?>">Exporter Excel (CSV)</a>
        <a href="/PIS/exports/print_stagiaires.php?<?= http_build_query(["q" => $q]) ?>" target="_blank">Exporter PDF</a>
    </div>
</div>

<h3><?= $editStagiaire ? "Modifier un apprenant" : "Ajouter un apprenant" ?></h3>
<?php if (hasRole(["admin", "secretaire"])): ?>
<form method="POST">
    <input type="hidden" name="action" value="<?= $editStagiaire ? "update" : "create" ?>">
    <?php if ($editStagiaire): ?>
        <input type="hidden" name="id" value="<?= (int) $editStagiaire["id"] ?>">
    <?php endif; ?>
    <input type="text" name="nom" placeholder="Nom" required value="<?= htmlspecialchars((string) ($editStagiaire["nom"] ?? "")) ?>">
    <input type="text" name="prenoms" placeholder="Prenoms" required value="<?= htmlspecialchars((string) ($editStagiaire["prenoms"] ?? "")) ?>">
    <select name="sexe">
        <option value="">Sexe</option>
        <option value="M" <?= (($editStagiaire["sexe"] ?? "") === "M") ? "selected" : "" ?>>M</option>
        <option value="F" <?= (($editStagiaire["sexe"] ?? "") === "F") ? "selected" : "" ?>>F</option>
    </select>
    <input type="text" name="numero" placeholder="Numero" value="<?= htmlspecialchars((string) ($editStagiaire["numero"] ?? "")) ?>">
    <input type="date" name="date_naissance" value="<?= htmlspecialchars((string) ($editStagiaire["date_naissance"] ?? "")) ?>">
    <input type="text" name="lieu_naissance" placeholder="Lieu de naissance" value="<?= htmlspecialchars((string) ($editStagiaire["lieu_naissance"] ?? "")) ?>">
    <select name="formation_id" required>
        <option value="">Choisir le module (obligatoire)</option>
        <?php foreach ($formations as $f): ?>
            <option value="<?= (int) $f["id"] ?>"><?= htmlspecialchars($f["titre"]) ?></option>
        <?php endforeach; ?>
    </select>
    <button type="submit"><?= $editStagiaire ? "Mettre a jour" : "Ajouter" ?></button>
</form>
<?php else: ?>
    <p class="subtitle"><!-- Vous pouvez consulter les apprenants, mais vous n'avez pas le droit de modifier ou d'ajouter. --></p>
<?php endif; ?>

<h3>Importer des apprenants (Excel/CSV)</h3>
<?php if (hasRole(["admin", "secretaire"])): ?>
<form method="POST" enctype="multipart/form-data">
    <input type="hidden" name="action" value="import">
    <input type="file" name="fichier" accept=".xlsx,.csv" required>
    <select name="formation_id" required>
        <option value="">Choisir le module (obligatoire)</option>
        <?php foreach ($formations as $f): ?>
            <option value="<?= (int) $f["id"] ?>"><?= htmlspecialchars($f["titre"]) ?></option>
        <?php endforeach; ?>
    </select>
    <button type="submit">Importer</button>
</form>
<?php else: ?>
    <!-- L'importation de listes d'apprenants est reservee aux administrateurs et secretaire. -->
<?php endif; ?>
<p>Colonnes attendues: <strong>nom, prenoms, sexe, numero, date de naissance, lieu de naissance</strong>. Le module est obligatoire pour une inscription automatique a l'import.</p>

<h3>Actions groupees sur les apprenants</h3>
<?php if (hasRole(["admin", "secretaire"])): ?>
<form method="POST">
    <input type="hidden" name="action" value="bulk_manage">
    <select name="bulk_action" required>
        <option value="">Choisir une action</option>
        <option value="delete">Supprimer la selection</option>
        <option value="enroll">Inscrire la selection dans un module</option>
        <option value="unenroll">Desinscrire la selection d'un module</option>
    </select>
    <select name="bulk_formation_id">
        <option value="">Choisir le module (requis pour inscrire/desinscrire)</option>
        <?php foreach ($formations as $f): ?>
            <option value="<?= (int) $f["id"] ?>"><?= htmlspecialchars($f["titre"]) ?></option>
        <?php endforeach; ?>
    </select>
    <button type="submit" onclick="return confirm('Appliquer cette action a tous les apprenants selectionnes ?');">Appliquer</button>
    <div class="table-wrap">
        <table>
            <thead>
            <tr>
                <th><input type="checkbox" id="selectAllStagiaires"></th>
                <th>Nom</th>
                <th>Prenoms</th>
                <th>Sexe</th>
                <th>Numero</th>
                <th>Date naissance</th>
                <th>Lieu naissance</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($stagiaires as $s): ?>
                <tr>
                    <td><input type="checkbox" name="selected_ids[]" value="<?= (int) $s["id"] ?>" class="row-select-stagiaire"></td>
                    <td><?= htmlspecialchars($s["nom"]) ?></td>
                    <td><?= htmlspecialchars($s["prenoms"]) ?></td>
                    <td><?= htmlspecialchars((string) $s["sexe"]) ?></td>
                    <td><?= htmlspecialchars((string) $s["numero"]) ?></td>
                    <td><?= htmlspecialchars((string) $s["date_naissance"]) ?></td>
                    <td><?= htmlspecialchars((string) $s["lieu_naissance"]) ?></td>
                    <td class="actions">
                        <a href="/PIS/stagiaires/index.php?edit=<?= (int) $s["id"] ?>">Modifier</a>
                        <a class="btn-danger"
                           href="/PIS/stagiaires/index.php?delete=<?= (int) $s["id"] ?>"
                           onclick="return confirm('Supprimer cet apprenant ?');">Supprimer</a>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</form>
<?php else: ?>
    <!-- <p class="subtitle">Les actions groupees sont reservees aux administrateurs et secretaire.</p> -->
    <div class="table-wrap">
        <table>
            <thead>
            <tr>
                <th>Nom</th>
                <th>Prenoms</th>
                <th>Sexe</th>
                <th>Numero</th>
                <th>Date naissance</th>
                <th>Lieu naissance</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($stagiaires as $s): ?>
                <tr>
                    <td><?= htmlspecialchars($s["nom"]) ?></td>
                    <td><?= htmlspecialchars($s["prenoms"]) ?></td>
                    <td><?= htmlspecialchars((string) $s["sexe"]) ?></td>
                    <td><?= htmlspecialchars((string) $s["numero"]) ?></td>
                    <td><?= htmlspecialchars((string) $s["date_naissance"]) ?></td>
                    <td><?= htmlspecialchars((string) $s["lieu_naissance"]) ?></td>
                    <td class="actions">&mdash;</td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>
<?= renderPagination($pagination["page"], $pagination["totalPages"], "/PIS/stagiaires/index.php", ["q" => $q]) ?>
<script>
const selectAllStagiaires = document.getElementById("selectAllStagiaires");
if (selectAllStagiaires) {
    selectAllStagiaires.addEventListener("change", function () {
        document.querySelectorAll(".row-select-stagiaire").forEach(function (checkbox) {
            checkbox.checked = selectAllStagiaires.checked;
        });
    });
}
</script>
<?php require_once __DIR__ . "/../includes/footer.php"; ?>
