<?php
loadController('base/module');

class ControllerModuleTrackingCode extends ControllerBaseModule
{

    protected $referencePathFile = 'module/tracking_code';
    protected $verify = false;

    protected function loadModel()
    {
        $this->load->dmodel('design/layout');
        parent::loadModel();
    }

    public function loadData()
    {
        $tracking_code = (array) $this->dmodel_module_tracking_code->getList();

        $tracking_code = array_map(function ($code) {
            $code['script'] = htmlspecialchars_decode($code['script']);
            if(!isset($code['tag'])){
                $code['tag'] = 0;
            }
            return $code;
        }, $tracking_code);

        $this->dataVue['tracking_code'] = $tracking_code;
        $this->dataVue['status'] = Type_Status::getEnumList();
        $this->dataVue['positions'] = Type_ScriptPosition::getEnumList();
        $this->dataVue['type_custom_tags'] = TypeCustomTags::getEnumList();

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

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

    protected function saveTable()
    {

        if (isset($this->request->post['excluded'])) {
            $this->dmodel_module_tracking_code->delete($this->request->post['excluded']);
        }

        if($this->verify == true){
            $this->responseJson['list'] = [];
        } else {
            $this->dmodel_module_tracking_code->add($this->request->post[$this->fileName]);
            $tracking_code = (array) $this->dmodel_module_tracking_code->getList();
            $tracking_code = array_map(function ($code) {
                $code['script'] = htmlspecialchars_decode($code['script']);
                return $code;
            }, $tracking_code);
            
            $this->responseJson['list'] = $tracking_code;
        }

    }
    
    protected function validate()
    {
        extract($this->request->post);

        $errors = [];
        if(isset($tracking_code) && !empty($tracking_code)){
            foreach ($tracking_code as $key => $value) {
                [
                    'title' => $title,
                    'script' => $script
                ] = $value;

                $errors = array_merge($errors, $this->validate->execute([
                    "tracking_code[$key][title]" => [
                        'value' => $title,
                        'validates' => ['isEmpty'],
                    ],
                    "tracking_code[$key][script]" => [
                        'value' => $script,
                        'validates' => ['isEmpty'],
                    ],
                ]));
            }
        } else {
            $this->verify = true;
        }

        return $errors;
    }
}
