<?php

namespace Yajny\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Spatie\Searchable\Searchable;
use Spatie\Searchable\SearchResult;
use Spatie\Translatable\HasTranslations;
use Yajny\Scopes\StatusScope;
use Yajny\Traits\HasCurrency;
use Yajny\Traits\HasSitemap;
use Yajny\Traits\SelectTranslations;

class Store extends Model implements Searchable
{
    use HasTranslations, SelectTranslations, HasCurrency, HasSitemap;

    /**
     * @var string
     */
    protected $table = 'stores';
    /**
     * @var string
     */
    protected $primaryKey = 'id';
    /**
     * @var string[]
     */
    protected $guarded = ['id'];
    /**
     * @var string[]
     */
    protected $appends = ['was_cashback_text', 'cashback_text', 'is_favourite'];

    /**
     * @var string[]
     */
    public $translatable = ['name', 'about_store', 'more_about_store_title', 'more_about_store', 'sp_terms_title', 'sp_terms', 'cb_terms', 'secrets', 'hashtag', 'h1_tag', 'h2_tag', 'h3_tag', 'meta_title', 'meta_desc', 'meta_kw', 'homepage'];
    /**
     * @var string[]
     */
    public $selColmns = ['id', 'slug', 'background_color', 'text_color', 'logo',  'offers_count', 'current_cb', 'amount_type', 'cb_status', 'tracking_channels', 'cb_mobile', 'cb_coupon', 'related_stores', 'visits', 'current_cb as user_cb', 'name', 'amount_type', 'rate_type', 'was_cb', 'offers_count', 'domain_name', 'checkout_url', 'categories','cb_valid_period','is_featured','status'];
    /**
     * @var string[]
     */
    public $apiSelColmns = ['id', 'slug', 'logo', 'offers_count', 'current_cb', 'amount_type', 'cb_status', 'tracking_channels', 'cb_mobile', 'cb_coupon', 'related_stores', 'visits', 'current_cb as user_cb', 'name', 'amount_type', 'rate_type', 'was_cb', 'about_store', 'sp_terms_title', 'sp_terms', 'cb_terms', 'filter', 'rate_count', 'rate_stars', 'header_image', 'offers_count', 'more_about_store_title', 'more_about_store','cb_valid_period','is_featured','status'];
    /**
     * @var string[]
     */
    public $casts = [
        'filter' => 'array'
    ];

    /**
     *
     */
    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope(new StatusScope());
    }
    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function store_categories()
    {
        return $this->hasMany('Yajny\Models\StoreCategories', 'id', 'store_id');
    }


    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function store_cashback()
    {
        return $this->hasMany('Yajny\Models\StoreCashback', 'store_id', 'id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function draft_store_cashback()
    {
        return $this->hasMany('Yajny\Models\StoreCashback', 'store_id', 'id')->where('enabled', 0)->withoutGlobalScopes();
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function store_coupons()
    {
        return $this->hasMany('Yajny\Models\Coupon', 'store_id', 'id')->where('type', '=', 'coupon');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function draft_store_coupons()
    {
        return $this->hasMany('Yajny\Models\Coupon', 'store_id', 'id')->where('type', '=', 'coupon')->where('status', 'draft')->withoutGlobalScopes();
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function store_offers()
    {
        return $this->hasMany('Yajny\Models\Coupon', 'store_id', 'id')->where('type', '=', 'offer');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function coupons()
    {
        return $this->hasMany('Yajny\Models\Coupon', 'store_id', 'id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function store_contents()
    {
        return $this->hasMany(StoreContent::class, 'store_id', 'id');
    }


    /**
     * @return SearchResult
     */
    public function getSearchResult(): SearchResult
    {
        $locale = app()->getLocale();
        if (request('region')) {
            $locale .= "-" . request('region');
        }
        $url = (config('app.purpose') == 'frontend') ? route('new.store.page', [$locale, $this->slug]) : '';

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

    /**
     * @return mixed
     */
    public static function sitemap()
    {
        return static::where('exclude_sitemap', 0)->select('slug', 'updated_at', 'created_at', 'region_code')->get();
    }

    /**
     * @param $originalValue
     * @return string
     */
    public function getWasCbAttribute($originalValue)
    {
        $wasCashbackType = explode('|', $originalValue)[0] ?? $this->amount_type ?? 'percent';
        return implode('|', [$wasCashbackType, $this->current_cb / 2]);
    }

    /**
     * @return string|null
     */
    public function getCashbackTextAttribute()
    {
        try {
            return (($this->amount_type == 'percent') ? round($this->current_cb, 2) . '%' : $this->userCurrencyFormat($this->current_cb));
        } catch (\Exception $exception) {
            Log::error('failed to handle current_cb', ['store' => $this->toArray(), 'exception' => $exception]);
            return null;
        }
    }

    /**
     * @return string|null
     */
    public function getWasCashbackTextAttribute()
    {
        try {
            $was_cb = explode('|', $this->was_cb);
            if (count($was_cb) < 2)
                return null;

            $amount_type = $was_cb[0];
            $cashback_amount = $this->current_cb / 2;

            if ($cashback_amount >= $this->current_cb)
                return null;

            if ($cashback_amount == 0)
                return null;
            return (($amount_type == 'percent') ? round($cashback_amount, 2) . '%' : $this->userCurrencyFormat($cashback_amount));
        } catch (\Exception $exception) {
            Log::error('failed to handle was_cb', ['store' => $this->toArray(), 'exception' => $exception]);
            return null;
        }
    }

    /**
     * @param $item
     * @return array
     */
    public static function mapItems($item)
    {
        $categoriesStr= (array)json_decode(str_replace('"','',$item->categories), true) ;
        $listcategs=[];
        foreach($categoriesStr as $key) {
            $res = Category::select("id", "name")->where("categories.id", "$key")->first();
            $listcategs[] = $res;
        }
        return [
            'id' => $item->id,
            'name' => [
                'ar' => $item->name_ar ?? $item->getTranslation('name', 'ar'),
                'en' => $item->name_en ?? $item->getTranslation('name', 'en')
            ],
            'name_en' => $item->name_en ?? $item->getTranslation('name', 'en'),
            'name_ar' => $item->name_ar ?? $item->getTranslation('name', 'ar'),
            'name_lang' => $item->name_lang ?? $item->name,
            'slug' => $item->slug,
            'logo' => $item->logo,
            'current_cb' => $item->current_cb,
            'cashback_text' => $item->cashback_text,
            'cb_status' => $item->cb_status,
            'cb_valid_period' => $item->cb_valid_period,
            'was_cb' => $item->was_cb,
            'was_cashback_text' => $item->was_cashback_text,
            'amount_type' => $item->amount_type,
            'rate_type' => $item->rate_type,
            'background_color' => $item->background_color,
            'text_color' => $item->text_color,
            'tracking_channels' => $item->tracking_channels,
            'is_favourite' => $item->is_favourite,
            'categories' =>$listcategs
        ];
    }

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

    /**
     * @param $region_code
     */
    public function replaceStoreContent($region_code)
    {
        $regionalContent = $this->store_contents()->where('store_contents.region_code', '=', $region_code)->first();
        if ($regionalContent) {
            $storeAttributesNames = array_keys($this->getAttributes());
            foreach ($regionalContent->getAttributes() as $key => $value) {
                if (!in_array($key, StoreContent::$nonReplaceableAttributes) && in_array($key, $storeAttributesNames)) {
                    $this->replaceTranslations($key, $regionalContent->getTranslations($key));
                }
            }
        }
    }
}
