<?php

namespace App\Services;

use App\Models\Attachment;
use App\Repositories\AttachmentRepository;

class AttachmentService
{
    protected AttachmentRepository $attachmentRepository;

    public function __construct() {
        $this->attachmentRepository = new AttachmentRepository();
    }
    
    public static function uploadFiles($locationId, $numExp, $files)
    {
        $uploadDir = __DIR__ . "/../../public/uploads/{$numExp}/";

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

        $uploadedFiles = [];

        foreach ($files['name'] as $key => $fileName) {
            $tmpName = $files['tmp_name'][$key];
            $baseName = pathinfo($fileName, PATHINFO_FILENAME);
            $extension = pathinfo($fileName, PATHINFO_EXTENSION);

            // Asegurar un nombre único si el archivo ya existe
            $finalFileName = $fileName;
            $i = 1;
            while (file_exists($uploadDir . $finalFileName)) {
                $finalFileName = "{$baseName}_{$i}." . $extension;
                $i++;
            }

            $filePath = $uploadDir . $finalFileName;

            if (move_uploaded_file($tmpName, $filePath)) {
                $attachment = new Attachment([
                    'location_id' => $locationId,
                    'file_name' => $finalFileName,
                    'file_path' => "/uploads/{$numExp}/" . $finalFileName
                ]);
                $attachment->save();

                if (empty($uploadedFiles)) {
                    $uploadedFiles = [
                        'file_name' => $finalFileName,
                        'file_path' => "/uploads/{$numExp}/" . $finalFileName
                    ];
                }
            }
        }

        return $uploadedFiles;
    }

    public function getAllAttachmentsByProcess($processId)
    {
        return $this->attachmentRepository->getAllAttachmentsByProcess($processId);
    }

}
