<?php

namespace Yajny\Models;

use Illuminate\Database\Eloquent\Model;
use Spatie\Translatable\HasTranslations;
use Spatie\Searchable\Searchable;
use Spatie\Searchable\SearchResult;
use Yajny\Traits\HasSitemap;
use Yajny\Traits\SelectTranslations;

class CategoryCoupon extends Model implements Searchable
{
    use HasTranslations;
    use SelectTranslations;
    use HasSitemap;

    protected $table = 'categories_coupon';
    protected $primaryKey = 'id';
    public $translatable = ['name', 'description', 'h1_tag', 'h2_tag', 'meta_title', 'meta_desc', 'meta_kw'];
    public  $selColmns = ['id as coupon_cat_id','name','slug','id','parent_id','icon','offers_count' ];
    protected $fillable = ['filter','offers_count'];
    public  $apiSelColmns = ['id as coupon_cat_id','name','slug','id','parent_id','description','icon','filter','header_image' ,'offers_count'];

    public $casts = [
        'filter' => 'array',
        'recom_store' => 'array'
    ];

    public function parent() {
        return $this->hasOne(static::class, 'id','parent_id');
    }

      //each category might have multiple children
    public function children() {
    return $this->hasMany(static::class,'parent_id','id')->orderBy('name', 'asc');
    }

    public function getSearchResult(): SearchResult
    {
        $locale = app()->getLocale();
        if (request('region')) {
            $locale .= "-" . request('region');
        }
       $url =  ( config('app.purpose') == 'frontend' )  ? route('category.name', [$locale, $this->slug]) : '';


        return new \Spatie\Searchable\SearchResult(
           $this,
           $this->name_lang ?? $this->name,
           $url
        );
    }
    /**
     * @param $item
     * @return array
     */
    public static function mapItems($item)
    {
        $mappedData = [
            'id' => $item->id,
            'coupon_cat_id' => $item->id,
            'name' => [
                'en' =>  $item->getTranslation('name','en'),
                'ar' => $item->getTranslation('name','ar')
            ],
            'name_en' =>  $item->getTranslation('name','en'),
            'name_ar' => $item->getTranslation('name','ar'),
            'slug' => $item->slug,
            'parent_id' => $item->parent_id,
            "icon"=> $item->icon,
            "offers_count"=> $item->offers_count
        ];


        return $mappedData;
    }

}
