<?php
class VersementControllerVB {
    private $db;

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

    public function getBonsVersByDateRange() {
        $dateDebut = $_GET['date_debut'] ?? null;
        $dateFin = $_GET['date_fin'] ?? null;

        if (!$dateDebut || !$dateFin) {
            echo json_encode([
                'success' => false,
                'message' => 'Paramètres date_debut et date_fin requis'
            ]);
            return;
        }

        try {
            $query = "SELECT 
                        Id,
                        num_vers,
                        DATE_FORMAT(date_vers, '%Y/%m/%d') AS date_vers,
                        periode_p,
                        operateur,
                        type_vehicule,
                        matricule,
                        mt_ttc,
                        obs,
                        creer_par,
                        DATE_FORMAT(date_creer, '%Y-%m-%d %H:%i:%s') AS date_creer
                      FROM bons_vers 
                      WHERE DATE(date_vers) BETWEEN :date_debut AND :date_fin
                      ORDER BY date_vers ASC, num_vers ASC";

            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':date_debut', $dateDebut, PDO::PARAM_STR);
            $stmt->bindParam(':date_fin', $dateFin, PDO::PARAM_STR);
            $stmt->execute();
            $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Convertir mt_ttc en float pour chaque ligne
            foreach ($data as &$row) {
                $row['mt_ttc'] = (float)$row['mt_ttc'];
                $row['Id'] = (int)$row['Id'];
            }

            echo json_encode([
                'success' => true,
                'data' => $data,
                'count' => count($data)
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'message' => 'Erreur serveur : ' . $e->getMessage()
            ]);
        }
    }
}
?>
