<?php

namespace Modules\Product\Models;

use App\Services\Upload\FileService;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Modules\Brand\Models\Brand;
use Modules\Canteen\Models\Canteen;
use Modules\Category\Models\Category;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Modules\Country\Models\Country;
use Modules\Order\Models\Order;
use Modules\Order\Models\OrderProduct;
use Modules\ProductType\Models\ProductType;
use Modules\Rate\Models\Rate;
use Modules\Store\Models\Store;
use Modules\User\Models\User;
use Modules\User\Services\AccountService;

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

    protected $fillable = [
        'status',
        'code',
        'cost',
        'count',
        'image',
        'canteen_id',
        'category_id'
    ];

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

    /**
     * Get current description of the the Room
     * @return HasOne
     */
    public function currentDescription(): HasOne
    {
        return $this->hasOne(ProductDescription::class)->where('language_id', currentLanguage()->id);
    }
    public function blockedByUsers(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'child_block_products', 'product_id', 'user_id');
    }
    public function setImageAttribute($value)
    {
        if ($value) {
            if (is_string($value)) {
                $this->attributes['image'] = $value;
            } else {
                $photo = FileService::uploadImage($value);
                $this->attributes['image'] = $photo;
            }
        } else {
            $this->attributes['image'] = request()->method() == 'post' ? 'logo.png' : $this->image;
        }
    }

    public function getPriceAttribute()
    {
        $cost = $this->cost_discount;
        if ($cost) {
            return $cost;
        }
        return $this->cost;
    }

}
