<?php

namespace App\Controllers;

use App\Services\StatusTicketService;
use App\Services\TicketAssignmentService;

class TicketAssignmentController
{
  private TicketAssignmentService $ticketAssignmentService;
  private StatusTicketService $ticketStatusService;

  public function __construct()
  {
    $this->ticketAssignmentService = new TicketAssignmentService();
    $this->ticketStatusService = new StatusTicketService();
  }

  // assign tiket
  public function assign(int $id)
  {
    try {

      $teknisiId = filter_input(INPUT_POST, 'teknisiId', FILTER_VALIDATE_INT);
      $catatan = filter_input(INPUT_POST, 'catatan');
      $userId = $_SESSION['user']['id'] ?? 1;

      if (!$teknisiId) {
        throw new \Exception('Teknisi tidak valid.');
      }

      $this->ticketAssignmentService->save($id, $teknisiId, $_POST['status'], $userId, $catatan ?? null);

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

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

    redirect('DETAIL_TIKET', ['id' => $id]);
    exit;
  }

  // escalate tiket
  public function escalate(int $id)
  {
    try {

      $teknisiUserId = $_POST['teknisiId'];
      $catatan = filter_input(INPUT_POST, 'catatan');
      $userId = $_SESSION['user']['id'] ?? 1;

      if (!$teknisiUserId) {
        throw new \Exception('Teknisi tidak valid.');
      }

      $this->ticketAssignmentService->escalate($id, $teknisiUserId, $catatan, $userId);

      $_SESSION['success'] = 'Tiket berhasil di eskalasi.';
    } catch (\Exception $e) {

      $_SESSION['error'] = 'Tiket gagal di eskalasi: ' . $e->getMessage();
    }

    redirect('DETAIL_TIKET', ['id' => $id]);
    exit;
  }
}
