<?php

class DettesController {
  private $model;

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

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

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

    require_once '/home/dykqnvjf/public_html/bewise/app/models/UtilisateursModel.php'; 
    $utilisateurs = (new UtilisateursModel())->getAllU();

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

  public function create() {
    @session_start();
    require_once '/home/dykqnvjf/public_html/bewise/app/models/ComptesModel.php';
    require_once '/home/dykqnvjf/public_html/bewise/app/models/UtilisateursModel.php';
    $comptes = (new ComptesModel())->getByUser($_SESSION['user']['id_utilisateur']);
    $utilisateurs = (new UtilisateursModel())->getAllU();
    require '/home/dykqnvjf/public_html/bewise/app/views/EditDettesView.php';
  }


  public function store() {
      @session_start();
      try {
          $data = $_POST;
          $data['id_contracteur'] = $_SESSION['user']['id_utilisateur'];
          
          if ($this->model->store($data)) {
              $_SESSION['notification'] = [
                  'type' => 'success',
                  'message' => 'Dette enregistrée avec succès!'
              ];
          } else {
              throw new Exception("Erreur lors de l'enregistrement");
          }
          
          header('Location: ../index.php/dettes');
          exit;
      } catch (Exception $e) {
          $_SESSION['notification'] = [
              'type' => 'error',
              'message' => $e->getMessage()
          ];
          header('Location: ../index.php/dettes/create');
          exit;
      }
  }


  public function edit($id) {
    @session_start();
    $dette = $this->model->find($id);
    require_once '/home/dykqnvjf/public_html/bewise/app/models/ComptesModel.php';
    require_once '/home/dykqnvjf/public_html/bewise/app/models/UtilisateursModel.php';
    $comptes = (new ComptesModel())->getByUser($_SESSION['user']['id_utilisateur']);
    $utilisateurs = (new UtilisateursModel())->getAllU();
    require '/home/dykqnvjf/public_html/bewise/app/views/EditDettesView.php';
  }

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

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