<?php

class Depenses_BiensController {
    private $model;
    private $biensModel;

    public function __construct() {
        @session_start();
        require_once '/home/dykqnvjf/public_html/bewise/app/models/Depenses_BiensModel.php';
        require_once '/home/dykqnvjf/public_html/bewise/app/models/BiensModel.php';
        $this->model = new Depenses_BiensModel();
        $this->biensModel = new BiensModel();
    }

    private function loadUserBiens($id_user) {
        return $this->biensModel->getByUser($id_user);
    }

    private function redirect($url, $message = null, $type = null) {
        if ($message && $type) {
            $_SESSION['flash'] = ['type' => $type, 'message' => $message];
        }
        header('Location: ' . $url);
        exit;
    }

    public function index() {
        $id_user = $_SESSION['user']['id_utilisateur'];
        $biens = $this->loadUserBiens($id_user);
        $depenses = $this->model->getAll();
        require '/home/dykqnvjf/public_html/bewise/app/views/Depenses_BiensView.php';
    }

    public function create() {
        $id_user = $_SESSION['user']['id_utilisateur'];
        $biens = $this->loadUserBiens($id_user);
        require '/home/dykqnvjf/public_html/bewise/app/views/CreateDepenses_BiensView.php';
    }

    public function filterByBien($id_bien) {
        $id_user = $_SESSION['user']['id_utilisateur'];
        $biens = $this->loadUserBiens($id_user);
        $depenses = $this->model->getByBien($id_bien);
        require '/home/dykqnvjf/public_html/bewise/app/views/Depenses_BiensView.php';
    }

    public function store() {
        try {
            $this->model->store($_POST);
            $this->redirect('../index.php/depenses_biens', 'Dépense créée avec succès', 'success');
        } catch (Exception $e) {
            $this->redirect('../index.php/depenses_biens', 'Erreur lors de la création', 'danger');
        }
    }

    public function edit($id) {
        $id_user = $_SESSION['user']['id_utilisateur'];
        $biens = $this->loadUserBiens($id_user);
        $depense = $this->model->find($id);
        require '/home/dykqnvjf/public_html/bewise/app/views/EditDepenses_BiensView.php';
    }

    public function update($id) {
        try {
            $this->model->update($id, $_POST);
            $this->redirect('/depenses_biens', 'Dépense mise à jour avec succès', 'success');
        } catch (Exception $e) {
            $this->redirect('/depenses_biens', 'Erreur lors de la mise à jour', 'danger');
        }
    }

    public function delete($id) {
        try {
            $this->model->delete($id);
            $this->redirect('../depenses_biens', 'Dépense supprimée avec succès', 'success');
        } catch (Exception $e) {
            $this->redirect('../depenses_biens', 'Erreur lors de la suppression', 'danger');
        }
    }
}
?>