<?php

namespace Mnv\Admin\Controllers;

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

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

use Mnv\Models\BannerGroups;

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

	public function fetch()
    {

        $BannerGroup = new BannerGroups($this->request);

        $this->smarty->assign('activeItem','bannergroups');
        $this->smarty->assign('title', 'Группы баннеров');

        $this->smarty->assign('statuses', array_slice(lang('general:statuses'), 1));
        $this->smarty->assign('sections', Helpers::getAllSectionOptions());

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

            $BannerGroup->edit()->gettingInfoAboutUsers();
//            if (!empty($BannerGroup->data)) $BannerGroup->data['pages'] = explode(',', $BannerGroup->data['pages']);

        } else if ($this->action == 'save' || $this->action == 'apply') {

            if (empty($BannerGroup->data['name'])) {
                $this->errors['name'] = true;
            }

            if (empty($BannerGroup->sectionIds)) {
                $this->errors['sectionId'] = true;
            }

            if (empty($this->errors)) {
                if ($BannerGroup->prepare($BannerGroup->data, $this->manager['userId'])) {
                    $this->messages['saved'] = true;
                } else {
                    $this->errors['not_saved'] = true;
                }

                $BannerGroup->edit()->gettingInfoAboutUsers();
                if (!empty($BannerGroup->data)) $BannerGroup->data['pages'] = explode(',', $BannerGroup->data['pages']);

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

        if (!empty($BannerGroup->id)) {
            $BannerGroup->data['pages'] = $BannerGroup->getTracking($BannerGroup->id);
        }

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

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

        if ($this->permissions('bannergroups')) {
            return $this->smarty->fetch('views/banners/banner-group.tpl');
        }

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


    }


}