<?php

namespace Yajny\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Request;
use Spatie\Searchable\Searchable;
use Spatie\Searchable\SearchResult;
use Spatie\Translatable\HasTranslations;
use Yajny\Member\Models\Member;
use Yajny\Traits\SelectTranslations;


class Coupon extends Model implements Searchable
{
    use HasTranslations, SelectTranslations;

    protected $table = 'coupons';
    protected $primaryKey = 'id';
    public $translatable = ['title', 'description', 'promo_text', 'link', 'highlight_title1', 'highlight_title2'];

    public $selColmns = ['id,id as coupon_id', 'store_id', 'type', 'status', 'UNIX_TIMESTAMP(expiry_date) as expiry', 'expiry_date', 'code', 'title', 'description', 'promo_text', 'thumbnail', 'is_exclusive', 'is_featured', 'is_recommended', 'highlight_title1', 'highlight_title2' ];

    protected $guarded = ['id'];

    protected $appends = ['is_favourite','reaction'];

    /**
     *
     */
    protected static function boot()
    {

        parent::boot();

        static::addGlobalScope('status', function (Builder $builder) {
            $builder->where('status', 'publish')->where('for_media_buyer',false)->whereRaw(' IFNULL(expiry_date,CURRENT_DATE) >= CURRENT_DATE ');
        });
    }

    /**
     * @return mixed
     */
    public function couponStore()
    {
        return $this->hasOne('Yajny\Models\Store', 'id', 'store_id')->withoutGlobalScopes();
    }

    /**
     * @return mixed
     */
    public function coupon_store()
    {
        return $this->belongsTo('Yajny\Models\Store', 'store_id', 'id')->withoutGlobalScopes();
    }


    /**
     * @return mixed
     */
    public function brands()
    {
        return $this->belongsToMany('Yajny\Models\Brand', 'coupon_brands', 'coupon_id', 'brand_id');
    }

    /**
     * @return mixed
     */
    public function tags()
    {
        return $this->belongsToMany('Yajny\Models\Tag', 'coupon_tags', 'coupon_id', 'tag_id');
    }

    /**
     * @return mixed
     */
    public function categories()
    {
        return $this->belongsToMany('Yajny\Models\CategoryCoupon', 'coupon_categories', 'coupon_id', 'cat_id');
    }

    /**
     * @return mixed
     */
    public function store_coupon()
    {
        return $this->hasMany('Yajny\Models\Store', 'id', 'store_id');
    }

    /**
     * @return mixed
     */
    public function store_by_coupon()
    {
        return $this->hasOne('Yajny\Models\Store', 'id', 'store_id');
    }

    /**
     * @param $type
     */
    public function filterType($type)
    {
        if ($type != '') {
            $this->type = $type;
        }
    }

    // create global scope for expired and status

    /**
     * @return SearchResult
     */
    public function getSearchResult(): SearchResult
    {
        // $Coupon     = new Coupon;
        // $Coupons = $Coupon->with('couponStore')->get();
        // $this $$this->hasOne('Yajny\Models\Store','id','store_id');

        $url = (config('app.purpose') == 'frontend') ? route('search.result', $this->title_lang ?? $this->title) : '';

        return new \Spatie\Searchable\SearchResult(
            $this,
            $this->title_lang ?? $this->title,
            $url
        );
    }

    /**
     * @param $item
     * @param bool $getStore
     * @return array
     */
    public static function mapItems($item, $getStore = true)
    {
        $mappedData = [
            'id' => $item->id,
            'store_id' => $item->coupon_store->id,
            'store_name' => [
                'en' =>  $item->coupon_store->getTranslation('name','en'),
                'ar' => $item->coupon_store->getTranslation('name','ar')
            ],
            'store_slug' => $item->coupon_store->slug,
            'store_logo' => $item->coupon_store->logo,
            'coupon_code' => $item->code,
            'coupon_title' => [
                'en' =>  $item->getTranslation('title','en'),
                'ar' => $item->getTranslation('title','ar')
            ],
            'title_en' => $item->getTranslation('title','en'),
            'title_ar' => $item->getTranslation('title','ar'),
            'title_lang' => $item->title_lang,
            'current_cashback' => $item->coupon_store->current_cb,
            'cashback_text' => $item->coupon_store->cashback_text,
            'rate_type' => $item->coupon_store->rate_type,
            'amount_type' => $item->coupon_store->amount_type,
            'promo_text' => [
                'en' => $item->getTranslation('promo_text','en'),
                'ar' => $item->getTranslation('promo_text','ar')
            ],
            'promo_text_en' => $item->getTranslation('promo_text','en'),
            'promo_text_ar' => $item->getTranslation('promo_text','ar'),
            'promo_text_lang' => $item->promo_text_lang,
            'background_color' => $item->coupon_store->background_color,
            'text_color' => $item->coupon_store->text_color,
            'thumbnail' => $item->thumbnail,
            'is_favourite' => $item->is_favourite,
            'is_featured' => $item->is_featured,
            'is_exclusive' => $item->is_exclusive,
            'is_recommended' => $item->is_recommended,
            'expiry_date' => $item->expiry_date,
            'status' => $item->status,
            'type' => $item->type,
            "like_count" => $item->like,
            "dislike_count" => $item->dislike,
            "reaction" => $item->reaction,
            'highlight_title1' => [
                'en' => $item->getTranslation('highlight_title1','en') ,
                'ar' =>  $item->getTranslation('highlight_title1','ar')
            ]  ,
            'highlight_title2' => [
                'en' => $item->getTranslation('highlight_title2','en') ,
                'ar' =>  $item->getTranslation('highlight_title2','ar')
            ]
        ];

        if ($getStore)
            $mappedData['coupon_store'] = Store::mapItems($item->coupon_store);

        return $mappedData;
    }

    /**
     * @return mixed
     */
    public function getIsFavouriteAttribute()
    {
        return \Yajny\Member\Models\UserFavourite::isFavourite(request('user_id'), \Yajny\Member\Entities\FavouriteTypes::FAV_OBJECT_TYPE_COUPON, $this->id);
    }

    /**
     * @return mixed
     */
    public function getReactionAttribute()
    {
        if(request('user_id')){
            $member = Member::find(request('user_id'));

            if($member){
                return $this->getReaction( $this, $member);
            }
        }
        return null ;
    }


    /**
     * @param $coupon
     * @param $member
     * @return string|null
     */
    public function getReaction( $coupon, $member)
    {
        $reaction = null;
        if ($member){

            $hasLiked = $member->likedCoupons->contains($coupon);
            $hasDisliked = $member->dislikedCoupons->contains($coupon);

            if ($hasLiked) {
                $reaction = 'like';
            }
            if ($hasDisliked) {
                $reaction = 'dislike';
            }
        }
        return $reaction;
    }



    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function likedByUsers()
    {
        return $this->belongsToMany(Yajny\Member\Models\Member::class, 'coupon_user' )->where('reaction', 'like');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function dislikedByUsers()
    {
        return $this->belongsToMany(Yajny\Member\Models\Member::class, 'coupon_user' )->where('reaction', 'dislike');
    }

}
