<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\AdminMnv;

use Mnv\Models\TypeContent;
use Mnv\Models\TypeContentField;
use Mnv\Models\Users\UserTypes;

/**
 * Class TypeContentFieldAdmin
 */
class TypeContentFieldAdmin extends AdminMnv
{

    public function fetch()
    {
        $field = new TypeContentField($this->request);

        $this->smarty->assign('activeItem','typecontents');
        $this->smarty->assign('title', 'Добавить поле');
        /** statuses */
        $this->smarty->assign('statuses', lang('general:statuses'));
        $this->smarty->assign('selectTypeContents', TypeContent::selectTypeContents('typeId ASC', 'typeId', 'name'));
        /** type fields */
        $this->smarty->assign('typeFields', TypeContentField::getTypeFields());

        $this->smarty->assign('positions', array(
            '0' => 'Выберите расположение поля',
            'M' => 'Основное',
            'S' => 'Статус и видимость',
//            'T' => 'Описание'
        ));
        $this->smarty->assign('radioGroupPositions', array(
            '0' => 'Выберите расположение группы',
            'V' => 'Вертикально',
            'H' => 'Горизонтально'
        ));


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

            $field->edit()->gettingInfoAboutUsers();
            $field->getProperties();

            $this->smarty->assign('field', $field->data);
            $this->smarty->assign('properties', $field->properties);
        }

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

            if (empty($field->data['name'])) $this->errors['name'] = true;
            if (empty($field->data['typeId'])) $this->errors['typeId'] = true;

            if (empty($field->data['fileName'])) $this->errors['fileName'] = true;

            if (preg_match('/[^a-zA-Z\-_\.,]/i', $field->data['fileName'])) $this->errors['fileNameCharacters'] = true;

            if ($fileName = $field->checkFileName($field->data['fileName'])) {
                if ($fileName == $field->data['fileName']) {
                    $this->errors['fileNameExists'] = true;
                } else {
                    $field->data['fileName'] = $fileName;
                }
            }

            if (empty($this->errors)) {
                if (empty($this->errors)) {
                    if ($field->prepare($field->data, $this->manager['userId'])) {
                        $this->messages['saved'] = true;
                    } else {
                        $this->errors['not_saved'] = true;
                    }
                }
            }

            $field->edit()->gettingInfoAboutUsers();
            $field->getProperties();
            $this->smarty->assign('field', $field->data);
            $this->smarty->assign('properties', $field->properties);

            if (empty($this->errors) && $this->action == 'save') {
                redirect($this->adminUrl . "/typecontent?" . $this->buildQueryString(['action' => 'edit', 'id' => $field->typeId]));
            }

        }
        /** удаление */
        elseif ($this->action == 'remove') {
            $result = $field->remove()
                ? array('status' => 200, 'message' => 'Поле удалено',  'type' => 'success')
                : array('status' => 500, '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;
            $field->data = [];
            foreach ($field->fieldIds as $fieldId) {
                $i++;
                $field->id = $fieldId;
                $field->data['orderBy'] = $i;
                $field->update($field->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 = $field->status()
                ? array('data' => true, 'status' => $field->status, 'type' => 'success')
                : array('data' => false, 'status' => $field->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();
        }


        $this->smarty->assign('fields', $field->all($this->limit = 50, $this->page));
        $this->smarty->assign('typeId', $field->typeId);


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


        /** Права доступа к данному шаблону */
        if ($this->manager['userType'] == UserTypes::DEVELOPER) {
            return $this->smarty->fetch('views/type-content/field.tpl');
        }

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

    }
}



