<?php

namespace Mnv\Admin\Controllers;

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

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

use Mnv\Models\Content;
use Mnv\Models\TypeContent;
use Mnv\Models\Exceptions\NoContentException;
use Mnv\Models\Exceptions\NotContentApproveException;
use Mnv\Models\Users\UserSettingOption;

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

    public function fetch()
    {
        global $SECTIONS;

        $dateSelector = new StatsDateSelector(false, 'contentDateSelector');

        $content = new Content($this->request);

        /** title */
        $this->smarty->assign('title', TypeContent::getTypeContentValue('name', $this->module));
        /** activeItem */
        $this->smarty->assign('activeItem', $this->module);
        /** generate url for type content */
        $this->smarty->assign('generate_url', $this->adminUrl . '/' . $this->module);
        /** type content */
        $content->typeContent = $this->request->get('typeContent', $this->module);
        /** statuses */
        $statuses = lang('general:statuses');
        array_pop($statuses);
        $this->smarty->assign('statuses', $statuses);
        /** получение разделов по типу контента */
        $sections = Helpers::getSectionContent(0, $content->typeContent);

        /** действия */
        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();
                response()->make("approveSuccess('" . $content->id . "');", \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'text/html;charset=UTF-8', 'Charset' => 'utf-8'])->send();
            } 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' => $this->status, 'type' => 'success')
                : array('data' => false, 'status' => $this->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();
            exit();
        }

        else {

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


            /** получение всего контента */
            $contents = collect($content->all($this->limit, $this->page))->map(function ($item) use ($content, $SECTIONS) {
                $item['statusName'] = lang('general:statuses:' . $item['status']);
                $item['publishedOn'] = langDate(adjustTime($item['publishedOn'], false, 'd.m.Y'));

                if (!empty($item['publicationEnd'])) {
                    $item['publicationEnd'] = langDate(adjustTime($item['publicationEnd'], false, 'd.m.Y'));
                }

                $image                  = $content->getMainImage($item['articleId']);
                $item['image']          = !empty($image['original']) ? $image['original'] : '/admin/assets/img/no_images.jpg';
                $item['section']        = $SECTIONS[$item['sectionId']] ? $SECTIONS[$item['sectionId']]['name'] : '';
                $item                   += $content->getProperties($item['articleId']);

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

//            print_r($contents);

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

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

        }



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

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

        $this->smarty->assign('title', lang('general:accessIsDenied'));
        return $this->smarty->fetch('accessIsDenied.tpl');

    }


}