<?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);
$editPaiement = null;
if ($editId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM paiements WHERE id = :id");
    $stmt->execute(["id" => $editId]);
    $editPaiement = $stmt->fetch();
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    requireAdmin();
    $action = $_POST["action"] ?? "create";
    $inscriptionId = (int) ($_POST["inscription_id"] ?? 0);
    $montant = (float) ($_POST["montant"] ?? 0);
    $date = $_POST["date_paiement"] ?? date("Y-m-d");

    if ($action === "create" && $inscriptionId > 0 && $montant > 0) {
        $stmt = $pdo->prepare(
            "INSERT INTO paiements (inscription_id, montant, date_paiement)
             VALUES (:inscription_id, :montant, :date_paiement)"
        );
        $stmt->execute([
            "inscription_id" => $inscriptionId,
            "montant" => $montant,
            "date_paiement" => $date,
        ]);
        setFlash("success", "Paiement enregistre.");
    }
    if ($action === "update") {
        $id = (int) ($_POST["id"] ?? 0);
        $stmt = $pdo->prepare("UPDATE paiements SET inscription_id=:inscription_id, montant=:montant, date_paiement=:date_paiement WHERE id=:id");
        $stmt->execute([
            "inscription_id" => $inscriptionId,
            "montant" => $montant,
            "date_paiement" => $date,
            "id" => $id,
        ]);
        setFlash("success", "Paiement modifie.");
    }
    redirect("/PIS/paiements/index.php");
}

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

$inscriptions = $pdo->query(
    "SELECT i.id, CONCAT(s.nom, ' ', s.prenoms) AS stagiaire, f.titre AS formation
     FROM inscriptions i
     JOIN stagiaires s ON i.stagiaire_id = s.id
     JOIN formations f ON i.formation_id = f.id
     ORDER BY i.id DESC"
)->fetchAll();

$sql = "SELECT p.id, p.montant, p.date_paiement, CONCAT(s.nom, ' ', s.prenoms) AS stagiaire, f.titre AS formation
     FROM paiements p
     JOIN inscriptions i ON p.inscription_id = i.id
     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 p.date_paiement LIKE :q";
    $params["q"] = "%{$q}%";
}
$sql .= " ORDER BY p.id DESC";
$countSql = "SELECT COUNT(*) FROM paiements p
     JOIN inscriptions i ON p.inscription_id = i.id
     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 p.date_paiement 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();
$paiements = $stmt->fetchAll();

if ($export === "csv") {
    $rows = [];
    foreach ($paiements as $p) {
        $rows[] = [$p["stagiaire"], $p["formation"], $p["montant"], $p["date_paiement"]];
    }
    exportCsv("paiements.csv", ["Apprenant", "Formation", "Montant", "Date"], $rows);
}
require_once __DIR__ . "/../includes/header.php";
?>
<h2>Gestion des paiements</h2>
<form method="GET">
    <input type="text" name="q" value="<?= htmlspecialchars($q) ?>" placeholder="Rechercher un paiement">
    <button type="submit">Rechercher</button>
</form>
<div class="actions">
    <a href="/PIS/paiements/index.php?<?= http_build_query(["q" => $q, "export" => "csv"]) ?>">Exporter Excel (CSV)</a>
    <a href="/PIS/exports/print_paiements.php?<?= http_build_query(["q" => $q]) ?>" target="_blank">Exporter PDF</a>
</div>
<?php if (isAdmin()): ?>
<form method="POST">
    <input type="hidden" name="action" value="<?= $editPaiement ? "update" : "create" ?>">
    <?php if ($editPaiement): ?><input type="hidden" name="id" value="<?= (int) $editPaiement["id"] ?>"><?php endif; ?>
    <select name="inscription_id" required>
        <option value="">Choisir une inscription</option>
        <?php foreach ($inscriptions as $i): ?>
            <option value="<?= (int) $i["id"] ?>" <?= (int) ($editPaiement["inscription_id"] ?? 0) === (int) $i["id"] ? "selected" : "" ?>>
                <?= htmlspecialchars($i["stagiaire"] . " - " . $i["formation"]) ?>
            </option>
        <?php endforeach; ?>
    </select>
    <input type="number" step="0.01" name="montant" placeholder="Montant" required value="<?= htmlspecialchars((string) ($editPaiement["montant"] ?? "")) ?>">
    <input type="date" name="date_paiement" value="<?= htmlspecialchars((string) ($editPaiement["date_paiement"] ?? date("Y-m-d"))) ?>" required>
    <button type="submit"><?= $editPaiement ? "Mettre a jour" : "Enregistrer le paiement" ?></button>
</form>
<?php else: ?>
    <p class="subtitle">Vous pouvez consulter les paiements, 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>Montant</th>
        <th>Date</th>
        <th>Action</th>
    </tr>
    </thead>
    <tbody>
    <?php foreach ($paiements as $p): ?>
        <tr>
            <td><?= htmlspecialchars($p["stagiaire"]) ?></td>
            <td><?= htmlspecialchars($p["formation"]) ?></td>
            <td><?= number_format((float) $p["montant"], 2, ",", " ") ?> FCFA</td>
            <td><?= htmlspecialchars($p["date_paiement"]) ?></td>
            <td class="actions">
                <?php if (isAdmin()): ?>
                    <a href="/PIS/paiements/index.php?edit=<?= (int) $p["id"] ?>">Modifier</a>
                    <a class="btn-danger"
                       href="/PIS/paiements/index.php?delete=<?= (int) $p["id"] ?>"
                       onclick="return confirm('Supprimer ce paiement ?');">Supprimer</a>
                <?php else: ?>
                    &mdash;
                <?php endif; ?>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>
<?= renderPagination($pagination["page"], $pagination["totalPages"], "/PIS/paiements/index.php", ["q" => $q]) ?>
<?php require_once __DIR__ . "/../includes/footer.php"; ?>
