<?php

namespace App\Models;

use App\Http\Traits\hasFilter;
use App\Http\Traits\HashIdTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Product extends Model
{
    use HasFactory, SoftDeletes, HashIdTrait, hasFilter;

    protected $table    =   'products';
    protected $guarded  =   ['id'];
    protected $appends  =   ['description', 'share_price', 'default_image'];

    public function shop() {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function category() {
        return $this->belongsTo(Category::class, 'category_id', 'id');
    }

    public function getDescriptionAttribute() {
        return is_null($this->en_description) || app()->getLocale() == 'ar' ? $this->ar_description : $this->en_description;
    }

    public function images() {
        return $this->morphMany(Image::class,'imageable');
    }

    public function favorite() {
        return $this->morphMany(Favorite::class, 'favoriteable');
    }

    public function getDefaultImageAttribute() {
        $image = optional($this->images()->where('is_default', 1)->first())->path;
        return $this->attributes['default_image'] = $image? asset('storage/'.$image) : asset('dashboard/images/logo/shop.png');
    }

    public function getSharePriceAttribute() {
        $price =  $this->price ;
        $currency = $this->shop->country->currency;
        return "{$price} .'-'. {$currency}";
    }

    public function notificationData() {
        return [
            'image' =>  $this->default_image,
            'name'  =>  'Blockat Product',
            'id'    =>  $this->id
        ];
    }
}
