<?php

namespace Modules\Unit\Models;

use App\Models\Trait\HasCode;
use App\Services\Upload\UploadService;
use Modules\User\Models\User;
use Modules\Unit\Models\CountryDescription;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Modules\Area\Models\Area;
use Modules\Type\Models\Type;

class Unit extends Model
{
    //use soft delete
    use SoftDeletes, HasCode;

    protected $fillable = [
        'user_id', 'area_id', 'type_id', 'status', 'sold_status', 'image',
         'price', 'baths', 'space', 'net_space', 'floor', 'visits'
    ];


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

    public function user()
    {
        return $this->belongsTo(User::class)->withTrashed();
    }

    public function type()
    {
        return $this->belongsTo(Type::class)->withTrashed();
    }

    public function area()
    {
        return $this->belongsTo(Area::class)->withTrashed();
    }


    public function photos()
    {
        return $this->hasMany(UnitPhoto::class);
    }

    public function setImageAttribute($value)
    {
        if($value)
        {
            if(is_string($value))
            {
                $this->attributes['image'] = $value;
            }
            else
            {
                $oldImage= 'logo.png' != $this->image ?  $this->image : null;
                $image = UploadService::upload($value, $oldImage, 'units');
                $this->attributes['image'] = $image;
            }
        }
        else
        {
            $this->attributes['image'] = request()->method() == 'post'  ? 'logo.png' : $this->image;
        }
    }

    /**
     * Return Image URL
     * @return string|null
     */
    public function getImageUrlAttribute() : ?string
    {
        // dd(UploadService::url($this->image), $this->image);
        return UploadService::url($this->image);
    }

    /**
     * Return status text
     * @return string|null
     */
    public function getStatusTextAttribute() : ?string
    {
        $status= ($this->status ?? config('globals.default_unit_status'));
        return __('units.statuses.'.$status);
    }

    /**
     * Return sold_status text
     * @return string|null
     */
    public function getSoldStatusTextAttribute() : ?string
    {
        $status= ($this->sold_status ?? config('globals.default_sold_status'));
        return __('units.sold_statuses.'.$status);
    }
}
