<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\AdminMnv;
use Mnv\Models\Shop\Options;


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

    public function fetch()
    {
        $features = new Options($this->request);

        $this->smarty->assign('title', 'Свойство опций');
        $this->smarty->assign('activeItem', 'options');

        /** statuses */
        $this->smarty->assign('statuses', array_slice(lang('general:statuses'), 1));
        /** generate url for type content */
        $this->smarty->assign('generate_url', $this->adminUrl . '/' . $this->module . 's');

        $this->smarty->assign('types',
            array(
                'select' => 'Список',
                'radio' => 'Переключатель',
//                'checkbox' => 'Флажок',
//                'text' => 'Текст',
//                'textarea' => 'Текстовая область'
            )
        );

        if ($this->action == 'add' || $this->action == 'edit') {
            $features->edit();
        }

        else if ($this->action == 'save' || $this->action == 'apply') {
            /** проверка полей */
            if (empty($features->data['name'])) {
                $this->errors['title'] = true;
            }

            /** если ошибок нет то можно продолжить дальше */
            if (empty($this->errors)) {

                if ($features->prepare($features->data, $this->manager['userId'])) {

                    if (is_array($features->options)) {
                        $optionIds = array();

                        foreach($features->options as &$option) {
                            if (isset($option['optionId']) && !empty($option['optionId'])) {
                                $features->updateOption($option['optionId'], $option);
                            } else {
                                $option['optionId'] = $features->addOption($option);
                            }

                            $option = $features->option($option['optionId']);
                            if (!empty($option['optionId'])) {
                                $optionIds[] = $option['optionId'];
                            }
                        }

                        /** возвращает specifications  */
                        $currentOptions = $features->options();
                        /** Удаляем непереданные */

                        foreach($currentOptions as $currentOption) {
                            if (!in_array($currentOption['optionId'], $optionIds, true)) {
                                print_r($optionIds);
                                $features->removeOption($currentOption['optionId']);
                            }
                        }

                        /** Отсортировать */
                        asort($optionIds);
                        $i = 0;
                        foreach($optionIds as $optionId) {
                            /** обновляем */
                            $features->updateOption($optionIds[$i], ['orderBy' => $optionId]);
                            $i++;
                        }
                    } else {
                        /** возвращает specifications  */
                        $currentOptions = $features->options();
                        /** Удаляем непереданные */
                        foreach($currentOptions as $currentOption) {
                            $features->removeOption($currentOption['propertyId']);
                        }
                    }

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

            $features->edit();

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

        }

        $options = [];
        if (!empty($features->id)) {
            $options = $features->options();
        }

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

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


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

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



}