<?php

namespace App\Controllers;

use App\Core\View;
use App\Services\StatusTicketService;

class StatusTicketController
{
  private StatusTicketService $statusTicketService;
  private View $view;

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

  public function index()
  {
    $statuses = $this->statusTicketService->findAll();

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

  public function update()
  {
    try {

      $id = (int) $_POST['id'];
      $namaStatus = $_POST['namaStatus'];
      $urutan = (int) $_POST['urutan'];
      $deskripsi = $_POST['deskripsi'];

      $this->statusTicketService->update(
        $id,
        $namaStatus,
        $urutan,
        $deskripsi
      );

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

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

    redirect('PENGATURAN_STATUS_TIKET');
    exit;
  }

  public function delete()
  {
    try {

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

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

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

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

    redirect('PENGATURAN_STATUS_TIKET');
    exit;
  }

  public function init()
  {
    try {

      $this->statusTicketService->init();

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

      $_SESSION['error'] = $e->getMessage();
    }

    redirect('PENGATURAN_STATUS_TIKET');
    exit;
  }
}
