<?php

namespace App\Models;

use App\Traits\HasSortsTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

class Files extends Model
{
    use HasFactory, HasSortsTrait;

    protected $table = 'files';

    protected $fillable = [
        'titulo',
        'ruta',
        'archivable_id',
        'archivable_type',
        'borrador',
        'key'
    ];

    public function archivable()
    {
        return $this->morphTo();
    }

    public function uploadBorrador(UploadedFile $archivo, String $model, $key = null,  $id = null)
    {
        $extension = $archivo->getClientOriginalExtension();
        $nombre = time();
        $file_name = $nombre . '.' . $extension;
        $ruta = 'files/' . $file_name;

        Storage::put($ruta, file_get_contents($archivo));

        $this->titulo = $archivo->getClientOriginalName();
        $this->ruta = $ruta;
        $this->archivable_type = $model;
        $this->archivable_id = $id;
        $this->key = $key;
        $this->borrador = true;
        $this->save();

        return $this;
    }

    public function upload(UploadedFile $archivo, String $model, $id, $key = null)
    {
        $extension = $archivo->getClientOriginalExtension();
        $nombre = time();
        $file_name = $nombre . '.' . $extension;
        $ruta = 'files/' . $file_name;

        Storage::put($ruta, file_get_contents($archivo));

        $this->titulo = $archivo->getClientOriginalName();
        $this->ruta = $ruta;
        $this->archivable_type = $model;
        $this->archivable_id = $id;
        $this->key = $key;
        $this->borrador = false;
        $this->save();

        return $this;
    }

    public function delete()
    {
        if ($this->ruta) {
            Storage::delete($this->ruta);
        }

        return parent::delete();
    }

    public function download()
    {
        if ($this->ruta && Storage::exists($this->ruta)) {
            $archivo = Storage::get($this->ruta);
            $mime = Storage::mimeType($this->ruta);
            $tamaño = Storage::size($this->ruta);

            return $archivo;
        }
        return null;
    }

    public function scopeBorrador($query)
    {
        return $query->where('borrador', true);
    }
}
