<?php

namespace Modules\Page\Models;

use App\Services\Upload\UploadService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;

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

    protected $fillable = [
        'image',
        'image_2',
        'image_3',
        'image_4',
        'code',
        'value_1',
        'value_2',
        'value_3',
        'value_4',
        'status',
    ];


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

    public function setImageAttribute($value)
    {
        $this->attributes['image'] = $this->prepareImageValue($value, $this->attributes['image'] ?? null);
    }

    public function setImage2Attribute($value)
    {
        $this->attributes['image_2'] = $this->prepareImageValue($value, $this->attributes['image_2'] ?? null);
    }

    public function setImage3Attribute($value)
    {
        $this->attributes['image_3'] = $this->prepareImageValue($value, $this->attributes['image_3'] ?? null);
    }

    public function setImage4Attribute($value)
    {
        $this->attributes['image_4'] = $this->prepareImageValue($value, $this->attributes['image_4'] ?? null);
    }

    private function prepareImageValue($value, ?string $current): ?string
    {
        if ($value) {
            if (is_string($value)) {
                return $value;
            }

            $oldPhoto = $current && $current !== 'logo.png' ? $current : null;
            return UploadService::upload($value, $oldPhoto, 'pages');
        }

        return $current;
    }

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

    public function getImage2UrlAttribute(): ?string
    {
        return UploadService::url($this->image_2 ?? null);
    }

    public function getImage3UrlAttribute(): ?string
    {
        return UploadService::url($this->image_3 ?? null);
    }

    public function getImage4UrlAttribute(): ?string
    {
        return UploadService::url($this->image_4 ?? null);
    }
}
