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

    public function fetch()
    {
        global $SECTIONS;

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

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

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

        /** действия */
        if ($this->action == 'remove') {
            $result = $block->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 == 'status') {
            $result = $block->status()
                ? array('data' => true, 'status' => $block->status, 'type' => 'success')
                : array('data' => false, 'status' => $block->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();

        }  else if ($this->action == 'reorder') {
            $i = 0;
            $block->data = [];
            foreach ($block->blockIds as $blockId) {
                $i++;
                $block->id = $blockId;
                $block->data['orderBy'] = $i;
                $block->update($block->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 {

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

            /** получение всего контента */
            $blocks = collect($block->all($this->limit, $this->page))->map(function ($item) use ($SECTIONS) {
                $item['statusName']  = lang('general:statuses:' . $item['status']);
                $item['section']     = $SECTIONS[$item['sectionId']] ?? array();

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

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

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

        }

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

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


    }


}