<?php

class Epargne_ctModel {
    private $pdo;

    public function __construct() {
        $this->pdo = new PDO(
            'mysql:host=localhost;dbname=dykqnvjf_gespes360;charset=utf8',
            'dykqnvjf_gespes360',
            'dykqnvjf_gespes360',
            [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            ]
        );
    }

    public function getByUser(int $id_user): array {
        $stmt = $this->pdo->prepare("SELECT * FROM epargne_ct WHERE id_utilisateur = ? ORDER BY date_enregistrement DESC");
        $stmt->execute([$id_user]);
        return $stmt->fetchAll();
    }

    public function find(int $id): ?array {
        $stmt = $this->pdo->prepare("SELECT * FROM epargne_ct WHERE id_epargne_ct = ?");
        $stmt->execute([$id]);
        return $stmt->fetch() ?: null;
    }

    public function getById(int $id): ?array {
        return $this->find($id); // Les méthodes find() et getById() font la même chose
    }  

    public function insert(array $data): bool {
        $sql = "INSERT INTO epargne_ct (
            id_utilisateur, id_compte, libelle_epargne, type_epargne, objectif, 
            priorite, statut, montant_vise, montant_actuel, commentaire, date_echeance
        ) VALUES (
            :id_utilisateur, :id_compte, :libelle_epargne, :type_epargne, :objectif, 
            :priorite, :statut, :montant_vise, :montant_actuel, :commentaire, :date_echeance
        )";
        $stmt = $this->pdo->prepare($sql);
        return $stmt->execute($data);
    }

    public function update(int $id, array $data): bool {
        $sql = "UPDATE epargne_ct SET 
            id_utilisateur = :id_utilisateur,
            id_compte = :id_compte,
            libelle_epargne = :libelle_epargne,
            type_epargne = :type_epargne,
            objectif = :objectif,
            priorite = :priorite,
            statut = :statut,
            montant_vise = :montant_vise,
            montant_actuel = :montant_actuel,
            commentaire = :commentaire,
            date_echeance = :date_echeance
        WHERE id_epargne_ct = :id";

        $data['id'] = $id;
        $stmt = $this->pdo->prepare($sql);
        return $stmt->execute($data);
    }

    public function delete(int $id): bool {
        $stmt = $this->pdo->prepare("DELETE FROM epargne_ct WHERE id_epargne_ct = ?");
        return $stmt->execute([$id]);
    }
}
?>