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

header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");

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

// Initialiser la connexion PDO
$database = new Database();
$pdo = $database->getConnection();

// Instancier le modèle
$model = new CotisationMensuelleModel($pdo);

// Contrôleur
$controller = new CotisationMensuelleController($model);

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 'arrears':
        $controller->getArrieres();
        break;

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

class CotisationMensuelleController {
    private $model;

    public function __construct($model) {
        $this->model = $model;
    }

    public function add() {
        $data = json_decode(file_get_contents("php://input"), true);
        $membreId = $data["membre_id"] ?? null;
        $montant = $data["montant"] ?? null;
        $mois = $data["mois"] ?? null;

        if (!$membreId || !$montant || !$mois) {
            echo json_encode(["success" => false, "message" => "Champs requis manquants"]);
            return;
        }

        [$annee, $moisNum] = explode("-", $mois);
        $success = $this->model->ajouter($membreId, $montant, $annee, $moisNum);
        echo json_encode([
            "success" => $success,
            "message" => $success ? "Cotisation enregistrée" : "Échec de l'enregistrement"
        ]);
    }

    public function getAll() {
        $data = $this->model->tout();
        echo json_encode(["success" => true, "data" => $data]);
    }

    public function getArrieres() {
        $data = $this->model->calculArrieres();
        echo json_encode(["success" => true, "data" => $data]);
    }
}
