<?php

namespace App\Controllers;

use App\Core\View;
use App\Services\CategoryService;

class CategoryController
{
  private CategoryService $categoryService;
  private View $view;

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

  public function index()
  {
    $categories = $this->categoryService->findAll();

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

  public function create()
  {
    try {
      $name = $_POST['namaKategori'];
      $desc = $_POST['deskripsi'];

      $this->categoryService->save($name, $desc);

      $_SESSION['success'] = 'Kategori berhasil ditambahkan';
      redirect('PENGATURAN_KATEGORI');
      exit;
    } catch (\Exception $e) {
      $_SESSION['error'] = 'Kategori gagal ditambahkan: ' . $e->getMessage();
      redirect('PENGATURAN_KATEGORI');
      exit;
    }
  }

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

      $this->categoryService->update($id, $name, $desc);

      $_SESSION['success'] = 'Kategori berhasil diubah';
      redirect('PENGATURAN_KATEGORI');
      exit;
    } catch (\Exception $e) {
      $_SESSION['error'] = 'Kategori gagal diubah: ' . $e->getMessage();
      redirect('PENGATURAN_KATEGORI');
      exit;
    }
  }

  public function delete()
  {
    try {
      $id = $_POST['id'];

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

      $_SESSION['success'] = 'Kategori berhasil dihapus';
      redirect('PENGATURAN_KATEGORI');
      exit;
    } catch (\Exception $e) {
      $_SESSION['error'] = 'Kategori gagal dihapus: ' . $e->getMessage();
      redirect('PENGATURAN_KATEGORI');
      exit;
    }
  }


  // category
  public function incident()
  {

    $categories = $this->categoryService->findAll();

    $categories = array_filter(
      $categories,
      fn($category) =>
      stripos($category->getDeskripsi() ?? '', 'incident') !== false ||
        stripos($category->getDeskripsi() ?? '', 'insiden') !== false
    );

    $this->view->renderUserPage(
      'user/category',
      [
        'categories' => $categories,
        'title' => 'Incident'
      ]
    );
  }

  public function request()
  {
    $categories = $this->categoryService->findAll();

    // filter desc contains request / permintaan
    $categories = array_filter(
      $categories,
      fn($category) =>
      stripos($category->getDeskripsi() ?? '', 'request') !== false ||
        stripos($category->getDeskripsi() ?? '', 'permintaan') !== false
    );

    $this->view->renderUserPage(
      'user/category',
      [
        'categories' => $categories,
        'title' => 'IT Service'
      ]
    );
  }
}
