<?php

namespace Mnv\Admin\Controllers;

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

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

use Mnv\Models\Sections;
use Mnv\Models\TypeContent;

/**
 * Class SectionAdmin
 * @package Mnv\Admin\Controllers
 */
class SectionAdmin extends AdminMnv
{
    protected $id;
    protected $val;

    public function fetch()
    {
        global $SECTIONS;

        $oldSection = '';

        $section = new Sections($this->request);

        $this->smarty->assign('title', lang('sections:title'));
        $this->smarty->assign('activeItem', 'sections');

        $this->smarty->assign('paramCaching', [
            0   => lang('general:cachingDefault'),
            -1  => lang('general:cachingDisabled'),
            1   => lang('general:enableCachingFor')
        ]);
        /** select commentsEnabled */
        $this->smarty->assign('paramComments', [
            0   => lang('general:defaultComments'),
            -1  => lang('general:disableComments'),
            1   => lang('general:enableComments')
        ]);

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

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


        /** редактирование или добавление */
        if ($this->action == 'edit') {

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

            /** проверка полей */
            $section->data['name'] = trim($section->data['name']);
            if (empty($section->data['name'])) $this->errors['name'] = true;

            /** параметры input(checkbox) int 1/0 */
            $section->data['showMainPage']  = $section->data['showMainPage'] ?? 0;
            $section->data['topMenu']       = $section->data['topMenu'] ?? 0;
            $section->data['footerMenu']    = $section->data['footerMenu'] ?? 0;
            $section->data['enableGallery'] = $section->data['enableGallery'] ?? 0;
            $section->data['enableIcon']    = $section->data['enableIcon'] ?? 0;
            $section->data['sitemap']       = $section->data['sitemap'] ?? 'N';

            /** проверяем существует ли главная страница если да то ошибка / если нет то устанавливаем ей параметры type и parentId */
            if ($section->data['fileName'] == 'index') {
                $section->data['type'] = 'plain';
                $section->data['parentId'] = 0;
                if ($fileName = $section->isFileNamePage($section->data['fileName'])) {
                    if ($fileName == $section->data['fileName']) {
                        $this->errors['pageFileNameExists'] = true;
                    } else {
                        $section->data['fileName'] = $fileName;
                    }
                }
            }

            /** проверка наличия  */
            if (!empty($section->id)) $oldSection = $SECTIONS[$section->id] ?? null;

            if (empty($section->data['fileName'])) $this->errors['fileName'] = true;
            if (empty($section->data['parentId'])) {
                $section->data['parentId'] = 0;
            } else if ($section->id == $section->data['parentId']) {
                $this->errors['parentId'] = true;
            }


            /** проверяем существует ли `fileName` если да то ошибка */
            if ($fileName = $section->checkFileName($section->data['fileName'])) {
                if ($fileName == $section->data['fileName']) {
                    $this->errors['fileNameExists'] = true;
                } else {
                    $section->data['fileName'] = $fileName;
                }
            }

            if (preg_match('/^(admin|images|files)$/i', $section->data['fileName'])) $this->errors['fileNameProhibited'] = true;
            if (preg_match('/[^0-9a-zA-Z\-_\.,]/i', $section->data['fileName'])) $this->errors['fileNameCharacters'] = true;

            $templates = searchDir(THEME_ROOT, '*.tpl');
            if (!in_array($section->data['templateName'], $templates, true)) $section->data['templateName'] = '';
            if (!in_array($section->data['subTemplateName'], $templates, true)) $section->data['subTemplateName'] = '';
            if (!in_array($section->data['artTemplateName'], $templates, true)) $section->data['artTemplateName'] = '';

            $images['fileId'] = !empty($image) ? $image['fileId'] : '';
            $images['gallery'] = !empty($gallery) ? $gallery : '';

            if (isset($docs)) $images['docs'] = !empty($docs) ? $docs : '';

            if (!empty($section->data['urlType']) && $section->data['urlType'] == 'external') {
                if (empty($section->data['externalLink'])) {
                    $this->errors['externalLink'] = true;
                }
            } else {
                $section->data['externalLink'] = null;
            }


            if (empty($this->errors)) {

                if (isset($oldSection['parentId']) && (int)$section->data['parentId'] !== (int)$oldSection['parentId']) {
                    $section->data['sortOrder']  = $section->getSortOrder($section->data['parentId']);
                }

                if ($section->prepare($section->data, $this->manager['userId'])) {

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

                    if (isset($oldSection->parentId) && $section->parentId != $oldSection->parentId) {
                        /** обновить порядок сортировки, если был изменен родитель */
                        $section->writeSortOrders($section->parentId);
                        $section->writeSortOrders($oldSection->parentId);
                    }

                    $this->messages['saved'] = true;
                } else {
                    $this->errors['not_saved'] = true;
                }

                $section->parentId = $section->data['parentId'];
                if (!saveSerializations()) {
                    $this->errors['serializations'] = true;
                }
                if (!writeHtaccess()) {
                    $this->errors['htaccess'] = true;
                }
            }

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

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

//            $section->sortPictures($imageIds);
        }
        /** удаление картинки из галереи */
        else if ($this->action == 'deletePicture') {

            $result = $section->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();
         }

        /** удаление файлов docs */
        else if ($this->action == 'deleteDocs') {

            $result = $section->deleteFile($imageId)
                ? array('status' => 200, 'message' => lang('javascript:deletingDocs'), 'type' => 'success')
                : array('status' => 500, 'message' => lang('javascript:deletingDocsError'), '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();
        }



        $this->smarty->assign('section', $section->data);
        $this->smarty->assign('parents', Helpers::getSectionOptions($section->id ?? 0));
        $this->smarty->assign('parentId', $section->parentId);

        /* template options */
        $templates = searchDir(THEME_ROOT, '*.tpl');
        array_unshift($templates, lang('general:useDefaultTemplate'));
        $this->smarty->assign('templates', $templates);

        /* caching time options */
        $cachingTimeOptions = array();
        for ($i = 1; $i <= 60; $i++) $cachingTimeOptions[$i] = $i;
        $this->smarty->assign('cachingTimeOptions', $cachingTimeOptions);
        $this->smarty->assign('cachingPeriodOptions', lang('general:cachingPeriodOptions'));
        $this->smarty->assign('statuses', lang('sections:statuses'));



        $addContents = TypeContent::selectTypeContents('typeId ASC', 'fileName', 'name');
        if (!empty($addContents))   $section->typeContents += $addContents;
        $this->smarty->assign('typeContents', $section->typeContents);

        $this->smarty->assign('types', lang('sections:types'));
        $this->smarty->assign('urlTypes', array('default' => 'Выбрать тип ссылки', 'external' => 'Внешняя ссылка' ));


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


        if ($this->permissions('sections')) {
            return $this->smarty->fetch('views/sections/section.tpl');
        }

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






}
	
	

	
