<?php

namespace App\Repositories;

use PDO;
use App\Config\DatasourceConfig;
use App\Helpers\AttachmentMapper;

final class AttachmentRepo
{
  private PDO $connection;
  private AttachmentMapper $mapper;

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

  private string $querySelect = "
        SELECT
            id_lampiran,
            id_ticket,
            id_user,
            nama_file,
            tipe_file,
            ukuran_file,
            tanggal_upload
        FROM attachments
    ";

  public function findAll()
  {
    $statement = $this->connection->prepare($this->querySelect);
    $statement->execute();

    $rows = $statement->fetchAll(PDO::FETCH_ASSOC);

    return array_map([$this->mapper, 'toAttachment'], $rows);
  }

  public function findById(int $id)
  {
    $statement = $this->connection->prepare(
      $this->querySelect . " WHERE id_lampiran=:id"
    );

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

    $row = $statement->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
      return null;
    }

    return $this->mapper->toAttachment($row);
  }

  public function findByTicket(int $ticketId)
  {
    $statement = $this->connection->prepare(
      $this->querySelect . " WHERE id_ticket=:ticketId ORDER BY tanggal_upload"
    );

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

    $rows = $statement->fetchAll(PDO::FETCH_ASSOC);

    return array_map([$this->mapper, 'toAttachment'], $rows);
  }

  public function save(
    PDO $connection,
    int $ticketId,
    int $userId,
    string $namaFile,
    ?string $tipeFile,
    ?int $ukuranFile
  ) {

    $query = "
            INSERT INTO attachments
            (
                id_ticket,
                id_user,
                nama_file,
                tipe_file,
                ukuran_file
            )
            VALUES
            (
                :ticketId,
                :userId,
                :namaFile,
                :tipeFile,
                :ukuranFile
            )
        ";

    $statement = $connection->prepare($query);

    $statement->execute([
      'ticketId' => $ticketId,
      'userId' => $userId,
      'namaFile' => $namaFile,
      'tipeFile' => $tipeFile,
      'ukuranFile' => $ukuranFile
    ]);
  }

  public function delete(int $id)
  {
    $statement = $this->connection->prepare(
      "DELETE FROM attachments WHERE id_lampiran=:id"
    );

    $statement->execute([
      'id' => $id
    ]);
  }

  public function deleteByTicket(int $ticketId)
  {
    $statement = $this->connection->prepare(
      "DELETE FROM attachments WHERE id_ticket=:ticketId"
    );

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