<?php namespace TPS\Birzha\Models;

use Cms\Classes\Page as CmsPage;
use Cms\Classes\Theme;
use Model;
use DB;

/**
 * Model
 */
class Category extends Model
{

    use \October\Rain\Database\Traits\Validation;

    use \October\Rain\Database\Traits\SoftDelete;

    use \October\Rain\Database\Traits\Sortable;

    protected $dates = ['deleted_at'];

    public $implement = ['@RainLab.Translate.Behaviors.TranslatableModel'];

    /**
     * @var string The database table used by the model.
     */
    public $table = 'tps_birzha_categories';

    /**
     * @var array Validation rules
     */
    public $rules = [
        'name'   => 'required',
        'sort_order'   => 'required',
        'slug'   => ['required', 'regex:/^[a-z0-9\/\:_\-\*\[\]\+\?\|]*$/i', 'unique:tps_birzha_categories'],
        'status' => 'required',
    ];

    public $translatable = ['name',['slug', 'index' => true]];

     public $hasMany = [
        'filter_group' => ['TPS\Birzha\Models\FilterGroups', 'key' => 'category_id'],
        'subs' => ['TPS\Birzha\Models\Category', 'key' => 'primary_key']
    ];
    
    public $belongsTo = [
        'parent'       => ['TPS\Birzha\Models\Category','key' => 'primary_key'],
    ];


    public $belongsToMany = [
        'products' => [
            'TPS\Birzha\Models\Product',
            'table'=>'tps_birzha_product_categories'
        ],
        'users' => [
            'RainLab\User\Models\User',
            'table'=>'tps_birzha_users_categories',
        ],
    ];

    public function scopeActive($query)
    {
        return $query->where('status', 1);
    }
    
    public function scopeUserCategory($query)
    {
        return $query->where('status', 1)->orderBy('id', 'DESC')->select(DB::raw("CONCAT(id, '. ', name, ' --- ', slug, ' / ', primary_key) AS name"),'id', 'primary_key');
    }

    public function scopeActiveAndParent($query)
    {
        return $query->where('status', 1)->where('primary_key',0);
    }
    

    public function scopeActiveAndParentFirstFour($query)
    {
        return $query->where('status', 1)->where('primary_key', 0)->offset(0)->limit(4);
    }

    public function scopeActiveAndParentLastFour($query)
    {
        return $query->where('status', 1)->where('primary_key', 0)->offset(4)->limit(8);
    }

    public static function getMenuTypeInfo($type){
        $result = [];

        if ($type == 'category') {
            $result = [
                'references'   => Category::active()->pluck('name','id'),
                'nesting'      => true,
                'dynamicItems' => true
            ];
        }

        if ($type == 'all-categories') {
            $result = [
                'dynamicItems' => true
            ];
        }

        if ($result) {
            $theme = Theme::getActiveTheme();

            $pages = CmsPage::listInTheme($theme, true);
            $cmsPages = [];
            foreach ($pages as $page) {
                if (!$page->hasComponent('categories')) {
                    continue;
                }

                /*
                 * Component must use a category filter with a routing parameter
                 * eg: categoryFilter = "{{ :somevalue }}"
                 */
                $properties = $page->getComponentProperties('blogPosts');
                if (!isset($properties['categoryFilter']) || !preg_match('/{{\s*:/', $properties['categoryFilter'])) {
                    continue;
                }

                $cmsPages[] = $page;
            }

            $result['cmsPages'] = $cmsPages;
        }
        return $result;
    }

    public static function resolveMenuItem($item, $url, $theme){
        //todo
    }
}
