<?php

namespace App\Controllers;

use App\Services\TicketCommentService;

class CommentController
{
  private TicketCommentService $commentService;

  public function __construct()
  {
    $this->commentService = new TicketCommentService();
  }

  public function store(): void
  {
    $ticketId = (int) $_POST['ticketId'];
    $komentar = trim($_POST['komentar']);
    $user = $_SESSION['user'];

    if ($ticketId <= 0 || empty($komentar)) {
      $_SESSION['error'] = 'Komentar tidak boleh kosong.';
      if ($user["role"] == "ADMIN") {
        redirect('DETAIL_TIKET', ['id' => $ticketId], "#comment");
      } else {
        redirect('USER_TIKET_DETAIL', ['id' => $ticketId], "#comment");
      }

      exit;
    }

    $userId = $_SESSION['user']['id'] ?? 1;

    $this->commentService->create(
      ticketId: $ticketId,
      userId: $userId,
      komentar: $komentar
    );

    if ($user["role"] == "ADMIN") {
      redirect('DETAIL_TIKET', ['id' => $ticketId], "#comment");
    } else {
      redirect('USER_TIKET_DETAIL', ['id' => $ticketId], "#comment");
    }
    exit;
  }
}
