<?php

namespace Mnv\Admin\Controllers;

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


use Mnv\Core\Helpers;
use Mnv\Core\AdminMnv;
use Mnv\Core\Test\Logger;

use Mnv\Models\Sections;
use Mnv\Models\TypeContent;
use Mnv\Models\Users\UserSettingOption;

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

    public function fetch()
    {
        global $SECTIONS;

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

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

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

        /** подтвердить удаление */
        if ($this->action == 'confirmDelete') {
            /** проверить сущестуют ли у этого раздела подразделы и контент */
            if ($section->remove()) {

                if ($section->data['hasSubsections']) {
                    $subsectionOptions = array('delete' => lang('general:delete'));
                    $subsectionOptions[0] = lang('sections:moveToRoot');
                    $subsectionOptions += Helpers::getSectionOptions($section->id);
                    foreach ($subsectionOptions as $key => $name) {
                        if ($key > 0) {
                            $subsectionOptions[$key] = lang('sections:moveTo') . ': ' . $name;
                        }
                    }
                    $this->smarty->assign('subsectionOptions', $subsectionOptions);
                }

                if ($section->data['hasArticles']) {
                    $articleOptions = array('delete' => lang('general:delete'));
                    $articleOptions += Helpers::getSectionOptions($section->id);
                    foreach ($articleOptions as $key => $name) {
                        if ($key > 0) {
                            $articleOptions[$key] = lang('sections:moveTo') . ': ' . $name;
                        }
                    }
                    unset($articleOptions[0]);
                    $this->smarty->assign('articleOptions', $articleOptions);
                }

                $this->smarty->assign('section', $section->data);

            } else {

                $this->errors['section_not_found'] = true;
            }

        }
        /** удаление после подтверждения */
        else if ($this->action == 'deleteConfirmed') {

            if (!empty($section->id)) {
                if ($section->deleteConfirmed($section->param)) {
                    Logger::init()->info("Раздел «" . $section->data['name'] . "» удален", $this->manager['userId'])->save();
                    $this->messages['deleted'] = true;
                }
                if (!saveSerializations()) $this->errors['serializations'] = true;
                if (!writeHtaccess()) $this->errors['htaccess'] = true;
            } else {
                $this->errors['section_not_found'] = true;
            }
        }
        /** отобразить или скрыть с главного меню */
        else if ($this->action == 'menu') {

            if ($section->menuSection() && !saveSerializations()) $this->errors['serializations'] = true;

            response()->json($section->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();

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

            if ($section->status()) {
                if (!saveSerializations()) $this->errors['serializations'] = true;
                if (!writeHtaccess()) $this->errors['htaccess'] = true;
                $result = array('data' => true, 'status' => $section->status, 'type' => 'success');
            } else {
                $result = 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();
        }
        /** сортировать при перемещение */
        else if ($this->action == 'reorder') {

            $ids = array_values($section->sectionIds);
            sort($section->sectionIds);
            $section->reorder($ids, $section->sectionIds);

            if (!saveSerializations()) $this->errors['serializations'] = true;
            if (!writeHtaccess()) $this->errors['htaccess'] = true;

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

//        if ($section->parentId = $section->getParentId()) {
//            redirect($this->adminUrl . "/sections?" . $this->buildQueryString(array_filter(['parentId' => $section->parentId, 'page' => $this->page])));
//            die (lang('sections:noSubsections'));
//        }
        if (!empty($section->parentId) && !connect()->table('sections')->count('*', 'count')->where('parentId', $section->parentId)->getValue()) {
            $section->parentId = (int)connect()->table('sections')->select('parentId')->where('sectionId', $section->parentId)->getValue();
            redirect($this->adminUrl . "/sections?" . $this->buildQueryString(array_filter(['parentId' => $section->parentId, 'page' => $this->page])));

            die (lang('sections:noSubsections'));
        }

        /** получать информацию о родительском разделе */
        if ($section->parentId > 0) {
            $parent = $SECTIONS[$section->parentId];
            if ($parent['parentId'] > 0) {
                $parent['parent'] = $SECTIONS[$parent['parentId']];
            }
            $this->smarty->assign('parent', $parent);
        }


        /** получение всех разделов */
        $listSections = $section->all($this->limit, $this->page);
        $sections = collect($listSections)->map(function ($item, $i) use ($listSections, $SECTIONS, $section) {
            $item['statusName']         = lang('sections:statuses:' . $item['status']);
            $item['typeName']           = lang('sections:types:' . $item['type']);
            $item['typeContentName']    = ($item['typeContent'] == 'products') ? lang('products:title') : $section->typeContents[$item['typeContent']] ?? null;
            if (($this->page > 1 && $i == 0) || (($i - $this->limit >= 0) && ($i == count($listSections) - 1))) $item['isHidden'] = true;
            $item['hasSubsections']  = !empty($SECTIONS[$item['sectionId']]['children']);

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


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

//        print_r($this->sections);
        /** вывод в шаблон результатов */
        $this->smarty->assign('pageNums', $pages);
        $this->smarty->assign('sections', $sections);
        $this->smarty->assign('parentId', $section->parentId);


        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/sections.tpl');
        }

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

    }

}