<?php

namespace App\Repositories;

use App\Config\DatasourceConfig;
use App\Helpers\TicketCommentMapper;
use App\Models\TicketCommentModel;
use PDO;

class TicketCommentRepo
{
  private PDO $connection;
  public function __construct()
  {
    $this->connection = (new DatasourceConfig())->connect();
  }

  /**
   * @return TicketCommentModel[]
   */
  public function findByTicketId(int $ticketId): array
  {
    $sql = "
            SELECT
                tc.*,
                u.nama
            FROM ticket_comments tc
            INNER JOIN users u
                ON u.id_user = tc.id_user
            WHERE tc.id_ticket = :ticketId
            ORDER BY tc.tanggal_komentar ASC
        ";

    $stmt = $this->connection->prepare($sql);
    $stmt->execute([
      'ticketId' => $ticketId
    ]);

    $comments = [];

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      $comments[] = TicketCommentMapper::map($row);
    }

    return $comments;
  }

  public function create(
    int $ticketId,
    int $userId,
    string $komentar,
  ): void {
    $sql = "
        INSERT INTO ticket_comments (
            id_ticket,
            id_user,
            komentar
        ) VALUES (
            :ticketId,
            :userId,
            :komentar
        )
    ";

    $stmt = $this->connection->prepare($sql);

    $stmt->execute([
      'ticketId' => $ticketId,
      'userId' => $userId,
      'komentar' => $komentar
    ]);
  }
}
