<?php

namespace App\Traits;

use App\Classes\Constants;
use App\Classes\Service\Documents\RouteToNameDocuments;
use App\Classes\Service\Files\Base64Uploader;
use App\Classes\Service\Files\DeleteFile;
use App\Models\Document;
use Carbon\Carbon;

trait DocumentTrait
{

    abstract function getType();


    abstract function getReferenceId();


    abstract function getDocumentType();


    public function listDocuments(array $exclude = []) {
        return Document::where('type', $this->getType())
            ->where('reference_id', $this->getReferenceId())
            ->where('document_type', Constants::DOCUMENT_TYPES[$this->getDocumentType()]['id'])
            ->whereNotIn('name', $exclude);

    }

    public function deleteDocuments(array $exclude = []){

        $documents = (new RouteToNameDocuments())->execute(
            $exclude,
            Constants::DOCUMENT_TYPES[$this->getDocumentType()]['path']);

        $deleteDocuments = $this->listDocuments($documents);

        (new DeleteFile())->execute(Constants::UPLOAD_PATH.Constants::DOCUMENT_TYPES[$this->getDocumentType()]['path'], $deleteDocuments->get()->pluck('name')->toArray());

        $deleteDocuments->delete();

    }

    public function addDocuments(array $documents){

        $data = array_map(function($document){
            return [
                'type' => $this->getType(),
                'reference_id' => $this->getReferenceId(),
                'document_type' => Constants::DOCUMENT_TYPES[$this->getDocumentType()]['id'],
                'name' => (new Base64Uploader())->execute(Constants::UPLOAD_PATH.Constants::DOCUMENT_TYPES[$this->getDocumentType()]['path'], $document),
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now()
            ];
        }, $documents);

        Document::insert($data);
    }

}