<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

class File extends Model
{
    protected $fillable = ['name', 'extension', 'mime', 'size', 'path', 'disk'];

    /**
     * Create a new file entry and store it.
     *
     * @param  mixed  $file
     * @param  string  $path
     * @param  string  $disk
     * @return File
     */
    public static function createFile($file, $path, $disk)
    {
        // Store the file on the given disk
        $filePath = Storage::disk($disk)->put($path, $file);

        // Store the file metadata in the database
        return self::create([
            'name' => $file->getClientOriginalName(),
            'extension' => $file->getClientOriginalExtension(),
            'mime' => $file->getMimeType(),
            'size' => $file->getSize(),
            'path' => $filePath,
            'disk' => $disk,
        ]);
    }

    public function relations()
    {
        return $this->hasMany(HasFile::class);
    }

    public function models()
    {
        return $this->morphToMany(Model::class, 'fileable', 'has_file', 'file_id', 'fileable_id')
            ->withPivot('data')
            ->withTimestamps();
    }
}
