<?php

namespace frontend\widgets;

use common\modules\product\models\Category;
use common\modules\product\models\CategorySearch;
use Yii;
use yii\base\Widget;
use yii\web\View;
use yii\helpers\Url;

class Rubrics extends Widget {
    public $active;

    public $wrapper = '';

    public $includes = [];

    private $categories = [];

    public function run()
    {
        if (empty($this->active)) {
            $this->active = Yii::$app->request->get('category');
        }
        if (!empty($this->active) && !is_object($this->active)) {
            $this->active = CategorySearch::findByAlias($this->active);
        }
        if (!empty($this->active)) {
            $this->active = $this->active->category_id;
        }
        $items = [];

        if (empty($this->categories)) {
            $this->categories = Category::find()->orderBy('category_id', SORT_ASC)->all();
        }
        foreach ($this->categories as $category) {
            if (!empty($this->includes) && !in_array($category->category_id, $this->includes)) {
                continue;
            }
            $items[] = $category;[
                'label' => $category->name,
                'url' => Url::to(['catalog/category', 'category' => $category]),
                'active' => !empty($categoryObject) && $categoryObject->alias == $category->alias ? true : false,
            ];
        }

        return $this->render('rubrics', ['items' => $items, 'wrapper' => $this->wrapper, 'active' => $this->active]);
    }
}