<?php
class Ftr_geral_registry
{

    private $isAdmin = false;
    private $registry;
    private $load;
    private $config;
    private $session;
    private $db;
    private $cache;
    private $request;

    public function __construct($registry)
    {
        $this->registry = $registry;
        $this->load     = $registry->get('load');
        $this->config   = $registry->get('config');
        $this->session  = $registry->get('session');
        $this->db       = $registry->get('db');
        $this->cache    = $registry->get('cache');
        $this->request  = $registry->get('request');
    }

    public function __get($name)
    {
        return $this->registry->get($name);
    }

    public function isAdmin(): bool
    {
        return $this->isAdmin;
    }

    public function setIsAdmin(bool $isAdmin): void
    {
        $this->isAdmin = $isAdmin;
    }

    public function exibeMuduloLayout($layout)
    {
        if (isset($this->session->data['api_key'])) {
            if (($layout == Type_DisplayModuleOption::Tp_Todos) || ($layout == Type_DisplayModuleOption::Tp_Aplicativo)) {
                return true;
            }
        } else if (($layout == Type_DisplayModuleOption::Tp_Todos) || ($layout == Type_DisplayModuleOption::Tp_Ecommerce)) {
            return true;
        } else {
            return false;
        }
    }

    public function isApp()
    {

        // linha abaixo é pra testar quando é app
        // return true;

        if (isset($this->request->get['buildapp']) && ftr_geral::isInDevelopping()) {
            return true;
        }

        $dataUrl = explode('.', str_replace(array('https://wwww.', 'https://'), array('', ''), $this->request->server['HTTP_HOST']));

        if (isset($this->session->data['api_key']) || ($dataUrl[0] == 'm')) {
            return true;
        } else {
            return false;
        }
    }

    public function getConfigTemplate()
    {
        $this->load->type('tipocomum');

        if ($this->isApp()) {
            $template = Type_Theme::getNickFromValue(Type_Theme::Tp_appmobile);
        } else {
            $template = Type_Theme::getNickFromValue(Type_Theme::Tp_Vista);
        }

        if (isset($this->request->get['buildapp']) && ftr_geral::isInDevelopping()) {
            $template = Type_Theme::getNickFromValue(Type_Theme::Tp_appmobile);
        }

        return $template;
    }

    public function isSistema($tpSistema)
    {
        /* Modelo json
    {"sistemas": [
      {
        "id": "101",
        "descricao": "FUTURA SERVER"
      },
      {
        "id": "2401",
        "descricao": "E-commerce"
      }
    ]}  */
        $query = $this->db->query("select sistemas from parametros_efutura limit 1");
        if ($query->num_rows) {
            $sistemas = $query->row['sistemas'];
            $sistemas = json_decode(base64_decode($sistemas));
            $retorno = false;
            if (is_object($sistemas)) {
                foreach ($sistemas->sistemas as $sistema) {

                    if ((isset($sistema->id)) && ($sistema->id == $tpSistema)) {
                        $retorno = true;
                        break;
                    }
                }
            }
        } else {
            $retorno = false;
        }
        return $retorno;
    }


    public function getCache($name, $value)
    {

        $valuemd5 = md5($value);
        $cache_data = $this->cache->get($name . $valuemd5);

        if ($cache_data) {
            return $cache_data;
        } else {
            return false;
        }
    }

    public function setCache($name, $value, $time/* valor em segundos*/)
    {
        $valuemd5 = md5($value);
        $this->cache->set($name . $valuemd5, $value, $time);
    }

    public function gerarCache($name, $value, $time)
    {

        $cache = $this->getCache($name, $value);
        if ($cache) {
            return $cache;
        } else {
            $this->setCache($name, $value, $time);
            return $value;
        }
    }

    public function twigToHtml($filetemplate, $data)
    {
        $template    = new Twig($this->registry);
        $template->data = $data;
        return $template->fetch($filetemplate);
    }

    public function twigToString($filetemplate, $string, $array)
    {
        $template    = new Twig($this->registry);
        return $template->fetchString($filetemplate, $string, $array);
    }

    public function fetchStr($string, $array)
    {
        $template    = new Twig($this->registry);
        return $template->fetchStr($string, $array);
    }

    public function getStatusAviseme()
    {
        $aviseme_status =  Type_Status::Tp_Desabilitado;
        if (ftr_geral::isIsset($this->config->get('avise_me_status'))) {
            if ($this->config->get('config_stock_checkout')) {
                $aviseme_status =  Type_Status::Tp_Desabilitado;
            } else {
                $aviseme_status = $this->config->get('avise_me_status');
            }
        }
        return $aviseme_status;
    }


