<?php

namespace App\Controllers;

use App\Services\DivisiService;
use App\Core\View;

class DivisiController
{

  private DivisiService $divisiService;
  private View $view;

  public function __construct()
  {
    $this->divisiService = new DivisiService();
    $this->view = new View();
  }

  public function index()
  {
    $divisions = $this->divisiService->findAll();
    $this->view->renderAdminPage('pengaturan/divisi', ['divisions' => $divisions]);
  }

  public function create()
  {

    try {
      $name = $_POST['namaDivisi'];
      $desc = $_POST['deskripsi'];

      $this->divisiService->save($name, $desc);
      $_SESSION['success'] = 'Divisi berhasil ditambahkan';
      redirect('PENGATURAN_DIVISI');
      exit;
    } catch (\Exception $e) {
      $_SESSION['error'] = 'Divisi gagal ditambahkan: ' . $e->getMessage();
      redirect('PENGATURAN_DIVISI');
      exit;
    }
  }

  public function update()
  {
    try {
      $id = $_POST['id'];
      $name = $_POST['namaDivisi'];
      $desc = $_POST['deskripsi'];

      $this->divisiService->update($id, $name, $desc);
      $_SESSION['success'] = 'Divisi berhasil diubah';
      redirect('PENGATURAN_DIVISI');
      exit;
    } catch (\Exception $e) {
      $_SESSION['error'] = 'Divisi gagal diubah: ' . $e->getMessage();
      redirect('PENGATURAN_DIVISI');
      exit;
    }
  }

  public function delete()
  {
    try {
      $id = $_POST['id'];
      $this->divisiService->delete($id);
      $_SESSION['success'] = 'Divisi berhasil dihapus';
      redirect('PENGATURAN_DIVISI');
      exit;
    } catch (\Exception $e) {
      $_SESSION['error'] = 'Divisi gagal dihapus: ' . $e->getMessage();
      redirect('PENGATURAN_DIVISI');
      exit;
    }
  }
}
