<?php

namespace Mnv\Admin\Controllers;

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

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

use Mnv\Models\Shop\Product;
use Mnv\Models\Shop\ProductBlocks;

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

    public function fetch()
    {
        $block = new ProductBlocks($this->request);

        /** title */
        $this->smarty->assign('title', 'Инфоблоки');
        /** activeItem */
        $this->smarty->assign('activeItem', 'iblocks');
        /** statuses */
        $statuses = lang('general:statuses');
        array_shift($statuses);
        array_pop($statuses);
        $this->smarty->assign('statuses', $statuses);
        /** generate url for type content */
        $this->smarty->assign('generate_url', $this->adminUrl . '/' . $this->module);

        $products = array('0' => 'Выберите продукт...');
//        $result = Product::getModels();
//        if (!empty($result)) $models += $result;
        $this->smarty->assign('models', $products);

        /** действия */
        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,
                'product_id'    => $this->product_id,
            ]);

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

                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('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('products')) {
            return $this->smarty->fetch('views/shop/blocks.tpl');
        }

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


    }


}