    public function getParametros()
    {
        $param_efutura = $this->db->query("select * from parametros_efutura");

        if ($param_efutura->num_rows) {
            return $param_efutura->row;
        } else {
            return false;
        }
    }

    public function getClienteNotify($order_status_id)
    {

        return $this->db->query("select client_notify from oc_order_status WHERE order_status_id = " . $order_status_id . " and language_id = 1")->row['client_notify'];
    }

    public function getScriptManifest($link, $cache)
    {

        $this->load->type('tipocomum');

        if (stristr($link, 'public')) {

            if (preg_match("/\/admin\/$/", DIR_APPLICATION)) {
                $pathJson = DIR_APPLICATION . 'view/public/manifest.json';
                $pathFile = 'view/';
            } elseif ($this->getConfigTemplate() == Type_Theme::getNickFromValue(Type_Theme::Tp_appmobile)) {
                $pathJson = DIR_APPLICATION . 'view/theme/appmobile/public/manifest.json';
                $pathFile = 'catalog/view/theme/appmobile/';
            } else {
                $pathJson = DIR_APPLICATION . 'view/theme/vista/public/manifest.json';
                $pathFile = 'catalog/view/theme/vista/';
            }

            $manifest = json_decode(file_get_contents($pathJson), true);

            $key = strstr($link, "public");

            if (array_key_exists($key, $manifest)) {
                return $pathFile . $manifest[$key];
            }
        }

        return ($cache && file_exists($link)) ? $link . '?version=' . filemtime($link) : $link;
    }


    public function getPathRecord()
    {

        return str_replace('image', 'arquivo', DIR_IMAGE);
    }

    public function getMktError($idxSession, $product_key_id)
    {

        $mkt_error = false;
        if (isset($this->session->data[$idxSession][$product_key_id])) {
            if (is_array($this->session->data[$idxSession][$product_key_id])) {
                $mkt_error[$product_key_id] = $this->session->data[$idxSession][$product_key_id];
            } else {
                $mkt_error = $this->session->data[$idxSession][$product_key_id];
            }
            unset($this->session->data[$idxSession][$product_key_id]);
        }

        return $mkt_error;
    }

    public function getUrlRelease($route)
    {

        $arrayUrl = array_map(function ($url) {
            $url = explode('&', $url);
            return $url[0];
        }, array_merge(Type_UrlLiberada::getEnumList(), Type_TaskUrl::getEnumList()));

        if (in_array($route, $arrayUrl)) {
            return true;
        }

        return false;
    }

    public function setEtiquetaPdf($pathFile, $data)
    {
        $file = fopen($pathFile, 'w+');
        fputs($file, $data);
        fclose($file);
    }

    public function permissaoAcessoUrl($config_task = false)
    {
        $taskexec = true;
        if ($config_task) {
            $data      = new DateTime($this->db->dataAtual(), new DateTimeZone('America/Sao_Paulo'));
            $data->modify('+1 minute');

            if ($config_task['predefined_execution'] == Type_PreConfigTask::Tp_PreConfigTask_Manual) {
                if (is_null($config_task['date_last_acting'])) {
                    $taskexec = true;
                } else {
                    $dateExecution   = date_format(date_add(date_create($config_task['date_last_acting']), new DateInterval("PT0H" . $config_task['time_execution'] . "M0S")), 'Y-m-d H:i:s');
                    $dataAtual = $data->format("Y-m-d H:i:s");
                    $taskexec = ($dataAtual > $dateExecution);
                }
            } else {
                $timeExec  = new DateTime(Type_PreConfigTask::getNickFromConstValue($config_task['predefined_execution']), new DateTimeZone('America/Sao_Paulo'));
                //não rodar 2x no mesmo dia
                $dateExecution = (is_null($config_task['date_last_acting'])) ||
                    date_format(date_create($config_task['date_last_acting']), 'Y-m-d') < $data->format("Y-m-d");
                $taskexec = (($data->format("H") == $timeExec->format("H"))  && ($dateExecution));
            }
        }

        /* O acesso só deve ser negado se a execução estiver fora do tempo de execução, caso contrario é possivel rodar a URL inclusive manualmente sem validação,
    precisa ser assim por causa do servidor novo */
        if (!ftr_geral::isInDevelopping() && !$taskexec) {
            die('Acesso negado');
        }
    }

