<?php

class ControllerExtensionModule extends Controller
{
    public function index()
    {

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

        $this->data = array_merge($this->data, $this->language->load('extension/module'));

        $this->document->setTitle($this->language->get('heading_title'));

        $this->document->addScript(array(
            'view/javascript/page.module.js'
        ));

        $this->data['discontinued_module_message'] = $this->language->get('discontinued_module_message');


        $this->data['breadcrumbs'] = array();

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
            'separator' => false
        );

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL'),
            'separator' => ' :: '
        );

        if (isset($this->session->data['success'])) {
            $this->data['success'] = $this->session->data['success'];
            unset($this->session->data['success']);
        } else {
            $this->data['success'] = '';
        }

        if (isset($this->session->data['error'])) {
            $this->data['error'] = $this->session->data['error'];
            unset($this->session->data['error']);
        } else {
            $this->data['error'] = '';
        }

        $moduleName = (isset($this->request->get['module_name'])) ? $this->request->get['module_name'] : false;

        $this->load->model('setting/extension');

        //modulo de desconto/acrescimo yapay
        $ignoreTotal = array(
            'yapay',
            'wirecard'
        );

        $ignoreShipping = array(
//      'b2wentregacorreios',
//      'spreadsheet',
            TypeGaleriaPage_Module::Tp_Shipping,
            Type_MercadoLivreModule::Tp_Shipping,
            TypeSkyhub_Module::Tp_Shipping,
            Type_ShopeeModule::Tp_Shipping
        );

        $ignoreModule = array(
            'mosaic'
        );

        $ignorePayment = array(
            Type_FidelityPayment::Tp_FidelityPayment,
            TypeGaleriaPage_Module::Tp_Payment,
            Type_MercadoLivreModule::Tp_Payment,
            TypeSkyhub_Module::Tp_Payment,
            Type_ShopeeModule::Tp_Payment
        );

        $extensions = $this->model_setting_extension->getInstalledAll();
        $extensions['shipping'] = isset($extensions['shipping']) ? array_filter($extensions['shipping'], function ($value) use ($ignoreShipping) {
            return (!in_array($value, $ignoreShipping));
        }) : array();
        $extensions['module'] = isset($extensions['module']) ? array_filter($extensions['module'], function ($value) use ($ignoreModule) {
            return (!in_array($value, $ignoreModule));
        }) : array();
        $extensions['payment'] = isset($extensions['payment']) ? array_filter($extensions['payment'], function ($value) use ($ignorePayment) {
            return (!in_array($value, $ignorePayment));
        }) : array();
        $extensions['total'] = isset($extensions['total']) ? array_filter($extensions['total'], function ($value) use ($ignoreTotal) {
            return (!in_array($value, $ignoreTotal));
        }) : array();

        foreach ($extensions as $key => $extension) {
            foreach ($extension as $extKey => $value) {
                if (!file_exists(DIR_APPLICATION . 'controller/' . $key . '/' . $value . '.php') && (defined('PREFIX_NAME') && !file_exists(DIR_APPLICATION . 'controller/specific/' . PREFIX_NAME . '/' . $key . '/' . $value . '.php'))) {
                    $this->model_setting_extension->uninstall($key, $value);
                    unset($extensions[$key]);
                }
            }
        }

        $typeModules = array(
            Type_TitleModules::Tp_ListProd => array(
                'module/bestseller',
                'module/featured',
                'module/latest',
                'module/lpbc',
                'module/product_viewed_all',
                'module/product_visualized',
                'module/random',
                'module/special',
                'module/special_action',
                'module/produtosrelacionados',
                'module/starter_kit',
                'module/boughtalso'
            ),
            Type_TitleModules::Tp_Config => array(
                'module/avise_me',
                'module/clearsale',
                'module/fields_register_brazil',
                'module/futuralimitaritem',
                'module/futuraquantidadeatacado',
                'module/listapresente',
                'module/modulofutura',
                'module/preco_dinamico',
                'module/futuragrade',
                'module/valor_minimo',
                'module/wg24themeoptionpanel',
                'module/newsletter',
                'module/store_rating',
                'module/task',
                'module/fidelity',
                'module/processo_venda',
                'module/loginredesociais'
            ),
            Type_TitleModules::Tp_Filtros => array(
                'module/futurafiltromarca',
                'module/futurafiltrovalor',
                'module/futura_filter_selected'
            ),
        );

        if ($this->config->get('config_sistema_marketplace')) {
            $typeModules[Type_TitleModules::Tp_Marketplace] = array(
                'module/mercadolivre',
                'module/skyhub',
                'module/galeriapage',
                'module/shopee',
            );
        }

        if ($this->config->get('config_ramo_atividade') == Type_RamoAtividade::Tp_Papelaria) {
            $typeModules[Type_TitleModules::Tp_Config][] = 'module/listaescolar';
        }

        $module = glob(DIR_APPLICATION . 'controller/module/*.php');

        $this->data['extensions'] = array();

        $payment = glob(DIR_APPLICATION . 'controller/payment/*.php');
        $shipping = glob(DIR_APPLICATION . 'controller/shipping/*.php');
        $total = glob(DIR_APPLICATION . 'controller/total/*.php');

        $this->specific->loadFiles($module, $payment, $shipping, $total);

        $files = array_merge($module, $payment, $shipping, $total);

        $ignoreFiles = array(
            'geralconfigs' => false,
            'cielo_transparente' => $this->config->get('cielo_transparente_status'),
            'FuturaKomerci' => $this->config->get('FuturaKomerci_status'),
            'pp_express' => $this->config->get('pp_express_status'),
            'jadlog' => $this->config->get('jadlog_status'),
            'banner' => false,
            'carousel' => false,
            'mercadolivre' => $this->config->get('config_sistema_marketplace'),
            'skyhub' => $this->config->get('config_sistema_marketplace'),
            'galeriapage' => $this->config->get('config_sistema_marketplace'),
            'shopee' => $this->config->get('config_sistema_marketplace'),
        );

        $ignoreFiles = array_merge($ignoreFiles, $this->specific->getIgnoreFiles());

        if ($files) {
            foreach ($files as $file) {
                $extension = basename($file, '.php');
                if (array_key_exists($extension, $ignoreFiles) && (!$ignoreFiles[$extension])) {
                    next($files);
                } else {
                    $pasta = array_reverse(explode('/', dirname($file)))[0];

                    $this->language->load($pasta . '/' . $extension);

                    switch ($pasta) {
                        case 'module':
                            $extensionName = $pasta . '/' . $extension;
                            $tipo = Type_TitleModules::Tp_Outros;

                            if (in_array($extensionName, $typeModules[Type_TitleModules::Tp_ListProd])) {
                                $tipo = Type_TitleModules::Tp_ListProd;
                            }

                            if (in_array($extensionName, $typeModules[Type_TitleModules::Tp_Config])) {
                                $tipo = Type_TitleModules::Tp_Config;
                            }

                            if (in_array($extensionName, $typeModules[Type_TitleModules::Tp_Filtros])) {
                                $tipo = Type_TitleModules::Tp_Filtros;
                            }

                            if ($this->config->get('config_sistema_marketplace')) {
                                if (in_array($extensionName, $typeModules[Type_TitleModules::Tp_Marketplace])) {
                                    $tipo = Type_TitleModules::Tp_Marketplace;
                                }
                            }
                            break;
                        case 'shipping':
                            $tipo = Type_TitleModules::Tp_Envio;
                            break;
                        case 'payment':
                            $tipo = Type_TitleModules::Tp_Pagamento;
                            break;
                        case 'total':
                            $tipo = Type_TitleModules::Tp_Finalizacao;
                            break;
                    }

                    switch ($extension) {
                        case 'redirecionamento301':
                            $link = $this->specific->getLink('outros/' . $extension, $this->session->data['token'], $tipo);
                            break;
                        case 'mercadolivre':
                        case 'skyhub':
                        case 'galeriapage':
                        case 'shopee':
                            $link = $this->specific->getLink($pasta . '/' . $extension . '/settings', $this->session->data['token'], $tipo);
                            break;
                        default:
                            $link = $this->specific->getLink($pasta . '/' . $extension, $this->session->data['token'], $tipo);
                    }

                    $link = array(
                        'text' => $this->language->get('text_edit'),
                        'href' => $link,
                        'icon' => 'fas fa-pencil-alt'
                    );

                    if (!in_array($extension, $extensions[$pasta])) {
                        $status = Type_DsimDnao::Tp_Nao;
                        $action = $this->url->link('extension/module/install', 'token=' . $this->session->data['token'] . '&extension=' . $extension . '&type=' . $pasta, 'SSL');
                    } else {
                        $status = Type_DsimDnao::Tp_Sim;
                        $action = $this->url->link('extension/module/uninstall', 'token=' . $this->session->data['token'] . '&extension=' . $extension . '&type=' . $pasta, 'SSL');
                    }

                    if ($this->config->has($extension . '_status')) {
                        $status = $this->config->get($extension . '_status') ? $this->language->get('text_enabled') : $this->language->get('text_disabled');
                    }

                    if (file_exists('view/image/' . $pasta . '/' . strtolower($extension) . '.jpg')) {
                        $img = 'view/image/' . $pasta . '/' . strtolower($extension) . '.jpg';
                    } else if (file_exists('view/image/' . $pasta . '/' . strtolower($extension) . '.png')) {
                        $img = 'view/image/' . $pasta . '/' . strtolower($extension) . '.png';
                    } else {
                        $img = 'view/image/sem-imagem.png';
                    }

                    $display = true;
                    if (in_array($extension, Type_BoletoBanco::getEnumList()) && (count($action) == 1)) {
                        $display = false;
                    }

                    switch ($pasta) {
                        case 'shipping':
                            $moduleType = Type_TitleModules::Tp_Envio;
                            break;
                        case 'payment':
                            $moduleType = Type_TitleModules::Tp_Pagamento;
                            break;
                        case 'total':
                            $moduleType = Type_TitleModules::Tp_Finalizacao;
                            break;
                        case 'module':
                            foreach ($typeModules as $key => $value) {
                                $moduleType = Type_TitleModules::Tp_Outros;
                                if (in_array('module/' . $extension, $typeModules[$key])) {
                                    if ($moduleName && $moduleName == 'module/' . $extension) {
                                        $moduleType = $key;
                                        break;
                                    } else {
                                        $moduleType = $key;
                                        break;
                                    }
                                }
                            }
                            break;
                    }

                    $this->data['extensions'][$moduleType][] = array(
                        'title' => Type_TitleModules::getNickFromValue($moduleType),
                        'name' => $this->language->get('heading_title'),
                        'data_name' => preg_replace("/&([a-z])[a-z]+;/i", "$1", htmlentities(trim(strip_tags($this->language->get('heading_title'))))),
                        'action' => $action,
                        'sort_order' => $this->config->get($extension . '_sort_order'),
                        'display' => $display,
                        'status' => $status,
                        'img' => $img,
                        'link' => $link,
                        'news' => ftr_geral::getNovidadeModulo($this->language->get($extension . '_data_new')),
                    );
                }
            }
        }


        $discontinued_payments = array(
            'Komerci Integrado',
            'Checkout Cielo Transparente',
            'PayPal Express Checkout'
        );

        $this->data['discontinued_payments'] = $discontinued_payments;

        if (isset($this->request->get['module'])) {
            $this->data['moduleType'] = $this->request->get['module'];
        } else {
            $this->data['moduleType'] = Type_TitleModules::Tp_Outros;
        }

        $this->data['extensions'] = array_reverse($this->data['extensions'], true);
        uksort($this->data['extensions'], function ($key) {
            if ($key == Type_TitleModules::Tp_Outros){
                return -1;
            }
            return ($key > Type_TitleModules::Tp_Outros) ? 1 : 0;
        });

        foreach ($this->data['extensions'] as $key => $value) {
            usort(
                $value,
                function ($a, $b) {
                    if ($a['news'] == $b['news']) return 0;
                    return (($a['news'] > $b['news']) ? -1 : 1);
                }
            );
        }


        $this->children = array(
            'common/header',
            'common/footer'
        );

        $this->response->setOutput($this->render('extension/module'));
    }

    public function install()
    {
        $type = $this->request->get['type'];
        $this->language->load('extension/' . $type);
        $json = array();

        if (!$this->user->hasPermission('modify', 'extension/' . $type)) {
            $json['error'] = $this->language->get('error_permission');
        } else {
            $this->load->model('setting/extension');

            switch ($this->request->get['extension']) {
                case 'sub_total';
                case 'total' :
                    $subtype = Type_ExtensionSubType::Tp_Totalizador;
                    break;
                case 'shipping' :
                    $subtype = Type_ExtensionSubType::Tp_TotalizadorFrete;
                    break;
                case in_array($this->request->get['extension'],
                    ['coupon', 'descontoporpagamento', 'descontoprimeiracompra',
                        'descontofaixavalorpedido', 'low_order_fee', 'descontoacrescimokit', 'yapay', 'wirecard']) :
                    $subtype = Type_ExtensionSubType::Tp_TotalizadorAcrescimoDesconto;
                    break;
                default :
                    $subtype = Type_ExtensionSubType::Tp_Default;
                    break;

            }

            $this->model_setting_extension->install($type, $this->request->get['extension'], $subtype);

            $this->load->model('user/user_group');

            $this->model_user_user_group->addPermission($this->user->getId(), 'access', $type . '/' . $this->request->get['extension']);
            $this->model_user_user_group->addPermission($this->user->getId(), 'modify', $type . '/' . $this->request->get['extension']);


            $class = $this->specific->getPathController($type, $this->request->get['extension']);
            $class = new $class($this->registry);

            $json['success'] = 'Módulo instalado com sucesso!';
            if (method_exists($class, 'install')) {
                $class->install();
            }
        }
        $this->response->setOutput(json_encode($json));
    }

    public function uninstall()
    {
        $type = $this->request->get['type'];
        $this->language->load('extension/' . $type);
        $this->load->type('tipocomum');
        $modulos = Type_ModulosObrigatorios::getEnumList();
        $this->load->model('setting/setting');
        $json = array();

        if (!$this->user->hasPermission('modify', 'extension/' . $type) || (in_array($this->request->get['extension'], $modulos))) {
            if (in_array($this->request->get['extension'], $modulos)) {
                $json['error'] = $this->language->get('error_permission_module');
            } else {
                $json['error'] = $this->language->get('error_permission');
            }
        }

        if ($type == Type_DefaultValues::Tp_Payment) {

            $result = $this->model_setting_setting->getSalesByPayment($this->request->get['extension']);
            if ($result > 0) {
                $json['error'] = 'O método de pagamento ' . $this->request->get['extension'] . ' não pode ser desinstalado porque existe pedidos vinculados. Você pode desabilita-lo.';
            }

        }


        if (count($json) == 0) {
            $this->load->model('setting/extension');
            $this->load->model('setting/setting');

            $this->model_setting_extension->uninstall($type, $this->request->get['extension']);

            $this->model_setting_setting->deleteSetting($this->request->get['extension']);

            require_once(DIR_APPLICATION . 'controller/' . $type . '/' . $this->request->get['extension'] . '.php');

            $class = $this->specific->getPathController($type, $this->request->get['extension']);
            $class = new $class($this->registry);

            $json['success'] = 'Módulo desinstalado com sucesso!';
            if (method_exists($class, 'uninstall')) {
                $class->uninstall();
            }
        }

        $this->response->setOutput(json_encode($json));

    }
}
