<?php

namespace Mnv\Admin\Controllers;

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

use InvalidArgumentException;
use Mnv\Core\AdminMnv;
use Mnv\Core\Uploads\Favicon;

/**
 * Class FaviconAdmin
 * @package Mnv\Admin\Controllers
 */
class FaviconAdmin extends AdminMnv
{
    const NONCE_ACTION_NAME_FAVICON_GENERATION    = 'favicon_generation';

    public function fetch()
    {

        $favicon = new Favicon();
        $this->smarty->assign('activeItem','favicon');
        $this->smarty->assign('title', 'Генерация favicon');

        if ($this->action == 'back') {
            $response       = $this->request->get('json_result', '');
            $responseUrl    = $this->request->get('json_result_url', '');

            if ($responseUrl != null) {
                if (strpos($responseUrl, '/') === 0) {
                    $responseUrl = 'https://realfavicongenerator.net' . $responseUrl;
                }
                // Эта операция может занять несколько секунд ... лучше оставить это за Ajax-запросом
                $response = file_get_contents($responseUrl);
            }

            if ($response != null) {
                try {
                    $favicon->run($response);

                    $favicon->downloadAndUnpack();

                    $favicon->storePictures($favicon);

                    $favicon->storePreview( $favicon->getPreviewPath());

                    if ($favicon->getCustomParameter() != self::NONCE_ACTION_NAME_FAVICON_GENERATION) {
                        $this->errors['not_saved'] = true;
                    } else {
                        $this->messages['saved'] = true;
                        $this->smarty->assign('html_code', $favicon->getHtmlCode());
                    }

                } catch (\Exception $e) {
                    $error = $e->getMessage();
                    $this->errors['error'] = true;
                }
            } else {
                $this->errors['no_response'] = 'No response from RealFaviconGenerator';
            }
        }


        $preview_url = $favicon->is_preview_available() ? $favicon->previewUrl() : null;
        $this->smarty->assign('preview_url', $preview_url);

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

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

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

    }


}








	
	
	
	
	