<?php

namespace Mnv\Admin\Controllers;

if (!defined('MNV_CMS')) {
    die('Hacking attempt!');
}

use Mnv\Core\AdminMnv;
use Mnv\Core\Helpers;

use Mnv\Models\Shop\Features;

/**
 * Class ProductFeaturesAdmin
 * @package Mnv\Admin\Controllers
 */
class ProductFeaturesAdmin extends AdminMnv
{

    public function fetch()
    {
        global $SECTIONS;

        $feature = new Features($this->request);

        $this->smarty->assign('activeItem','features');
        $this->smarty->assign('title', 'Свойства товара');

        /** получение разделов по типу контента */
        $sections = Helpers::getSectionContent(0, 'products');

        /** действия */
        if ($this->action === 'remove') {
            $result = $feature->remove()
                ? array('status' => 200, 'message' => 'Свойство удалено', 'type' => 'success')
                : array('status' => 403, 'message' => 'Ошибка при удаление свойства', 'type' => 'error');

            response()->json($result, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
            exit();

        }
        else if ($this->action === 'reorder') {
            $i = 0;
            $feature->data = [];
            foreach ($feature->featureIds as $featureId) {
                $i++;
                $feature->id = $featureId;
                $feature->data['orderBy'] = $i;
                $feature->update($feature->data);
            }

            response()->json(array('status' => 200), \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
            exit;
        }
        else if ($this->action === 'status') {
            $result = $feature->status()
                ? array('data' => true, 'status' => $feature->status, 'type' => 'success')
                : array('data' => false, 'status' => $feature->status, 'type' => 'error');

            response()->json($result, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
            exit();
        }

        $sectionIds = [];
        if (!empty($this->filterSection) && !empty($SECTIONS[$this->filterSection])) {
            $sectionIds = array($this->filterSection);
            if (!empty($SECTIONS[$this->filterSection]['allChildren'])) {
                $sectionIds = array_merge($sectionIds, $SECTIONS[$this->filterSection]['allChildren']);
            }
        }

        /** фильтровать контент */
        $feature->filter = array_filter([
            'sectionIds'    => $sectionIds,
            'status'        => $this->status,
            'query'         => $this->query,
        ]);

        /** получение всех */
        $features = collect($feature->all($this->limit, $this->page))->map(function ($item) use ($SECTIONS) {
            $item['statusName']  = lang('general:statuses:' . $item['status']);
            if (!empty($item['sectionIds'])) {
                $sectionIds = json_decode($item['sectionIds'], false, 512, JSON_THROW_ON_ERROR);
                $sectionArr = array();
                foreach ($sectionIds as $key => $sectionId) {
                    $sectionArr[$key] = isset($SECTIONS[$sectionId]) ? $SECTIONS[$sectionId]['name'] : '';
                }
                $item['sections'] = $sectionArr;
            }

            return $item;
        })->all();


        /** pagination */
        $feature->total();
        $pages = getPageNums($feature->total, $this->page, $this->limit, 0, 4, 4, 0);

        /** вывод в шаблон результатов */
        $this->smarty->assign('totalFeatures', $feature->total);
        $this->smarty->assign('features', $features);
        $this->smarty->assign('pageNums', $pages);
        $this->smarty->assign('sections', $sections);

        if (!empty($this->errors)) {
            $this->smarty->assign('errors', $this->errors);
        }
        if (!empty($this->messages)) {
            $this->smarty->assign('messages', $this->messages);
        }

        if ($this->permissions('features')) {
            return $this->smarty->fetch('views/shop/features.tpl');
        }

        $this->smarty->assign('title', 'Access Denied');
        return $this->smarty->fetch('accessIsDenied.tpl');

    }

}