<?php

namespace App\Services;

use App\Repositories\AttachmentRepo;
use PDO;

class AttachmentService
{
  private AttachmentRepo $attachmentRepo;

  public function __construct()
  {
    $this->attachmentRepo = new AttachmentRepo();
  }

  public function findAll()
  {
    return $this->attachmentRepo->findAll();
  }

  public function findById(int $id)
  {
    return $this->attachmentRepo->findById($id);
  }

  public function findByTicket(int $ticketId)
  {
    return $this->attachmentRepo->findByTicket($ticketId);
  }

  public function delete(int $id)
  {
    $attachment = $this->attachmentRepo->findById($id);

    if (empty($attachment)) {
      throw new \Exception('Lampiran tidak ditemukan.');
    }

    return $this->attachmentRepo->delete($id);
  }

  public function deleteByTicket(int $ticketId)
  {
    return $this->attachmentRepo->deleteByTicket($ticketId);
  }

  private function validate(string $namaFile): array
  {
    $errors = [];

    if (trim($namaFile) === '') {
      $errors['namaFile'] = 'Nama file wajib diisi.';
    }

    return $errors;
  }

  private function isValid(string $namaFile): void
  {
    $errors = $this->validate($namaFile);

    if (count($errors) > 0) {
      throw new \Exception(implode(', ', $errors));
    }
  }

  public function upload(
    PDO $connection,
    int $ticketId,
    int $userId,
    array $files
  ): array {

    $uploadedFiles = [];

    if (empty($files['name'][0])) {
      return [];
    }

    $uploadDir = dirname(__DIR__, 2) . '/public/uploads/tickets/';

    if (!is_dir($uploadDir)) {
      mkdir($uploadDir, 0777, true);
    }

    $allowedExtension = [
      'pdf',
      'jpg',
      'jpeg',
      'png',
      'doc',
      'docx',
      'xls',
      'xlsx',
      'zip'
    ];

    $maxSize = 5 * 1024 * 1024; //5MB

    foreach ($files['name'] as $i => $originalName) {

      if ($files['error'][$i] == UPLOAD_ERR_NO_FILE) {
        continue;
      }

      if ($files['error'][$i] != UPLOAD_ERR_OK) {
        throw new \Exception("Upload file gagal.");
      }

      $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));

      if (!in_array($extension, $allowedExtension, true)) {
        throw new \Exception("Format file {$originalName} tidak didukung.");
      }

      if ($files['size'][$i] > $maxSize) {
        throw new \Exception("Ukuran {$originalName} maksimal 5 MB.");
      }

      $newFileName =
        uniqid('ticket_', true) .
        '.' .
        $extension;

      $destination = $uploadDir . $newFileName;

      if (!move_uploaded_file(
        $files['tmp_name'][$i],
        $destination
      )) {
        throw new \Exception("Gagal menyimpan {$originalName}");
      }

      $uploadedFiles[] = $destination;

      $this->attachmentRepo->save(
        connection: $connection,
        ticketId: $ticketId,
        userId: $userId,
        namaFile: $newFileName,
        tipeFile: $files['type'][$i],
        ukuranFile: $files['size'][$i]
      );
    }

    return $uploadedFiles;
  }
}
