<?php

namespace App\Models;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class Picture extends Model
{
    //
    protected $fillable = ['path', 'cache', 'item_id', 'real_name', 'mime_type', 'size', 'updated_at'];
    protected $guarded = ['id'];
    public $timestamps = true; // для seeder дожна быть public

    public static function fromRequest(Item $item)
    {
        $pictures = [];
        $files = Input::file()['files'] ?? [];
        foreach ($files as $file) {
            $pictures[] = self::store($item, $file);
        }
        return $pictures;
    }


    public static function store(Item $item, UploadedFile $file): Picture
    {
        if (self::validatePicture($file)) {

            $prefix = 'items/item_' . $item->id;
            $picture = new self([
                'path' => Storage::disk('images')->putFile($prefix, $file),
                'item_id' => $item->id,
                'real_name' => $file->getClientOriginalName(),
                'mime_type' => $file->getClientOriginalExtension(),
                'size' => $file->getSize()
            ]);
            $picture->save();
            return $picture;
        }
        return redirect()->back()->with('message', 'Файл должен быть картинкой до 5 Mb');
    }

    public function item()
    {
        return $this->belongsTo(Item::class);
    }

    public static function validatePicture(UploadedFile $file): bool
    {
        $validFile['image'] = $file;
        $rules = ['image' => 'file|image|max:5000'];
        return Validator::make($validFile, $rules)->passes();
    }
}
