<?php

namespace App\Repositories;

use PDO;
use App\Config\DatasourceConfig;
use App\Helpers\ActivityLogMapper;
use App\Models\ActivityLogModel;

class ActivityLogRepository
{
  private PDO $connection;
  private ActivityLogMapper $mapper;


  public function __construct()
  {
    $this->connection = (new DatasourceConfig())->connect();
    $this->mapper = new ActivityLogMapper();
  }

  private string $querySelect = "
        SELECT
            al.*,
            u.nama

        FROM activity_logs al

        INNER JOIN users u
            ON u.id_user = al.id_user
    ";

  public function insert(PDO $connection, ActivityLogModel $log): void
  {
    $statement = $connection->prepare("
            INSERT INTO activity_logs
            (
                id_ticket,
                id_user,
                aktivitas,
                log_type,
                ip_address
            )
            VALUES
            (
                :ticket,
                :user,
                :aktivitas,
                :log_type,
                :ip
            )
        ");

    $statement->execute([
      'ticket' => $log->getTicketId(),
      'user' => $log->getUserId(),
      'aktivitas' => $log->getAktivitas(),
      'ip' => $log->getIpAddress(),
      'log_type' => $log->getLogType(),
    ]);
  }

  public function findByTicketId(int $ticketId): array
  {
    $statement = $this->connection->prepare(
      $this->querySelect . "
                WHERE al.id_ticket = :ticket
                ORDER BY al.tanggal_aktivitas ASC
            "
    );

    $statement->execute([
      'ticket' => $ticketId
    ]);

    return array_map(
      [$this->mapper, 'toActivityLog'],
      $statement->fetchAll(PDO::FETCH_ASSOC)
    );
  }

  // get first time assigned
  public function findFirstTimeAssigned(int $ticketId)
  {
    $statement = $this->connection->prepare(
      $this->querySelect . "
                WHERE al.id_ticket = :ticket
                AND al.log_type = 'ASSIGN'
                ORDER BY al.tanggal_aktivitas ASC
                LIMIT 1
            "
    );

    $statement->execute([
      'ticket' => $ticketId
    ]);

    return $statement->fetch(PDO::FETCH_ASSOC);
  }
}
