<?php

namespace Modules\Gallery\Models;

use App\Services\Upload\UploadService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Modules\Gallery\Enums\GalleryStatusEnum;
use Modules\Option\Models\Option;

class Gallery extends Model
{
    //use soft delete
    use SoftDeletes;

    protected $fillable =
    [
        'status','image','link','video'
    ];

    /**
     * Get current description of the the Room
     * @return HasOne
     */
    public function currentDescription() :HasOne
    {
        return $this->hasOne(GalleryDescription::class)->where('language_id', config('current_language_id'));
    }

    public function getVideoLinkAttribute()
    {
        $link = $this->link;
        if ($this->status == GalleryStatusEnum::VIDEO->value)
        {
            $link = asset($this->video);
        }
        return $link;
    }

    public function setImageAttribute($value): void
    {
        if ($value) {
            if (is_string($value)) {
                $this->attributes['image'] = $value;
            } else {
                $oldImage = request('old_image') ?? $this->image ?? null;
                $image = UploadService::upload($value, $oldImage, 'galleries');
                $this->attributes['image'] = $image;
            }
        } elseif ($this->image ?? false) {
            $this->attributes['image'] = $this->image;
        }
    }

    public function setVideoAttribute($value): void
    {
        if ($value) {
            if (is_string($value)) {
                $this->attributes['video'] = $value;
            } else {
                $oldVideo = request('old_video') ?? $this->video ?? null;
                $video = UploadService::upload($value, $oldVideo, 'galleries');
                $this->attributes['video'] = $video;
            }
        } elseif ($this->video ?? false) {
            $this->attributes['video'] = $this->video;
        }
    }

    public function getImageUrlAttribute(): ?string
    {
        return UploadService::url($this->image);
    }

    public function getVideoUrlAttribute(): ?string
    {
        return UploadService::url($this->video);
    }
}
