<?php

namespace Modules\Product\Models;

use Modules\Brand\Models\Brand;
use Modules\Category\Models\Attribute;
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\Offer\Models\Offer;
use Modules\Offer\Models\OfferProduct;
use Modules\Offer\Services\OfferService;
use Modules\Order\Models\Order;
use Modules\Order\Models\OrderProduct;
use Modules\Product\Services\ProductService;
use Modules\ProductType\Models\ProductType;
use Modules\Rate\Models\Rate;
use Modules\Store\Models\Store;
use Modules\User\Services\AccountService;
use Modules\Warehouse\Models\Warehouse;

class Product extends Model
{
    //use soft delete
    use SoftDeletes;
    private AccountService $accountService;
    private OfferService $offerService;
    private ProductService $productService;
    public function __construct(array $attributes = [] )
    {
        parent::__construct($attributes);
        $this->accountService = app(AccountService::class);
        $this->offerService = app(OfferService::class);
        $this->productService = app(ProductService::class);
    }
        protected $fillable = [
        'code','status_active',	'image','discount_percentage','category_id', 'views',	'sub_category_id'	,'store_id'	,'brand_id'	,'attribute_id','max_count_order'
    ];
    public function photos()
    {
        return $this->hasMany(ProductPhoto::class);
    }


    public function items()
    {
        return $this->hasMany(ProductItem::class);
    }
    public function rates()
    {
        return $this->hasMany(Rate::class,'product_id');
    }
    public function warehouses()
    {
        return $this->belongsToMany(Warehouse::class,'product_warehouses');
    }
    public function offers()
    {
        return $this->belongsToMany(Offer::class,'offer_products');
    }
    public function offer()
    {
        return $this->offerService->productOffer($this->id);
    }
    public function prooductWarehouses()
    {
        return $this->hasMany(ProductWarehouse::class,'product_id');
    }
    public function productOptions()
    {
        return $this->hasMany(ProductWarehouse::class,'product_id')->whereNotNull('option_id')->whereNotNull('attribute_id')->with(['attribute','option']);
    }

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

    public function attribute()
    {
        return $this->belongsTo(Attribute::class, 'attribute_id')->withTrashed();
    }

    public function store()
    {
        return $this->belongsTo(Store::class, 'store_id')->withTrashed();
    }


    public function brand()
    {
        return $this->belongsTo(Brand::class, 'brand_id')->withTrashed();
    }

    public function productType()
    {
        return $this->belongsTo(ProductType::class, 'product_type_id')->withTrashed();
    }

    public function subCategory()
    {
        return $this->belongsTo(Category::class, 'sub_category_id')->withTrashed();
    }

    public function favorites()
    {
        return $this->hasMany(Favorite::class,'product_id');
    }

    public function favorited()
    {
        $account = $this->accountService->getAccount();
        $favorite = $this->hasOne(Favorite::class)->where('user_status',$account['status'])->where('user_id',$this->id)->where('product_id',$this->id)->first();
        return $favorite;
    }
    public function rated()
    {
        $account = $this->accountService->getAccount();
        $rate = $this->hasOne(Rate::class)->where('user_status',$account['status'])->where('user_id',$this->id)->where('product_id',$this->id)->first();
        return $rate;
    }

    public function orders()
    {
        return $this->hasMany(OrderProduct::class,'product_id');
    }

    /**
     * Get current description of the the Room
     * @return HasOne
     */
    public function currentDescription(): HasOne
    {
        return $this->hasOne(ProductDescription::class)->where('language_id', config('current_language_id'));
    }
//
//    public function getImageAttribute()
//    {
//        $image = $this->photos()->first() ? asset($this->photos()->first()->image) : asset('logo.png');
//        return $image;
//    }

    public function getMaxCountAttribute()
    {
        $count = !is_null($this->max_count_order) ? $this->max_count_order : $this->category->max_count_order;
        return $count;
    }

    public function getSoldCountAttribute()
    {
        return OrderProduct::where('product_id',$this->id)->sum('count');
    }

    public function getCostAttribute()
    {
        $account = $this->accountService->getAccount();
        $user = $account['user'];
        $data = [
            'user'=>$user,
            'user_status'=>$account['status']
        ];
        if (count($this->productOptions))
        {
            $data['option_id'] = $this->productOptions->first()->option_id;
        }
        return $this->productService->productCost($data,$this);
    }

    public function getPriceAttribute()
    {
        $account = $this->accountService->getAccount();
        $user = $account['user'];
        $data = [
            'user'=>$user,
            'user_status'=>$account['status']
        ];
        if (count($this->productOptions))
        {
            $data['option_id'] = $this->productOptions->first()->option_id;
        }
        return $this->productService->productPrice($data,$this);
    }

    public function getPricesAttribute()
    {
        $account = $this->accountService->getAccount();
        $user = $account['user'];
        $data = [
            'user'=>$user,
            'user_status'=>$account['status']
        ];
        if (count($this->productOptions))
        {
            $data['option_id'] = $this->productOptions->first()->option_id;
        }
        return $this->productService->productPrice($data,$this);
    }


    public function getRateAttribute()
    {
        $account = $this->accountService->getAccount();
        $count = Rate::where('product_id',$this->id)->count();
        if ($count)
        {
            $rate = Rate::where('product_id',$this->id)->sum('rate') / $count;
        }
        else
        {
            $rate = 0;
        }
        return number_format($rate,1);
    }


    public function getRateCountAttribute()
    {
        $account = $this->accountService->getAccount();
        $rate = Rate::where('product_id',$this->id)->count();
        return $rate;
    }

    public function getCanRateAttribute()
    {
        $account = $this->accountService->getAccount();
        $show = true;
        $rate = Rate::where('user_id',$account['user']->id)->where('user_status',$account['status'])->where('product_id',$this->id)->first();

        if ($rate)
        {
            $show = false;
        }
        else
        {
            $order = Order::join('order_products AS op', 'orders.id', 'op.order_id')
                ->where('orders.user_id',$account['user']->id)
                ->where('orders.user_status',$account['status'])
                ->where('op.product_id',$this->id)
                ->count();
            if (!$order)
            {
                $show = false;
            }

        }
        return $show;
    }
}
