<?php

namespace Mnv\Admin\Controllers;

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

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

use Mnv\Models\Blocks;

/**
 * Class BlockAdmin
 * @package Mnv\Admin\Controllers
 */
class BlockAdmin extends AdminMnv
{
    /**
     * Вывод всего контента
     */
    public function fetch()
    {

        $block = new Blocks($this->request);

        $image    = $this->request->get('image', '');
        $gallery  = $this->request->get('gallery', '');
        $imageIds = $this->request->get('imageIds', '');
        $imageId  = (int) $this->request->get('imageId', '');
        $picture  = $this->request->get('picture', '');

        /** title */
        $this->smarty->assign('title', 'Инфоблоки');
        /** activeItem */
        $this->smarty->assign('activeItem', 'blocks');
        /** statuses */
        $statuses = lang('general:statuses');
        array_shift($statuses);
        array_pop($statuses);
        $this->smarty->assign('statuses', $statuses);

        $this->smarty->assign('imageSizes', $block->imageSizes);
        $this->smarty->assign('backgrounds', $block->backgrounds);
        $this->smarty->assign('positions', $block->positions);
        $this->smarty->assign('text_positions', $block->text_positions);


        $sections = Helpers::getSectionBlock(0 );
        $this->smarty->assign('sections', $sections);


        if ($this->action == 'add' || $this->action == 'edit') {
            $block->edit()->getFiles()->gettingInfoAboutUsers();
        } else if ($this->action == 'save' || $this->action == 'apply') {
            /** проверка полей */
            if (empty($block->data['title'])) $this->errors['title'] = true;
            /** проверка доступных разделов для статей */
            if (empty($block->data['sectionId']) || empty($sections[$block->data['sectionId']])) $this->errors['sectionId'] = true;

            /** основная картинка */
            $images['fileId'] = !empty($image) ? $image['fileId'] : null;
            /** включить / отключить галерею у данного контента */
            $block->data['enableGallery'] = isset($block->data['enableGallery']) ? 1 : 0;
            $images['gallery'] = !empty($gallery) ? $gallery : null;

            /** если ошибок нет то можно продолжить дальше */
            if (empty($this->errors)) {
                if ($block->prepare($block->data, $this->manager['userId'])) {
                    if (!empty($images['fileId'])) $block->addMainImage($block->id, $images);
                    if (!empty($images['gallery'])) $block->addGalleryAndDocuments($block->id, $images, 'gallery');
                    $this->messages['saved'] = true;
                } else {
                    $this->errors['not_saved'] = true;
                }
            }

            $block->edit()->getFiles()->gettingInfoAboutUsers();

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

        }/** удаление основной картинки */
        else if ($this->action == 'deleteImage') {
            $result = $block->deleteFile($imageId)
                ? array('status' => 200, 'message' => lang('javascript:deletingImage'), 'type' => 'success')
                : array('status' => 500, 'message' => lang('javascript:deletingImageError'), '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 == 'editPictureInfo') {

            $response = $block->editPictureInfo($imageId, $picture)
                ? array('status' => 200, 'title' => $block->result['title'], 'alias' => $block->result['alias'], 'description' => $block->result['description'], 'link' => $block->result['link'], 'position' => $block->result['position'])
                : array('status' => 400, 'title' => '', 'alias' => '', 'description' => '', 'link' => '', 'position' => '');

            response()->json($response, \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 == 'sortPictures') {

            $i = 0;
            foreach ($imageIds as  $imageId) {
                $i++;
                $block->sortPictures($imageId, $i);
            }

            response()->json(array('status' => 200, 'type' => 'success'), \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 == 'deletePicture') {

            $result = $block->deleteFile($imageId)
                ? array('status' => 200, 'message' => lang('javascript:deletingImage'), 'type' => 'success')
                : array('status' => 500, 'message' => lang('javascript:deletingImageError'), '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('block', $block->data);


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

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

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



}