<?php

namespace Mnv\Admin\Controllers;

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

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

use Mnv\Core\SortTable;
use Mnv\Core\Utilities\Cookie\Session;
use Mnv\Models\Variants;
use Mnv\Models\Shop\Product;
use Mnv\Models\Exceptions\NoContentException;
use Mnv\Models\Exceptions\NotContentApproveException;

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

    public function fetch()
    {
        global $SECTIONS;

        $dateSelector   = new StatsDateSelector(false, 'productDateSelector');
//        $productVariant = new Variants();
        $variants       = null;

        $content = new Product($this->request);
        $content->sortTableId = $this->module;
        /** title */
        $this->smarty->assign('title', lang($this->module .':title'));
        /** activeItem */
        $this->smarty->assign('activeItem', $this->module);
        /** statuses */
        $this->smarty->assign('statuses', lang('general:statuses'));
        $stock_status = $content->getStockStatuses();

        $group_action  = $this->request->get('group_action');

        /** Получение разделов по типу контента */
        $sections = Helpers::getSectionContent(0, 'products');


        /** удаление */
        if ($this->action === 'remove') {
            $result = $content->remove()
                ? array('status' => 200, 'message' => lang('articles:messages:2'), 'type' => 'success')
                : array('status' => 403, 'message' => lang('articles:errors:11'), '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 === 'approve') {

            try {
                $content->approve();
                echo "approveSuccess('" . $content->id . "');";
            } catch (NotContentApproveException $e) { /** Ошибка при одобрении контента */
                response()->make("approveError();", \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'text/html;charset=UTF-8', 'Charset' => 'utf-8'])->send();
            } catch (NoContentException $e) { /** Контент не найден или пустой ID */
                response()->make("notFound();", \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'text/html;charset=UTF-8', 'Charset' => 'utf-8'])->send();
            }
            exit;

        }
        /** Изменить статус */
        else if ($this->action === 'status') {

            $result = $content->status()
                ? array('data' => true, 'status' => $content->status, 'type' => 'success')
                : array('data' => false, 'status' => $content->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 === 'group') {
            if (!empty($group_action)) {
                if (!empty($content->contentIds)) {
                    foreach ($content->contentIds as $contentId) {
                        $content->id = $contentId;
                        $content->group($group_action);
                    }
                    $response = array('status' => 200, 'message' => 'Успешно выполнено', 'type' => 'success');
                } else {
                    $response =  array('status' => 500, 'message' => 'Необходимо выбрать контент', 'type' => 'error');
                }
            } else {
                $response =  array('status' => 500, 'message' => 'Необходимо выбрать действие', 'type' => 'error');
            }

            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();

        }
        /** Сортировать таблицу */
        else if ($this->action === 'sort_table') {
            SortTable::init()->setSort($content->sortTableId, $content->sortBy, $content->sortOrder);
            $result = array('status' => 200, 'table' => $content->sortTableId, 'sortBy' => $content->sortBy, 'sortOrder' => $content->sortOrder);

            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 === 'clear_sort_table') {
            SortTable::init()->clearSort($content->sortTableId);
            $result = array('status' => 200, 'table' => $content->sortTableId);

            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 {

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

            /** получение всего контента */
            $contents = collect($content->all($this->limit, $this->page))->map(function ($item) use ($content, $stock_status, $SECTIONS) {
                $item['statusName']  = lang('general:statuses:' . $item['status']);
                $item['publishedOn'] = langDate(adjustTime($item['publishedOn'], false, 'd.m.Y'));
                $image               = $content->getMainImage($item['productId']);
                $item['image']       = !empty($image['original']) ? $image['original'] : '/admin/assets/img/no_images.jpg';
                $item['section']     = $SECTIONS[$item['sectionId']] ?? array();
                $item['stock_status']     = $stock_status[$item['stock_status_id']] ?? '';

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


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

            /** вывод в шаблон результатов */
            $this->smarty->assign('totalProducts', $content->total);
            $this->smarty->assign('product_variants', $variants);
            $this->smarty->assign('products', $contents);
            $this->smarty->assign('pageNums', $pages);
            $this->smarty->assign('sections', $sections);
        }

        /** Права доступа к данному шаблону */
        if ($this->permissions('products')) {
            return $this->smarty->fetch('views/shop/products.tpl');
        }

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

    }


}