<?php

namespace Modules\Product\Models;

use Modules\Brand\Models\Brand;
use DB;
use Modules\Category\Models\Category;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Modules\ContactList\Enums\ContactStatusEnum;
use Modules\Country\Models\Country;
use Modules\Deal\Models\Deal;
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\Target\Models\Target;
use Modules\User\Services\AccountService;
use Modules\Warehouse\Models\Warehouse;
use Modules\Deal\Enums\DealStatusEnum;

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->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','lock'
    ];
    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 category()
    {
        return $this->belongsTo(Category::class, 'category_id')->withTrashed();
    }

    public function targetYear($year,$emplyoee_id)
    {
        return Target::whereHas('product', function ($query) {
            $query->whereNull('deleted_at');
        })->where('year',$year)->where('product_id',$this->id)->where('employee_id',$emplyoee_id)->sum('target');
    }

    public function targetEmp($year, $month , $emplyoee_id)
    {
        if($month == 'Q1')
        {
            $month = [1,2,3];
        }
        elseif($month == 'Q2')
        {
            $month = [4,5,6];
        }
        elseif($month == 'S1')
        {
            $month = [1,2,3,4,5,6];
        }
        elseif($month == 'Q3')
        {
            $month = [7,8,9];
        }
        elseif($month == 'YTD')
        {
            $month = [1,2,3,4,5,6,7,8,9];
        }
        elseif($month == 'Q4')
        {
            $month = [10,11,12];
        }
        elseif($month == 'S2')
        {
            $month = [7,8,9,10,11,12];
        }
        elseif($month == 'FY')
        {
            $month = [1,2,3,4,5,6,7,8,9,10,11,12];
        }
        $builder = Target::query();
        $builder->whereHas('product', function ($query) {
            $query->whereNull('deleted_at');
        });
        if(is_array($month))
        {
            $builder->whereIn('month',$month);
        }
        else
        {
            $builder->where('month',$month);
        }
        $target = $builder->where('year',$year)->where('employee_id',$emplyoee_id)->where('product_id',$this->id)->sum('target');

        return $target;
    }

    public function salesEmp($year, $month , $emplyoee_id)
    {
        if($month == 'Q1')
        {
            $month = [1,2,3];
        }
        elseif($month == 'Q2')
        {
            $month = [4,5,6];
        }
        elseif($month == 'S1')
        {
            $month = [1,2,3,4,5,6];
        }
        elseif($month == 'Q3')
        {
            $month = [7,8,9];
        }
        elseif($month == 'YTD')
        {
            $month = [1,2,3,4,5,6,7,8,9];
        }
        elseif($month == 'Q4')
        {
            $month = [10,11,12];
        }
        elseif($month == 'S2')
        {
            $month = [7,8,9,10,11,12];
        }
        elseif($month == 'FY')
        {
            $month = [1,2,3,4,5,6,7,8,9,10,11,12];
        }
        $builder = Deal::query();
        $builder->where('status',DealStatusEnum::Payment_Received->value);
        // $builder->whereHas('contactList',function ($query){
        //     $query->where('status',ContactStatusEnum::PROJECT_WON->value);
        // });
        if(is_array($month))
        {
            $builder->whereIn(DB::raw('MONTH(start_date)'), $month);
        }
        else
        {
            $builder->whereMonth('start_date',$month);
        }
        $sales = $builder->whereYear('start_date',$year)->where('employee_id',$emplyoee_id)->where('product_id',$this->id)->sum('amount');

        return $sales;
    }
    public function percentAcheived($year, $month , $emplyoee_id)
    {
        if($month == 'Q1')
        {
            $month = [1,2,3];
        }
        elseif($month == 'Q2')
        {
            $month = [4,5,6];
        }
        elseif($month == 'S1')
        {
            $month = [1,2,3,4,5,6];
        }
        elseif($month == 'Q3')
        {
            $month = [7,8,9];
        }
        elseif($month == 'YTD')
        {
            $month = [1,2,3,4,5,6,7,8,9];
        }
        elseif($month == 'Q4')
        {
            $month = [10,11,12];
        }
        elseif($month == 'S2')
        {
            $month = [7,8,9,10,11,12];
        }
        elseif($month == 'FY')
        {
            $month = [1,2,3,4,5,6,7,8,9,10,11,12];
        }
        $builder = Target::query();
        $builder->whereHas('product', function ($query) {
            $query->whereNull('deleted_at');
        });
        if(is_array($month))
        {
            $builder->whereIn('month',$month);
        }
        else
        {
            $builder->where('month',$month);
        }
        $target = $builder->where('year',$year)->where('employee_id',$emplyoee_id)->where('product_id',$this->id)->sum('target');

        $builder = Deal::query();
        $builder->where('status',DealStatusEnum::Payment_Received->value);
        // $builder->whereHas('contactList',function ($query){
        //     $query->where('status',ContactStatusEnum::PROJECT_WON->value);
        // });
        if(is_array($month))
        {
            $builder->whereIn(DB::raw('MONTH(start_date)'), $month);
        }
        else
        {
            $builder->whereMonth('start_date',$month);
        }
        $sales = $builder->whereYear('start_date',$year)->where('employee_id',$emplyoee_id)->where('product_id',$this->id)->sum('amount');
        if($target == 0 && $sales == 0)
        {
            return 0;
        }
        elseif($sales != 0 && $target == 0)
        {
            return 100;
        }
        return ($sales/$target) * 100;
    }

    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', currentLanguage()->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;
    }
}