    public function loadCaptcha()
    {
        $this->load->library('captcha');
        $captcha = new Captcha();
        $this->session->data['captcha'] = $captcha->getCode();
        $captcha->showImage();
    }

    public function validateCaptcha($captcha)
    {
        $google_captcha = $this->config->get('google_recaptcha_site_key') && $this->config->get('google_recaptcha_secret_key') && $this->config->get('wg24_google_recaptcha_status');
        if ($google_captcha) {
            $recaptcha = $this->validateGoogleCaptha($this->config->get('google_recaptcha_secret_key'), isset($captcha) ? $captcha : '', $this->request->server['REMOTE_ADDR']);
            return $recaptcha["success"];
        } else {
            return (!empty($this->session->data['captcha'])) && ($this->session->data['captcha'] == $captcha);
        }
    }

    public function validateGoogleCaptha($google_recaptcha_secret_key = '', $g_recaptcha_response = '', $remote_addr = '')
    {
        if (!isset($this->session->data['gcapcha'])) {
            if (!$g_recaptcha_response) {
                return array('success' => false);
            }
            ini_set("allow_url_fopen", 1);
            $recaptcha = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($google_recaptcha_secret_key) . '&response=' . $g_recaptcha_response . '&remoteip=' . $remote_addr);
            $recaptcha = json_decode($recaptcha, true);
            if ($recaptcha['success']) {
                $this->session->data['gcapcha'] = true;
            }
            return $recaptcha;
        } else {
            return array('success' => $this->session->data['gcapcha']);
        }
    }

    public function formatMessageVariable($message, $replace, $variable)
    {

        $find = array_map(function ($value) {
            return '{{' . $value . '}}';
        }, array_keys($variable));

        $newMessage = trim(str_replace($find, $replace, $message));

        return html_entity_decode(trim($newMessage), ENT_QUOTES, 'UTF-8');
    }

    public function organizeCustomLinks($type)
    {
        $this->load->dmodel('module/custom_links');
        $this->load->dmodel('tool/image');

        $customLinks = $this->dmodel_module_custom_links->getListEnabledByPosition($type);

        $links = [];

        foreach ($customLinks as $customLinksItem) {
            if (preg_match("/\./", $customLinksItem['icon'])) {
                $customLinksItem['icon'] = $this->dmodel_tool_image->resize(
                    "data/{$customLinksItem['icon']}",
                    Type_MiniatureSmall::Tp_width,
                    Type_MiniatureSmall::Tp_height
                );
            }

            if (empty($customLinksItem['parent'])) {
                array_push($links, $customLinksItem);
            }
        }

        foreach ($links as &$linksItem) {
            $linksItem['items'] = [];

            foreach ($customLinks as $customLinksItem) {
                if (preg_match("/\./", $customLinksItem['icon'])) {
                    $customLinksItem['icon'] = $this->dmodel_tool_image->resize(
                        "data/{$customLinksItem['icon']}",
                        Type_MiniatureSmall::Tp_width,
                        Type_MiniatureSmall::Tp_height
                    );
                }

                if ($customLinksItem['parent'] === $linksItem['custom_links_id']) {
                    array_push($linksItem['items'], $customLinksItem);
                }
            }
        }

        $links = ftr_geral::arraySort($links, 'order', SORT_ASC);

        foreach ($links as &$linksItem) {
            if (!empty($linksItem['items'])) {
                $linksItem['items'] = ftr_geral::arraySort($linksItem['items'], 'order', SORT_ASC);
            }
        }

        return $links;
    }


    public function validateMinInstallment($total, $generalMinInstallment, $installmentConfigs){
        $parametros_parcela = $installmentConfigs;

        //retrocompatibilidade para remover todas as parcelas que forem menor que a parcela minima
        $parametros_parcela = array_filter($parametros_parcela, function($parcela) use ($generalMinInstallment){
            return (float)$parcela['val_minimo'] >= (float)$generalMinInstallment;
        });

        $status = false;
        foreach ($parametros_parcela as $key => $param_parcela) {
            $parcela = $total / $param_parcela['num_parcela'];
            //Se pelo menos uma parcela for atendida, o módulo pode ser exibido
            if ( ($parcela  >= (float)$param_parcela['val_minimo']) && ((float)$param_parcela['val_minimo'] <= $total) &&
                ($parcela >= (float)$generalMinInstallment) ) {
                $status = true;
                break;
            }
        }

        return $status;
    }
}
