<?php

namespace App\Controllers;

use App\Core\View;
use App\Services\SlaService;

class SlaController
{
  private SlaService $slaService;
  private View $view;

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

  public function index()
  {
    $slas = $this->slaService->findAll();

    $this->view->renderAdminPage(
      'pengaturan/sla',
      [
        'slas' => $slas
      ]
    );
  }

  public function create()
  {
    try {

      $namaSla = $_POST['namaSla'];
      $waktuResponJam = (int) $_POST['waktuResponJam'];
      $waktuPenyelesaianJam = (int) $_POST['waktuPenyelesaianJam'];
      $deskripsi = $_POST['deskripsi'];

      $this->slaService->save(
        $namaSla,
        $waktuResponJam,
        $waktuPenyelesaianJam,
        $deskripsi
      );

      $_SESSION['success'] = 'SLA berhasil ditambahkan.';
    } catch (\Exception $e) {

      $_SESSION['error'] = 'SLA gagal ditambahkan: ' . $e->getMessage();
    }

    redirect('PENGATURAN_SLA');
    exit;
  }

  public function update()
  {
    try {

      $id = (int) $_POST['id'];
      $namaSla = $_POST['namaSla'];
      $waktuResponJam = (int) $_POST['waktuResponJam'];
      $waktuPenyelesaianJam = (int) $_POST['waktuPenyelesaianJam'];
      $deskripsi = $_POST['deskripsi'];

      $this->slaService->update(
        $id,
        $namaSla,
        $waktuResponJam,
        $waktuPenyelesaianJam,
        $deskripsi
      );

      $_SESSION['success'] = 'SLA berhasil diubah.';
    } catch (\Exception $e) {

      $_SESSION['error'] = 'SLA gagal diubah: ' . $e->getMessage();
    }

    redirect('PENGATURAN_SLA');
    exit;
  }

  public function delete()
  {
    try {

      $id = (int) $_POST['id'];

      $this->slaService->delete($id);

      $_SESSION['success'] = 'SLA berhasil dihapus.';
    } catch (\Exception $e) {

      $_SESSION['error'] = 'SLA gagal dihapus: ' . $e->getMessage();
    }

    redirect('PENGATURAN_SLA');
    exit;
  }
}
