<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\AdminMnv;

use Mnv\Models\Shop\Currencies;

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

    public function fetch()
    {
        $currency = new Currencies($this->request);

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

        if ($this->action == 'remove') {
            if ($currency->remove()) {
                if (!saveSerializations()) $this->errors['serializations'] = true;

                response()->make("deleteSuccess('". $currency->id . "');", \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'text/html;charset=UTF-8', 'Charset' => 'utf-8'])->send();
                exit;
            }
        }
        else if ($this->action == 'reorder') {

            $i = 0;
            foreach ($currency->currencyIds as $currencyId) {
                $i++;
                $currency->id = $currencyId;
                $currency->data['orderBy'] = $i;
                $currency->update($currency->data);
            }


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

        }
        else if (($this->action == 'setDefaultCurrency') && $currency->setDefaultCurrency() && !saveSerializations()) {
            $this->errors['serializations'] = true;
        }


        $currencies = $currency->all($this->limit, $this->page);

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

        /** вывод в шаблон результатов */
        $this->smarty->assign('currencySelectList', $currency->currencySelectList());
        $this->smarty->assign('totalCurrencies', $currency->total);
        $this->smarty->assign('currencyList', $currencies);
        $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('currencies')) {
            return $this->smarty->fetch('views/currencies/currencies.tpl');
        }

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


    }
}


    



