<?php

namespace Mnv\Admin\Controllers;

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

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

use Mnv\Models\Countries;
use Mnv\Models\Dealers;

/**
 * Class BlockAdmin
 * @package Mnv\Admin\Controllers
 */
class DealerAdmin extends AdminMnv
{
    /**
     * Вывод всего контента
     */
    public function fetch()
    {

        $block = new Dealers($this->request);

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

        /** title */
        $this->smarty->assign('title', 'Дилеры');
        /** activeItem */
        $this->smarty->assign('activeItem', 'dealers');
        /** statuses */
        $statuses = lang('general:statuses');
        array_shift($statuses);
        array_pop($statuses);
        $this->smarty->assign('statuses', $statuses);
        $this->smarty->assign('countries', Countries::getSelectCountries());

        if ($this->action == 'add' || $this->action == 'edit') {
            $block->edit()->getFiles()->gettingInfoAboutUsers();
        } else if ($this->action == 'save' || $this->action == 'apply') {
            /** проверка полей */
            if (empty($block->data['title'])) $this->errors['title'] = true;
            if (empty($block->data['countryId'])) $this->errors['countryId'] = true;
            /** основная картинка */
            $images['fileId'] = !empty($image) ? $image['fileId'] : null;

            /** если ошибок нет то можно продолжить дальше */
            if (empty($this->errors)) {
                if ($block->prepare($block->data, $this->manager['userId'])) {
                    if (!empty($images['fileId'])) $block->addMainImage($block->id, $images);
                    $this->messages['saved'] = true;
                } else {
                    $this->errors['not_saved'] = true;
                }
            }

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

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

        }/** удаление основной картинки */
        else if ($this->action == 'deleteImage') {
            $result = $block->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 = $block->editPictureInfo($imageId, $picture)
                ? array('status' => 200, 'title' => $block->result['title'], 'alias' => $block->result['alias'], 'description' => $block->result['description'], 'link' => $block->result['link'], 'position' => $block->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++;
                $block->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 = $block->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('dealer', $block->data);


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

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

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



}