<?php
require_once __DIR__ . '/../config/database.php';

class DonController {

    private $db;

    public function __construct() {
        $database = new Database();
        $this->db = $database->getConnection();
    }

    /**
     * GET /api/dons?action=all
     */
    public function getAll() {
        header("Content-Type: application/json; charset=utf-8");

        $sql = $this->db->prepare("
            SELECT d.id, d.membre_id, m.nom, m.prenoms, d.montant, d.commentaire AS description, d.created_at
            FROM dons_membres d
            LEFT JOIN membres m ON d.membre_id = m.id
            ORDER BY d.created_at DESC
        ");
        $sql->execute();

        echo json_encode([
            "success" => true,
            "data" => $sql->fetchAll(PDO::FETCH_ASSOC)
        ]);
    }

    /**
     * POST /api/dons?action=add
     */
    public function add() {
        header("Content-Type: application/json; charset=utf-8");

        $input = json_decode(file_get_contents("php://input"), true);

        if (!$input || !isset($input["membre_id"]) || !isset($input["montant"])) {
            echo json_encode(["success" => false, "message" => "Paramètres manquants"]);
            return;
        }

        try {
            $stmt = $this->db->prepare("
                INSERT INTO dons_membres (membre_id, montant, commentaire, created_at)
                VALUES (?, ?, ?, NOW())
            ");

            $stmt->execute([
                $input["membre_id"],
                $input["montant"],
                $input["description"] ?? null
            ]);

            echo json_encode(["success" => true, "message" => "Don enregistré"]);

        } catch (Exception $e) {
            echo json_encode(["success" => false, "message" => $e->getMessage()]);
        }
    }

    /**
     * POST /api/dons?action=update&id=XX
     */
    public function update() {
        header("Content-Type: application/json; charset=utf-8");

        if (!isset($_GET["id"])) {
            echo json_encode(["success" => false, "message" => "ID manquant"]);
            return;
        }

        $id = $_GET["id"];
        $input = json_decode(file_get_contents("php://input"), true);

        if (!$input || !isset($input["montant"])) {
            echo json_encode(["success" => false, "message" => "Paramètres manquants"]);
            return;
        }

        try {
            $stmt = $this->db->prepare("
                UPDATE dons_membres
                SET montant = ?, commentaire = ?
                WHERE id = ?
            ");

            $stmt->execute([
                $input["montant"],
                $input["description"] ?? null,
                $id
            ]);

            echo json_encode(["success" => true, "message" => "Don mis à jour"]);

        } catch (Exception $e) {
            echo json_encode(["success" => false, "message" => $e->getMessage()]);
        }
    }

    /**
     * GET /api/dons?action=delete&id=XX
     */
    public function delete() {
        header("Content-Type: application/json; charset=utf-8");

        if (!isset($_GET["id"])) {
            echo json_encode(["success" => false, "message" => "ID manquant"]);
            return;
        }

        $id = $_GET["id"];

        try {
            $stmt = $this->db->prepare("DELETE FROM dons_membres WHERE id = ?");
            $stmt->execute([$id]);

            echo json_encode(["success" => true, "message" => "Don supprimé"]);

        } catch (Exception $e) {
            echo json_encode(["success" => false, "message" => $e->getMessage()]);
        }
    }
}

//
// ROUTEUR
//
$controller = new DonController();

if (isset($_GET["action"])) {

    switch ($_GET["action"]) {

        case "all":
            $controller->getAll();
            break;

        case "add":
            if ($_SERVER["REQUEST_METHOD"] === "POST") $controller->add();
            else echo json_encode(["success" => false, "message" => "POST requis"]);
            break;

        case "update":
            if ($_SERVER["REQUEST_METHOD"] === "POST") $controller->update();
            else echo json_encode(["success" => false, "message" => "POST requis"]);
            break;

        case "delete":
            $controller->delete();
            break;

        default:
            echo json_encode(["success" => false, "message" => "Action inconnue"]);
    }

} else {
    echo json_encode(["success" => false, "message" => "Aucune action fournie"]);
}
