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

class ArriereController {

    private $db;

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

    // GET /api/arrieres/membre/{id}
    public function getArrieresMembre($membre_id) {
        header("Content-Type: application/json");

        $sql = $this->db->prepare("
            SELECT id, annee, mois, montant_du, statut, created_at 
            FROM historiques_arriere
            WHERE membre_id = ?
            ORDER BY annee DESC, mois DESC
        ");
        $sql->execute([$membre_id]);
        echo json_encode($sql->fetchAll(PDO::FETCH_ASSOC));
    }

    // POST /api/arrieres/regler
    public function regler() {
        header("Content-Type: application/json");

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

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

        try {
            $sql = $this->db->prepare("
                UPDATE historiques_arriere
                SET statut = 'regle'
                WHERE id = ?
            ");
            $sql->execute([$input["id_arriere"]]);

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