<?php

namespace App\Controllers;

use App\Core\View;
use App\Services\PriorityService;

class PriorityController
{
  private PriorityService $priorityService;
  private View $view;

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

  public function index()
  {
    $priorities = $this->priorityService->findAll();

    $this->view->renderAdminPage(
      'pengaturan/prioritas-tiket',
      [
        'priorities' => $priorities
      ]
    );
  }

  public function init()
  {
    try {

      $this->priorityService->init();

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

      $_SESSION['error'] =
        'Gagal menginisialisasi prioritas: ' . $e->getMessage();
    }

    redirect('PENGATURAN_PRIORITAS');
    exit;
  }

  public function update()
  {
    try {

      $id = (int) $_POST['id'];
      $namaPrioritas = $_POST['namaPrioritas'];
      $level = (int) $_POST['level'];
      $deskripsi = $_POST['deskripsi'];

      $this->priorityService->update(
        $id,
        $namaPrioritas,
        $level,
        $deskripsi
      );

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

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

    redirect('PENGATURAN_PRIORITAS');
    exit;
  }
}
