<?php


class Epargne_ctController {

  private $model;

  public function __construct() {
    $this->model = new Epargne_ctModel();
    $this->userModel = new UtilisateursModel();
  }

  public function index() {
    @session_start();
    $id_user = $_SESSION['user']['id_utilisateur'];
    $epargnes = $this->model->getByUser($id_user);

    // Charger les comptes pour le menu déroulant
    require_once '/home/dykqnvjf/public_html/bewise/app/models/ComptesModel.php';
    $comptes = (new ComptesModel())->getByUser($id_user);

    require '/home/dykqnvjf/public_html/bewise/app/views/Epargne_ctView.php';
  }

    
  public function create() {
    renderEpargneCtEdit(null); // formulaire vide
  }


  public function store() {
      @session_start();
      try {
          $data = $_POST;
          $this->model->insert($data);
          
          $_SESSION['notification'] = [
              'type' => 'success',
              'message' => 'Épargne ajoutée avec succès!'
          ];
          
          header('Location: ../index.php/epargne_ct');
          exit;
          
      } catch (Exception $e) {
          $_SESSION['notification'] = [
              'type' => 'error',
              'message' => 'Erreur lors de l\'ajout: ' . $e->getMessage() 
          ];
          header('Location: ../index.php/epargne_ct');
          exit;
      }
  }



  public function edit($id) {
    @session_start();
    $id_user = $_SESSION['user']['id_utilisateur'];

    $epargne = $this->model->getById($id);

    require_once '/home/dykqnvjf/public_html/bewise/app/models/ComptesModel.php';
    $comptes = (new ComptesModel())->getByUser($id_user);

    require '/home/dykqnvjf/public_html/bewise/app/views/EditEpargne_ctView.php';
  }

  public function update($id) {
    @session_start();
    $data = $_POST;
    $this->model->update($id, $data);
    header('Location: ../epargne_ct');
  }

  public function delete($id) {
    $this->model->delete($id);
    header('Location: ../epargne_ct');
  }
}
?>