<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

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

class AutreCotisationController {
    private $db;

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

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

        try {
            $sql = $this->db->prepare("
                SELECT 
                    a.id, 
                    a.membre_id, 
                    m.nom, 
                    m.prenom, 
                    CONCAT(m.nom, ' ', m.prenom) AS nom_complet,
                    a.montant, 
                    a.commentaire, 
                    a.created_at, 
                    a.operation_id
                FROM autres_cotisations a
                LEFT JOIN membres m ON a.membre_id = m.id
                ORDER BY a.created_at DESC
            ");
            $sql->execute();

            echo json_encode([
                "success" => true,
                "data" => $sql->fetchAll(PDO::FETCH_ASSOC)
            ]);
        } catch (PDOException $e) {
            echo json_encode([
                "success" => false,
                "message" => "Erreur SQL : " . $e->getMessage()
            ]);
        }
    }

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

        try {
            $sql = $this->db->prepare("
                SELECT 
                    m.nom, 
                    m.prenom, 
                    CONCAT(m.nom, ' ', m.prenom) AS nom_complet,
                    a.montant, 
                    a.commentaire, 
                    a.created_at,
                    o.type, 
                    o.montant AS montant_operation, 
                    o.created_at AS date_operation
                FROM autres_cotisations a
                JOIN membres m ON a.membre_id = m.id
                JOIN operations o ON a.operation_id = o.id
                ORDER BY a.created_at DESC
            ");
            $sql->execute();

            echo json_encode([
                "success" => true,
                "data" => $sql->fetchAll(PDO::FETCH_ASSOC)
            ]);
        } catch (PDOException $e) {
            echo json_encode([
                "success" => false,
                "message" => "Erreur export : " . $e->getMessage()
            ]);
        }
    }

    /**
     * POST /api/autres?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 requis : membre_id, montant"]);
            return;
        }

        try {
            $this->db->beginTransaction();

            $op = $this->db->prepare("
                INSERT INTO operations (type, montant, created_at)
                VALUES ('autre_cotisation', ?, NOW())
            ");
            $op->execute([$input["montant"]]);
            $operation_id = $this->db->lastInsertId();

            $stmt = $this->db->prepare("
                INSERT INTO autres_cotisations (membre_id, operation_id, montant, commentaire, created_at)
                VALUES (?, ?, ?, ?, NOW())
            ");
            $stmt->execute([
                $input["membre_id"],
                $operation_id,
                $input["montant"],
                $input["commentaire"] ?? null
            ]);

            $this->db->commit();
            echo json_encode(["success" => true, "message" => "Autre cotisation enregistrée."]);

        } catch (Exception $e) {
            $this->db->rollBack();
            echo json_encode(["success" => false, "message" => "Erreur : " . $e->getMessage()]);
        }
    }

    /**
     * POST /api/autres?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 = intval($_GET["id"]);
        $input = json_decode(file_get_contents("php://input"), true);

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

        try {
            $stmt = $this->db->prepare("
                UPDATE autres_cotisations
                SET montant = ?, commentaire = ?
                WHERE id = ?
            ");
            $stmt->execute([
                $input["montant"],
                $input["commentaire"] ?? null,
                $id
            ]);

            echo json_encode(["success" => true, "message" => "Cotisation modifiée"]);

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

    /**
     * GET /api/autres?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 = intval($_GET["id"]);

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

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

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

//
// ─── ROUTEUR ─────────────────────────────────────────────────────────────
//
$controller = new AutreCotisationController();

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

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

        case "export":
            $controller->export();
            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"]);
}
