<?php
require_once '/home/dykqnvjf/public_html/bewise/app/kernel/Database_connexion.php';

class DepensesModel {
    private $db;
    private const REQUIRED_FIELDS = [
        'id_faiseur', 'libelles_depenses', 'categories', 'sous_categories', 'type_depense',
        'periodicite', 'mode_paiement', 'montant_periodique', 'montant_annuel_estimatif', 'statut_depense',
        'date_echeance', 'description', 'piece_justificative', 'impact_budgetaire', 'responsable_validation',
        'date_prevu_depense'
    ];

    private const UPDATE_FIELDS = [
        'libelles_depenses', 'categories', 'sous_categories', 'type_depense',
        'periodicite', 'mode_paiement', 'montant_periodique', 'montant_annuel_estimatif',
        'date_prevu_depense', 'date_echeance', 'statut_depense', 'description',
        'piece_justificative', 'impact_budgetaire', 'responsable_validation', 'id_receveur'
    ];

    public function __construct() {
        try {
            $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,
                    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"
                ]
            );
        } catch (PDOException $e) {
            throw new RuntimeException("Erreur de connexion à la base de données : " . $e->getMessage());
        }
    }

    public function getAllD(): array {
        return $this->query("SELECT * FROM depenses ORDER BY date_enregistrement DESC");
    }

    public function getByUser(int $id_utilisateur): array {
        return $this->query(
            "SELECT * FROM depenses WHERE id_faiseur = ? ORDER BY date_enregistrement DESC",
            [$id_utilisateur]
        );
    }

    public function store(array $data): bool {
        $this->validateData($data);
        
        $sql = "INSERT INTO depenses (
            id_faiseur, id_receveur, libelles_depenses, categories, sous_categories, type_depense,
            periodicite, mode_paiement, montant_periodique, montant_annuel_estimatif, statut_depense,
            date_echeance, description, piece_justificative, impact_budgetaire, responsable_validation,
            date_prevu_depense
        ) VALUES (
            :id_faiseur, :id_receveur, :libelles_depenses, :categories, :sous_categories, :type_depense,
            :periodicite, :mode_paiement, :montant_periodique, :montant_annuel_estimatif, :statut_depense,
            :date_echeance, :description, :piece_justificative, :impact_budgetaire, :responsable_validation,
            :date_prevu_depense
        )";
        
        return $this->execute($sql, $data);
    }

    public function find(int $id): ?array {
        $result = $this->query("SELECT * FROM depenses WHERE id_depense = ?", [$id]);
        return $result[0] ?? null;
    }

    public function update(int $id, array $data): bool {
        // Liste des champs modifiables
        $updateData = [
            'libelles_depenses' => $data['libelles_depenses'] ?? null,
            'categories' => $data['categories'] ?? null,
            'sous_categories' => $data['sous_categories'] ?? null,
            'type_depense' => $data['type_depense'] ?? null,
            'periodicite' => $data['periodicite'] ?? null,
            'mode_paiement' => $data['mode_paiement'] ?? null,
            'montant_periodique' => $data['montant_periodique'] ?? null,
            'montant_annuel_estimatif' => $data['montant_annuel_estimatif'] ?? null,
            'date_prevu_depense' => $data['date_prevu_depense'] ?? null,
            'date_echeance' => $data['date_echeance'] ?? null,
            'statut_depense' => $data['statut_depense'] ?? null,
            'description' => $data['description'] ?? null,
            'piece_justificative' => $data['piece_justificative'] ?? null,
            'impact_budgetaire' => $data['impact_budgetaire'] ?? null,
            'responsable_validation' => $data['responsable_validation'] ?? null,
            'id_receveur' => $data['id_receveur'] ?? null,
            'id' => $id
        ];
    
        $sql = "UPDATE depenses SET 
            libelles_depenses = :libelles_depenses,
            categories = :categories,
            sous_categories = :sous_categories,
            type_depense = :type_depense,
            periodicite = :periodicite,
            mode_paiement = :mode_paiement,
            montant_periodique = :montant_periodique,
            montant_annuel_estimatif = :montant_annuel_estimatif,
            date_prevu_depense = :date_prevu_depense,
            date_echeance = :date_echeance,
            statut_depense = :statut_depense,
            description = :description,
            piece_justificative = :piece_justificative,
            impact_budgetaire = :impact_budgetaire,
            responsable_validation = :responsable_validation,
            id_receveur = :id_receveur
        WHERE id_depense = :id";
    
        return $this->execute($sql, $updateData);
    }

    public function delete(int $id): bool {
        return $this->execute("DELETE FROM depenses WHERE id_depense = ?", [$id]);
    }

    public function getDepenseById(int $id): ?array {
        return $this->find($id);
    }

    /**
     * Méthodes privées pour factoriser le code
     */
    private function query(string $sql, array $params = []): array {
        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll();
    }

    private function execute(string $sql, array $params = []): bool {
        $stmt = $this->db->prepare($sql);
        return $stmt->execute($params);
    }

    private function validateData(array $data): void {
        foreach (self::REQUIRED_FIELDS as $field) {
            if (empty($data[$field])) {
                throw new InvalidArgumentException("Le champ $field est requis");
            }
        }
    }
}
?>