<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\AdminMnv;

use Mnv\Models\Countries;

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

    public function fetch()
    {

        $country = new Countries($this->request);

        $this->smarty->assign('activeItem','countries');
        $this->smarty->assign('title', 'Города');


        if ($this->action == 'remove') {
            $result = $country->remove()
                ? array('status' => 200, 'message' => 'Город удален', 'type' => 'success')
                : array('status' => 403, 'message' => 'Ошибка при удаление города', '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 === 'status') {
            $result = $country->status()
                ? array('data' => true, 'status' => $country->status, 'type' => 'success')
                : array('data' => false, 'status' => $country->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();
            exit();
        }

        $countries = collect($country->all($this->limit, $this->page))->map(function ($item) {
            $item['statusName']  = lang('general:statuses:' . $item['status']);

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

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

        $this->smarty->assign('countries', $countries);
        $this->smarty->assign('pageNums', $pages);

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


        /** Права доступа к данному шаблону */
        if ($this->permissions('countries')) {
            return $this->smarty->fetch('views/geo/geo.countries.tpl');
        }

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



