<?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 ProductFeatureAdmin
 * @package Mnv\Admin\Controllers
 */
class ProductFeatureAdmin extends AdminMnv
{

    public function fetch()
    {

        $feature = new Features($this->request);
        $this->smarty->assign('activeItem','features');
        $this->smarty->assign('title', 'Свойства товара');
        /* statuses */
        $this->smarty->assign('statuses', array_slice(lang('general:statuses'), 1));
        $sections = Helpers::getSectionContent(0, 'products');
        unset($sections[0]);
        $this->smarty->assign('sections', $sections);

        if ($this->action == 'add' || $this->action == 'edit') {
            $feature->edit()->gettingInfoAboutUsers();

        } else if ($this->action == 'save' || $this->action == 'apply') {

//            print_r($feature->data);


            /** проверка полей */
            if (empty($feature->data['name'])) $this->errors['name'] = true;
//            if (empty($feature->data['fileName'])) $this->errors['fileName'] = true;
            if (!empty($feature->data['sectionIds'])) {
                $feature->data['sectionIds'] = json_encode($feature->data['sectionIds'], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
            } else {
                $this->errors['sectionId'] = true;
            }

            /** если ошибок нет то можно продолжить дальше */
            if (empty($this->errors)) {
                if ($feature->prepare($feature->data, $this->manager['userId'])) {

                    if (is_array($feature->params)) {
                        $paramIds = array();

                        foreach($feature->params as &$param) {
                            $param['sectionIds'] = $feature->data['sectionIds']; // 71 209 01 71
                            if (isset($param['id']) && !empty($param['id'])) {
                                $feature->updateFeature($param['id'], $param, $this->manager['userId']);
                            } else {
                                $param['id'] = $feature->addFeature($param, $this->manager['userId']);
                            }

                            $param = $feature->feature($param['id']); // ОШИБКА
                            if (!empty($param['id'])) {
                                $paramIds[] = $param['id'];
                            }
                        }

                        /** возвращает specifications  */
                        $currentFeatures = $feature->features();
                        /** Удаляем непереданные */
                        foreach($currentFeatures as $currentFeature) {
                            if (!in_array($currentFeature['id'], $paramIds, true)) {
                                $feature->removeFeature($currentFeature['id']);
                            }
                        }

                        /** Отсортировать */
                        asort($paramIds);
                        $i = 0;
                        foreach($paramIds as $paramId) {
                            /** обновляем */
                            $feature->updateFeature($paramIds[$i], ['orderBy' => $paramId], $this->manager['userId']);
                            $i++;
                        }
                    } else {
                        $currentFeatures = $feature->features();
                        /** Удаляем непереданные */
                        if (!empty($currentFeatures)) {
                            foreach ($currentFeatures as $currentFeature) {
                                $feature->removeFeature($currentFeature['id']);
                            }
                        }
                    }

                    $this->messages['saved'] = true;
                } else {
                    $this->errors['not_saved'] = true;
                }
            }

            $feature->edit()->gettingInfoAboutUsers();

            if (empty($this->errors) && $this->action == 'save') {
                redirect($this->adminUrl . "/features?" . $this->buildQueryString(['page' => $this->page]));
            }
        }

        if (!empty($feature->data['sectionIds'])) {
            $feature->data['sectionIds'] = json_decode($feature->data['sectionIds'], true);
        }

        $features = [];
        if (!empty($feature->id)) $features = $feature->features();
        $this->smarty->assign('features', $features);


        $this->smarty->assign('feature', $feature->data);

        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/feature.tpl');
        }

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


    }
}