<?php

loadcontroller('base/module');

class ControllerModuleProductWhoSaw extends ControllerBaseModule{

    protected $referencePathFile = 'module/product_who_saw';

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

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

        $this->dataVue['TypesForJs'] = array(
            Type_Status::getTypeForJs(),
            Type_ModulePosition::getTypeForJs(),
            Type_IdLayout::getTypeForJs()
        );
    }

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

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

    protected function saveSetting(){
        if (isset($this->request->post['product_who_saw_module'])) {
            foreach ($this->request->post['product_who_saw_module'] as $key => $value) {
                //Forçando salvar o layoutid apenas para a tela de produtos
                $this->request->post['product_who_saw_module'][$key]['layout_id'] = Type_IdLayout::Tp_IdProduct;
            }
        }
        parent::saveSetting();
    }

    public function validate(){

        $this->loadLanguage();
        $targetIsDuplicatedObject = '';

        if (!$this->user->hasPermission('modify', 'module/product_who_saw')) {
            $this->errors['warning'] = $this->language->get('error_permission');
        }

        $productWhoSaw =  isset($this->request->post['product_who_saw_module'])? $this->request->post['product_who_saw_module'] : [];
        $errors = [];
        $productWhoSawModuleEnable = [] ;

        foreach ($productWhoSaw as $key => $value){
            if($value['status'] == Type_Status::Tp_Habilitado){
                array_push($productWhoSawModuleEnable , $value);
            }
        }

        $targetIsDuplicatedObject = $this->validate->targetIsDuplicatedObject(
            $productWhoSawModuleEnable,
            $this->language->get('error_duplicate'),
            ["position"]
        );


        if($targetIsDuplicatedObject){
            $errors['message'] = $targetIsDuplicatedObject;
        }

        return $errors;
    }
}
