<?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\TypeContentField;
use Mnv\Models\Exceptions\NotUpdateContentException;
use Mnv\Models\Exceptions\NotInsertContentException;

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

    public function fetch()
    {
        global $SECTIONS;

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

        /** работа с галереей */
        $image    = $this->request->get('image', '');
        $gallery  = $this->request->get('gallery', '');
        $docs     = $this->request->get('docs', '');

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

        $content->typeContent = $this->module . 's';
        /** title */
        $this->smarty->assign('title',  TypeContent::getTypeContentValue('name', $content->typeContent));
        /** activeItem */
        $this->smarty->assign('activeItem', $content->typeContent);
        /** generate url for type content */
        $this->smarty->assign('generate_url', $this->adminUrl . '/' . $content->typeContent);
        /** statuses */
        $statuses = lang('general:statuses');
        array_shift($statuses);
//        array_pop($statuses);
        $this->smarty->assign('statuses', $statuses);

//        $this->smarty->assign('urlTypes', array(
//            'default'   => 'Выбрать тип ссылки',
//            'modal'     => 'Модальное окно',
//            'external'  => 'Внешняя ссылка'
//        ));

        /** select isFeatured */
        $this->smarty->assign('paramIsFeatured', [
            0 => lang('general:no'),
            1 => lang('general:yes')
        ]);
        /** select commentsEnabled */
        $this->smarty->assign('paramSettingComments', [
            0   => lang('general:defaultComments'),
            -1  => lang('general:disableComments'),
            1   => lang('general:enableComments')
        ]);

        /** получить дополнительные поля по типу контента */
        $typeContentId = TypeContent::getTypeContentValue('typeId', $content->typeContent);
        $fields = collect(TypeContentField::typeContentFields($typeContentId, 'V'))->map(function ($item) {
            if ($item['type'] == 'R' || $item['type'] == 'S')
                $item['properties'] = TypeContentField::typeContentFieldProperty('propertyId ASC', $item['fieldId']);

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


        $this->smarty->assign('fields', $fields);


        /** получить разделы данного типа контента */
        $sections = Helpers::getSectionContent(0, $content->typeContent);
        if (count($sections) < 2) $this->errors['no_sections'] = true;
        $this->smarty->assign('sections', $sections);

        if ($this->action === 'add' || $this->action === 'edit') {

            $content->edit()->getFiles()->gettingInfoAboutUsers();
        }
        /** сохранение */
        else if ($this->action == 'save' || $this->action == 'apply') {

            /** проверка полей */
            if (empty($content->data['title'])) $this->errors['title'] = true;
            /** избранное */
            $content->data['isFeatured'] = $content->data['isFeatured'] ?? 0;
            /** тип контента */
            $content->data['typeContent'] = $content->typeContent;

            /** проверка доступных разделов для статей */
            if (empty($content->data['sectionId']) || empty($sections[$content->data['sectionId']])) {
                $this->errors['sectionId'] = true;
            }

            /** проверка fileName на совпадение / если пустой то fileName пропишется от последнего ID из таблицы + 1 */
            if ($fileName = $content->checkFileName($content->data['fileName'])) {
                if ($fileName == $content->data['fileName']) {
                    $this->errors['fileNameExists'] = true;
                } else {
                    $content->data['fileName'] = $fileName;
                }
            }

            /** основная картинка */
            $images['fileId'] = !empty($image) ? $image['fileId'] : null;

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

            /** если ошибок нет то можно продолжить дальше */
            if (empty($this->errors)) {
                /** построение url из полученного url раздела/fileName статьи . расширение файла из настроек  (html / htm)  */
                $content->data['url'] = $SECTIONS[$content->data['sectionId']]['path'] . '/'. $content->data['fileName'] . '.' . $this->config['file_extension'];

                try {
                    $content->prepare($content->data, $this->manager['userId']);

                    if (!empty($images['fileId'])) $content->addMainImage($content->id, $images);
                    if (!empty($images['gallery'])) $content->addGalleryAndDocuments($content->id, $images, 'gallery');
                    if (!empty($images['docs'])) $content->addGalleryAndDocuments($content->id, $images, 'docs');

                   $this->messages['saved'] = true;

                } catch (NotInsertContentException | NotUpdateContentException $e) {
                    $this->errors['not_saved'] = true;
                }
            }


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

            if (empty($this->errors) && $this->action === 'save') {
                redirect($this->adminUrl . "/" . $content->typeContent . "?" . $this->buildQueryString(['page' => $this->page]));
            }
        }
        /** удаление основной картинки */
        else if ($this->action == 'deleteImage') {
            $result = $content->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 = $content->editPictureInfo($imageId, $picture)
                ? array('status' => 200, 'title' => $content->result['title'], 'alias' => $content->result['alias'], 'description' => $content->result['description'], 'link' => $content->result['link'], 'position' => $content->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++;
                $content->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 = $content->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();
        }

        $totalPrice = 0;
        if (!empty($content->id)) {
            $content->data += $content->getProperties($content->id);
        }

        $this->smarty->assign('article', $content->data);
        $this->smarty->assign('totalPrice', $totalPrice);

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


        if ($this->permissions($this->module .'s')) {
            try {
                return $this->smarty->fetch('views/contents/article.tpl');
//                return $this->smarty->fetch('views/contents/' . $this->module . '.tpl');
            } catch (\SmartyException | \Exception $e) {
                print $e->getMessage();
            }
        }

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



}