<?php

namespace Yajny\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use Spatie\Translatable\HasTranslations;
use Yajny\Traits\HasCurrency;
use Yajny\Traits\SelectTranslations;

class StoreCashback extends Model
{
    use HasTranslations, SelectTranslations, HasCurrency;

    protected $table = 'store_cashback';
    protected $primaryKey = 'id';
	protected $foreignKey = 'store_id';
    public $translatable = ['title', 'description','exclusion','link'];

    public $guarded = ['id'];
    public $timestamps = false;
    public  $selColmns = ['id','store_id','title', 'description','exclusion','image','thumbnail','rate_type','rate_amount'];
    protected $appends = ['rate_amount_text'];
	public function store()
    {
        return $this->belongsTo('Yajny\Models\Store',  'id', 'store_id')->withoutGlobalScopes();
    }


    protected static function boot() {

        parent::boot();

        static::addGlobalScope('enabled', function (Builder $builder) {
            $builder->where('enabled', 1 );
        });
    }

    public function getRateAmountTextAttribute()
    {
        try {
            return (($this->rate_type == 'percent') ? round($this->rate_amount, 2) . '%' : $this->userCurrencyFormat($this->rate_amount));
        } catch (\Exception $exception) {
            Log::error('failed to handle rate_amount', ['storeCashback' => $this->toArray(), 'exception' => $exception]);
            return null;
        }
    }

    public static function mapItems($item)
    {
        return [
            'id' => $item->id,
            'store_id' => $item->store_id,
            'title' => $item->getTranslations('title'),
            'description' => $item->getTranslations('description'),
            'exclusion' => $item->getTranslations('exclusion'),
            'link' => $item->getTranslations('link'),
            'rate_type' => $item->rate_type,
            'rate_amount' => $item->rate_amount,
            'rate_amount_text' => $item->rate_amount_text,
            'image' => $item->image,
            'thumbnail' => $item->thumbnail
        ];
    }
}
