<?php

loadcontroller('base/module');

class ControllerModuleSpecialAction extends ControllerBaseModule
{
    protected $referencePathFile = 'module/special_action';

    protected $arrayJson = ['special_action_module', 'special_action_promotions_selected'];

    protected function loadModel()
    {
        parent::loadModel();
    }

    protected function loadData()
    {
        $this->load->dmodel('design/layout');
        $this->load->model('catalog/special_action');
        $this->dataVue['special_action_options'] = $this->autocomplete();
        parent::loadData();

        $this->dataVue['TypesForJs'] = array(
            Type_DsimDnao::getTypeForJs(),
            Type_ModulePosition::getTypeForJs(),
            Type_DefaultValues::getTypeForJs(),
            Type_ActionPromotionStyle::getTypeForJs(),
            Type_Status::getTypeForJs()
        );

        // Remove as opções de layout que não são usadas nos módulos de lista de produtos
        $data = array(
            'notarray' => Type_NotListaProdutos::getEnumList()
        );

        if (isset($this->request->post['special_action_item'])) {
            $special_actions = explode(',', $this->request->post['special_action_item']);
        } else {
            $special_actions = explode(',', $this->config->get('special_action_item'));
        }

        $this->dataVue['special_actions'] = array();


        foreach ($special_actions as $special_action) {
            if ($special_action) {
                $special_info = $this->model_catalog_special_action->getSpecialAction($special_action);

                if ($special_info) {
                    $this->dataVue['special_actions'][] = array(
                        'order_promotion_id' => $special_info['order_promotion_id'],
                        'description'        => $special_info['description']
                    );
                }
            }
        }

        $this->dataVue['layouts'] = $this->dmodel_design_layout->getLayouts($data);
    }

    protected function actionUrls()
    {
        parent::actionUrls();

        $this->dataVue['special_actions_url'] =  $this->url->linkAnchor(
            'module/special_action/autocomplete',
            'token=' . $this->token,
            'filter_special=',
            'SSL'
        );
    }

    public function autocomplete()
    {
        $json = array();

        $this->load->helper('ftr_geral');
        $this->load->type('tipocomum');
        $this->load->model('catalog/special_action');

        $results = $this->model_catalog_special_action->getSpecialActions();

        foreach ($results as $result) {
            $json[] = array(
                'id' => $result['order_promotion_id'],
                'name'     => strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8'))
            );
        }

        return $json;
    }

    public function validate()
    {
        $this->loadLanguage();

        $errors = [];
        $targetLayoutIsDuplicatedObject = '';
        $specialActioModuleHabilitado = [];
        $hasAppMobileSelectedInSpecialActionModule = false;

        $specialActionModule =  isset($this->request->post['special_action_module']) ? $this->request->post['special_action_module'] : [];

        if (isset($specialActionModule) && !empty($specialActionModule)) {
            foreach ($specialActionModule as $key => $value) {
                if ($value['status'] == Type_Status::Tp_Habilitado) {
                    array_push($specialActioModuleHabilitado, $value);
                }

                if ($value['position'] == Type_ModulePosition::Tp_AppMobile) {
                    $hasAppMobileSelectedInSpecialActionModule = true;
                }

                $module_errors = $this->validate->execute([
                    'special_action_module[' . $key . '][limit]' => [
                        'value' => $value['limit'],
                        'validates' => ['isEmpty'],
                    ],
                ]);

                $errors = array_merge($errors, $module_errors);
            }
        }

        $targetLayoutIsDuplicatedObject = $this->validate->targetIsDuplicatedObject(
            $specialActioModuleHabilitado,
            $this->language->get('error_layout'),
            ["layout_id"]
        );

        if ($hasAppMobileSelectedInSpecialActionModule) {
            $targetPositionIsDuplicatedObject = $this->validate->targetIsDuplicatedObject(
                $specialActioModuleHabilitado,
                $this->language->get('error_layout'),
                ['position']
            );
        }

        if (
            (!$hasAppMobileSelectedInSpecialActionModule && $targetLayoutIsDuplicatedObject) ||
            ($hasAppMobileSelectedInSpecialActionModule && $targetPositionIsDuplicatedObject && $targetPositionIsDuplicatedObject)
        ) {
            $errors['message'] = $targetLayoutIsDuplicatedObject;
        }

        return $errors;
    }

    public function install()
    {
        $this->load->model('setting/extension');
        $this->model_setting_extension->install('module', 'special_action');
    }

    public function uninstall()
    {
        $this->load->model('setting/extension');
        $this->model_setting_extension->uninstallSetting('module', 'special_action');
    }
}
