<?php

class Depenses_BiensModel {
    private $db;

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

    public function getAll() {
        try {
            $stmt = $this->db->query("SELECT * FROM depenses_biens ORDER BY annee_depense DESC, mois_depense DESC");
            return $stmt->fetchAll();
        } catch (PDOException $e) {
            throw new Exception("Erreur lors de la récupération des dépenses: " . $e->getMessage());
        }
    }

    public function getByBien($id_bien) {
        try {
            $stmt = $this->db->prepare("SELECT * FROM depenses_biens WHERE id_bien = ? ORDER BY annee_depense DESC, mois_depense DESC");
            $stmt->execute([$id_bien]);
            return $stmt->fetchAll();
        } catch (PDOException $e) {
            throw new Exception("Erreur lors de la récupération des dépenses du bien: " . $e->getMessage());
        }
    }

    public function getByUser($id_utilisateur) {
        try {
            $stmt = $this->db->prepare("SELECT id_bien, libelle_bien FROM biens WHERE id_utilisateur = ?");
            $stmt->execute([$id_utilisateur]);
            return $stmt->fetchAll();
        } catch (PDOException $e) {
            throw new Exception("Erreur lors de la récupération des biens de l'utilisateur: " . $e->getMessage());
        }
    }

    public function find($id) {
        try {
            $stmt = $this->db->prepare("SELECT * FROM depenses_biens WHERE id_depenses_biens = ?");
            $stmt->execute([$id]);
            return $stmt->fetch() ?: null;
        } catch (PDOException $e) {
            throw new Exception("Erreur lors de la recherche de la dépense: " . $e->getMessage());
        }
    }

    public function store($data) {
        try {
            $stmt = $this->db->prepare("
                INSERT INTO depenses_biens 
                (id_bien, montant_depense, motif_depense_bien, frequence_depense, 
                 motif_depense, piece_justificative, mois_depense, annee_depense) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $success = $stmt->execute([
                $data['id_bien'] ?? null,
                $data['montant_depense'] ?? 0,
                $data['motif_depense_bien'] ?? '',
                $data['frequence_depense'] ?? '',
                $data['motif_depense'] ?? '',
                $data['piece_justificative'] ?? '',
                $data['mois_depense'] ?? date('m'),
                $data['annee_depense'] ?? date('Y')
            ]);
            
            return $success ? $this->db->lastInsertId() : false;
            
        } catch (PDOException $e) {
            throw new Exception("Erreur lors de la création de la dépense: " . $e->getMessage());
        }
    }

    public function update($id, $data) {
        try {
            $stmt = $this->db->prepare("
                UPDATE depenses_biens SET 
                id_bien = ?, montant_depense = ?, motif_depense_bien = ?, 
                frequence_depense = ?, motif_depense = ?, piece_justificative = ?, 
                mois_depense = ?, annee_depense = ? 
                WHERE id_depenses_biens = ?
            ");
            
            return $stmt->execute([
                $data['id_bien'] ?? null,
                $data['montant_depense'] ?? 0,
                $data['motif_depense_bien'] ?? '',
                $data['frequence_depense'] ?? '',
                $data['motif_depense'] ?? '',
                $data['piece_justificative'] ?? '',
                $data['mois_depense'] ?? date('m'),
                $data['annee_depense'] ?? date('Y'),
                $id
            ]);
            
        } catch (PDOException $e) {
            throw new Exception("Erreur lors de la mise à jour de la dépense: " . $e->getMessage());
        }
    }

    public function delete($id) {
        try {
            $stmt = $this->db->prepare("DELETE FROM depenses_biens WHERE id_depenses_biens = ?");
            return $stmt->execute([$id]);
        } catch (PDOException $e) {
            throw new Exception("Erreur lors de la suppression de la dépense: " . $e->getMessage());
        }
    }
}