<?php

namespace Mnv\Admin\Controllers;

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


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

use Mnv\Models\Brands;
use Mnv\Models\Countries;

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

    public function fetch()
    {
        $brand = new Brands($this->request);

        $this->smarty->assign('title', lang('brands:title'));
        $this->smarty->assign('activeItem', 'brands');
        $this->smarty->assign('statuses', array_slice(lang('general:statuses'), 1));
        $this->smarty->assign('countryList', Countries::getSelectCountries());

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

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

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

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

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

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

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

                    $this->messages['saved'] = true;
                } else {
                    $this->errors['not_saved'] = true;
                }
            }
            $brand->edit()->getFiles()->gettingInfoAboutUsers();

            if (empty($this->errors) && $this->action == 'save') {
                redirect($this->adminUrl . "/brands?" . $this->buildQueryString(['page' => $this->page]));
            }

        }
        /** удаление основной картинки */
        else if ($this->action == 'deleteImage') {

            $result = $brand->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 = $brand->editPictureInfo($imageId, $picture)
                ? array('status' => 200, 'title' => $brand->result['title'], 'alias' => $brand->result['alias'], 'description' => $brand->result['description'], 'link' => $brand->result['link'], 'position' => $brand->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'])->send();
            exit();
        }
        /** сортировка картинок в галереи */
        else if ($this->action == 'sortPictures') {

            $i = 0;
            foreach ($imageIds as  $imageId) {
                $i++;
                $brand->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 = $brand->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();
        }

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

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

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

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

}
