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

use system\library\marketplace\MktPriceAdjustments;

class ControllerModuleMercadolivreMeasureManufacturer extends ControllerInsertList
{
    protected $referencePathFile = 'module/mercadolivre/measure_manufacturer';
    protected $mktPriceAdjustments;

    public function __construct($registry)
    {
        parent::__construct($registry);
        $this->mktPriceAdjustments = new MktPriceAdjustments($registry, ['tipo_integracao' => Type_MarketPlace::Tp_Mercadolivre]);
    }

    protected function loadLanguage()
    {
        parent::loadLanguage();
        $this->data = array_merge($this->data, $this->load->language('marketplace/marketprice'));
    }

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

    protected function loadModel()
    {
        parent::loadModel();
        $this->load->model('mercadolivre/mercadolivre');
        $this->load->model('localisation/order_status');
        $this->load->dmodel('mercadolivre/melipedido');
        $this->load->model('mercadolivre/measure_manufacturer');
        $this->load->model('catalog/manufacturer');
    }

    protected function breadcrumbs()
    {
        $type = $this->request->get['type'];

        $this->dataVue['breadcrumbs'] = [
            [
                'href' => $this->url->link('common/home', 'token=' . $this->token, 'SSL'),
                'text' => $this->language->get('text_home'),
            ],
            [
                'href' => $this->url->link($this->referencePathFile, 'token=' . $this->token . '&type=' . $type, 'SSL'),
                'text' => $this->language->get('heading_title'),
            ],
            [
                'href' => $this->url->link('module/mercadolivre/measure_manufacturer', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL'),
                'text' => $this->language->get('text_measure_manufacturer'),
            ],
        ];
    }

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

        $this->actionUrls();

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

        $this->dataVue['TypesForJs'] = array(
            Type_Status::getTypeForJs(),
            Type_MercadoLivremercaListType::getTypeForJs(),
            Type_MercadoLivreCondition::getTypeForJs(),
            Type_Garantia::getTypeForJs(),
            Type_TempoGarantia::getTypeForJs(),
            Type_MarketplaceTypeAdjustment::getTypeForJs(),
            Type_MarketplaceAdjustmentPrice::getTypeForJs(),
        );

        $this->dataVue['url'] = array(
            'autentication' => $this->urlloja->link('', '', 'NONSSL', false) . 'mercadolivreauth',
            'notification' => $this->urlloja->link('', '', 'NONSSL', false) . 'mercadolivrecallback',
            'sincat' => $this->urlloja->link('mercadolivre/mercadolivre/syncat', '', 'SSL'),
            'validateaccount' => $this->url->link('module/mercadolivre/settings/validateaccount', 'token=' . $this->session->data['token'], 'SSL'),
            'help' => Type_LinkManual::getNickFromValue(Type_LinkManual::Tp_linkManualConfigMercadoLivre),
            'category' => $this->url->link('module/mercadolivre/mercadolivre/category', 'token=' . $this->session->data['token'], 'SSL'),
            'typeshipping' => $this->url->link('module/mercadolivre/settings/typeshipping', 'token=' . $this->session->data['token'], 'SSL')
        );

        $this->dataVue['text_title_tab_setting_desc'] = sprintf($this->language->get('text_title_tab_setting_desc'), Type_LinkManual::getNickFromValue(Type_LinkManual::Tp_linkManualConfigMercadoLivre));

        $this->dataVue['validate_account'] = ($this->mercadolivre->getAccess()) ? true : false;

        $this->dataVue['userGroup'] = ($this->user->getUserGroup() == Type_UserGroupAdm::Tp_UserFutura) ? true : false;

        $this->dataVue['mercadolivre_cats'] = $this->model_mercadolivre_mercadolivre->getMercadoCategoryOption($this->dataVue['configurations']['mercadolivre_mercaId'], false);

        if ($this->config->get('processo_venda_status')) {
            $this->load->dmodel('proccess/order_to_situation');
            $order_statuses = $this->dmodel_proccess_order_to_situation->getProccessStatusAll();
        } else {
            $order_statuses = $this->model_localisation_order_status->getOrderStatuses();
        }

        $this->dataVue['order_statuses'] = $order_statuses;

        // carrega Lista de Marcar já Cadastradas no mercado Livre Brand

        $this->dataVue['categories_main'] = $this->getCategoryMain();
        $this->dataVue['manufacturer']    = $this->getManufacturer();
        $this->dataVue['valueSize']       = $this->getSystemSize();

        $this->dataVue['mercadolivre_types_comission'] = $this->model_mercadolivre_mercadolivre->getMercadoType();

        $merca_statuses = array();
        foreach (Type_MercadoLivreStatus::getEnumList() as $key => $mercastatus) {
            $merca_statuses[] = array(
                'type' => $key,
                'name' => $mercastatus,
                'status' => $this->dmodel_mercadolivre_melipedido->getOCStatus($key)
            );
        }

        $this->filter();

        $this->dataVue['merca_statuses'] = $merca_statuses;

        $this->dataVue['marketprice'] = $this->mktPriceAdjustments->getDataJson();

    }

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

        $this->load->helper('ftr_geral');
        $this->load->helper('ftr_validacao');
        extract($this->request->post);
        $tableType = $_POST['info']['domain_id'];
        $errors = [];

        $error = $this->validate->execute([
            "description_ML" => [
                'value' => $info['name'],
                'validates' => ['isEmpty'],
            ]
        ]);

        if($error) {
            array_push($errors, $error);
        }
        //NEW
        if($tableType === 'MLB-SNEAKERS'){
            $errors = $this->validate->validateGrid($rows,
            array('0' => ["colum" =>'size'   , 'name' => 'BR'     ],
                '1' => ["colum" =>'tamanho', 'name' => 'Tamanho']), 'notRepeat');

            foreach($rows as $row => $value){
                $error = $this->validate->execute(array_merge([
                    "$row.tamanho" => [
                        'value' => $value['tamanho'],
                        'validates' => ['isEmpty'],
                    ],
                    "$row.BR" => [
                        'value' => $value['size'],
                        'validates' => ['isEmpty'],
                    ],
                    "$row.Comprimento" => [
                        'value' => str_replace('.',',',$value['length']),
                        'validates' => ['isEmpty',
                        [
                            'method' => 'isMinMaxNumber',
                            'min' => 5,
                            'max' => 40]
                        ]
                    ]
                ]));

                if($error) {
                    array_push($errors, $error);
                }
            }
        }else{
            if($tableType === 'MLB-SHORTS'){
                $errors = $this->validate->validateGrid($rows,
                array('0' => ["colum" =>'tamanho', 'name' => 'Tamanho'],
                      '1' => ["colum" =>'hip_circumference_from'   , 'name' => 'hip_circumference_from'],
                      '2' => ["colum" =>'hip_circumference_to', 'name' => 'hip_circumference_to'],
                      '3' => ["colum" =>'person_height_from'   , 'name' => 'person_height_from'],
                      '4' => ["colum" =>'person_height_to', 'name' => 'person_height_to'],
                      '5' => ["colum" =>'waist_circumference_from'   , 'name' => 'waist_circumference_from'],
                      '6' => ["colum" =>'waist_circumference_to', 'name' => 'waist_circumference_to'],          
                ),'notRepeat');
            }else{
                $errors = $this->validate->validateGrid($rows,
                array('0' => ["colum" =>'tamanho', 'name' => 'Tamanho'],
                      '1' => ["colum" =>'chest_circumference_from'   , 'name' => 'chest_circumference_from'],
                      '2' => ["colum" =>'chest_circumference_to', 'name' => 'chest_circumference_to'],
                      '3' => ["colum" =>'hip_circumference_from'   , 'name' => 'hip_circumference_from'],
                      '4' => ["colum" =>'hip_circumference_to', 'name' => 'hip_circumference_to'],
                      '5' => ["colum" =>'person_height_from'   , 'name' => 'person_height_from'],
                      '6' => ["colum" =>'person_height_to', 'name' => 'person_height_to'],
                      '7' => ["colum" =>'waist_circumference_from'   , 'name' => 'waist_circumference_from'],
                      '8' => ["colum" =>'waist_circumference_to', 'name' => 'waist_circumference_to'],          
                ),'notRepeat');
            };
                  
            foreach($rows as $row => $value) {
                $validations = [
                    "$row.tamanho" => [
                        'value' => $value['tamanho'],
                        'validates' => ['isEmpty'],
                    ],
                    "$row.filtrable_size" => [
                        'value' => $value['filtrable_size'][0] ? $value['filtrable_size'][0] : $value['filtrable_size'],
                        'validates' => ['isEmpty']
                    ],
                    "$row.waist_circumference_from" => [
                        'value' => str_replace('.', ',', $value['waist_circumference_from']),
                        'validates' => [
                            'isEmpty',
                            [
                                'method' => 'isMinMaxNumber',
                                'min' => 1,
                                'max' => 500
                            ]
                        ]
                    ],
                    "$row.waist_circumference_to" => [
                        'value' => str_replace('.', ',', $value['waist_circumference_to']),
                        'validates' => [
                            [
                                'method' => 'isMinMaxNumber',
                                'min' => 1,
                                'max' => 500
                            ]
                        ]
                    ],
                    "$row.person_height_from" => [
                        'value' => str_replace('.', ',', $value['person_height_from']),
                        'validates' => [
                            [
                                'method' => 'isMinMaxNumber',
                                'min' => 1,
                                'max' => 500
                            ]
                        ]
                    ],
                    "$row.person_height_to" => [
                        'value' => str_replace('.', ',', $value['person_height_to']),
                        'validates' => [
                            [
                                'method' => 'isMinMaxNumber',
                                'min' => 1,
                                'max' => 500
                            ]
                        ]
                    ],
                    "$row.hip_circumference_from" => [
                        'value' => str_replace('.', ',', $value['hip_circumference_from']),
                        'validates' => [
                            [
                                'method' => 'isMinMaxNumber',
                                'min' => 1,
                                'max' => 500
                            ]
                        ]
                    ],
                    "$row.hip_circumference_to" => [
                        'value' => str_replace('.', ',', $value['hip_circumference_to']),
                        'validates' => [
                            [
                                'method' => 'isMinMaxNumber',
                                'min' => 1,
                                'max' => 500
                            ]
                        ]
                    ],
                ];
            
                if ($tableType !== 'MLB-SHORTS') {
                    $additionalValidations = [
                        "$row.chest_circumference_from" => [
                            'value' => str_replace('.', ',', $value['chest_circumference_from']),
                            'validates' => [
                                'isEmpty',
                                [
                                    'method' => 'isMinMaxNumber',
                                    'min' => 1,
                                    'max' => 500
                                ]
                            ]
                        ],
                        "$row.chest_circumference_to" => [
                            'value' => str_replace('.', ',', $value['chest_circumference_to']),
                            'validates' => [
                                [
                                    'method' => 'isMinMaxNumber',
                                    'min' => 1,
                                    'max' => 500
                                ]
                            ]
                        ],
                    ];
            
                    $validations = array_merge($validations, $additionalValidations);
                }
            
                $error = $this->validate->execute($validations);
            
                if($error) {
                    array_push($errors, $error);
                }

                if($tableType === 'MLB-SHORTS'){
                    $modifications = [
                        'filtrable_size' => 'Equivalências do tamanho',
                        'waist_circumference_from' => 'Cincunferência da cintura',
                        'waist_circumference_to' => 'Cincunferência da cintura',
                        'person_height_from' => 'Altura da pessoa',
                        'person_height_to' => 'Altura da pessoa',
                        'hip_circumference_from' => 'Circunferência do quadril',
                        'hip_circumference_to' => 'Circunferência do quadril',
                    ];
                }else{
                    $modifications = [
                        'filtrable_size' => 'Equivalências do tamanho',
                        'chest_circumference_from' => 'Contorno do peito',
                        'chest_circumference_to' => 'Contorno do peito',
                        'waist_circumference_from' => 'Cincunferência da cintura',
                        'waist_circumference_to' => 'Cincunferência da cintura',
                        'person_height_from' => 'Altura da pessoa',
                        'person_height_to' => 'Altura da pessoa',
                        'hip_circumference_from' => 'Circunferência do quadril',
                        'hip_circumference_to' => 'Circunferência do quadril',
                    ];
                };

                foreach ($errors as $keyMap => &$item) {
                    foreach ($modifications as $originalKey => $newKey) {
                        $fullOriginalKey = "$row.$originalKey";
                        if (isset($item[$fullOriginalKey])) {
                            $item["$row.$newKey"] = $item[$fullOriginalKey];
                            unset($item[$fullOriginalKey]);
                        }
                    }
                }
            }
        }
        return  $errors;
    }

    public function save(){
        $this->load->type('tipocomum');
        $this->loadLanguage();
       // $this->loadModel();
        $this->hasPermission();
        extract($this->request->post);
        $this->errors = $this->validate();

        $type = isset($list['names'][0]['type'])? $list['names'][0]['type'] : 'SPECIFIC';

        if(!$this->errors) {
            if ($type == Type_MercadoLivreTypeCharts::getEnumList()[0]) {
                $this->saveBrand();
            } else if ($type == Type_MercadoLivreTypeCharts::getEnumList()[1]) {
                $this->saveStandard();
            } else {
                $this->saveSpecific();
            }

            $this->responseJson['errors'] = $this->errors;
        } else {
            $this->responseJson['errors'] = $this->errors;
        }

        $this->response->setOutputJson($this->responseJson);
    }

    private function saveBrand(){
        $this->loadModel();
        //BRAND apenas salvas as informações na base vindas do mercado livre.
        extract($this->request->post);
        if(isset($list['names'][0]['grid_id'])){
            $this->model_mercadolivre_measure_manufacturer->deleteMeasured(array("list" => $list['names'][0]['grid_id']));
        }
        $result = $this->model_mercadolivre_measure_manufacturer->setCharts();

    }
    private function saveStandard(){
        extract($this->request->post);
    }
    private function saveSpecific(){
        $this->loadModel();
        extract($this->request->post);
        array_push($info, $this->model_catalog_manufacturer->getManufacturer($info['brand']));
        $newList = [];
        $genders = $this->mercadolivre->getChatsGender((object) $info);
        $valueGender = '';
        foreach ($genders as $gender){
            if($gender->id == $info['gender']){
                $valueGender = $gender->name;
                break;
            }
        }

        if(!$selected){ //Crian novo  chart specific
            $newList = $this->mercadolivre->setChatsSpecific($info, $rows,$valueGender);
        }else{
            //Atualização de linhas
            $addRows = [];
            if($info['domain_id'] === "MLB-SNEAKERS"){
                foreach ($rows as $key => $row){
                    if(isset($row['id'])){
                        $alterData = [];
                        foreach ($list['rows'][$selected] as $linha){
                            if($row['id'] == $linha['id']){
                                foreach ($linha['attributes'] as $attibute){

                                    if($attibute['id'] == 'FOOT_LENGTH'){
                                        if( (float) $attibute['values'][0]['name'] != (float)$row['length']){
                                            array_push($alterData, array(
                                                "colum_name"=>'FOOT_LENGTH',
                                                "value" => $row['length'],
                                                "gender" => $valueGender
                                            ));
                                            unset($rows[$key]['length']);
                                        }else{unset($rows[$key]['length']);}
                                    }
                                    if( $attibute['id']== 'EU_SIZE'){
                                        if( (float) $attibute['values'][0]['name'] != (float)$row['eu']){
                                            array_push($alterData, array(
                                                "colum_name"=>'EU_SIZE',
                                                "value" => $row['eu'],
                                                "gender" => $valueGender
                                            ));
                                            unset($rows[$key]['eu']);
                                        }else{unset($rows[$key]['eu']);}
                                    }
                                    if(strrpos($attibute['id'], 'US_SIZE') !== false){
                                        if( (float) $attibute['values'][0]['name'] != (float)$row['us']){
                                            array_push($alterData, array(
                                                "colum_name"=>'US_SIZE',
                                                "value" => $row['us'],
                                                "gender" => $valueGender
                                            ));
                                            unset($rows[$key]['us']);
                                        }else{unset($rows[$key]['us']);}
                                    }
                                    if( $attibute['id']== 'UK_SIZE'){
                                        if( (float)$attibute['values'][0]['name'] != (float)$row['uk']){
                                            array_push($alterData, array(
                                                "colum_name"=>'UK_SIZE',
                                                "value" => $row['uk'],
                                                "gender" => $valueGender
                                            ));
                                            unset($rows[$key]['uk']);
                                        }else{unset($rows[$key]['uk']);}
                                    }
                                }
                            }
                        }
                        //Novos campos como US UK EU Adicionados.
                        if(isset($rows[$key]['eu']) AND $rows[$key]['eu']){
                            array_push($alterData, array(
                                "colum_name"=>'EU_SIZE',
                                "value" => $row['eu'],
                                "gender" => $valueGender
                            ));
                        }
                        if(isset($rows[$key]['us']) AND $rows[$key]['us']){
                            array_push($alterData, array(
                                "colum_name"=>'US_SIZE',
                                "value" => $row['us'],
                                "gender" => $valueGender
                            ));
                        }
                        if(isset($rows[$key]['uk']) AND $rows[$key]['uk']){
                            array_push($alterData, array(
                                "colum_name"=>'UK_SIZE',
                                "value" => $row['uk'],
                                "gender" => $valueGender
                            ));
                        }
                        //Atualiza informações da linha.
                        if($alterData)
                            $newList = $this->setAlterChats($row['id'],$selected,$alterData, substr($info['domain_id'],4 , 100));
                        }else{
                            array_push($addRows,array(
                                "data" => $row,
                            ));
                        }
                    }
                }else{
                    //NEW
                    foreach ($rows as $key => $row){
                        if(isset($row['id'])){
                            $alterData = [];
                            $result = [];
                            foreach ($list['rows'][$selected] as $linha){
                                if($row['id'] == $linha['id']){
                                    foreach ($linha['attributes'] as $attibute){
                                        if($attibute['id'] == 'FILTRABLE_SIZE'){
                                            $filtrable_size_html = html_entity_decode($attibute['values'][0]['name']);
                                            $filtrable_size = json_decode($filtrable_size_html);
                                            
                                            if(is_array($filtrable_size)){
                                                foreach($filtrable_size as $item){
                                                    $part = explode(' ', $item);
                                                    if (count($part) > 0) {
                                                        $result[] = $part[0];
                                                    }
                                                }
                                                $filtrable_size = $result;
                                            }else{
                                                $part = explode(' ', $filtrable_size);
                                                if (count($part) > 0) {
                                                    $result[] = $part[0];
                                                }
                                                $filtrable_size = $result;
                                            }
                                                                                      
                                            if($filtrable_size != $row['filtrable_size']){
                                                array_push($alterData, array(
                                                    "colum_name"=>'FILTRABLE_SIZE',
                                                    "value" => $row['filtrable_size'],
                                                    "gender" => $valueGender
                                                ));
                                                unset($rows[$key]['filtrable_size']);
                                            }else{unset($rows[$key]['filtrable_size']);}
                                        }
                                        if($attibute['id'] === 'CHEST_CIRCUMFERENCE_FROM' && $info['domain_id'] !== "MLB-SHORTS"){
                                            if( (float) $attibute['values'][0]['name'] != (float)$row['chest_circumference_from']){
                                                array_push($alterData, array(
                                                    "colum_name"=>'CHEST_CIRCUMFERENCE_FROM',
                                                    "value" => $row['chest_circumference_from'],
                                                    "gender" => $valueGender
                                                ));
                                                unset($rows[$key]['chest_circumference_from']);
                                            }else{unset($rows[$key]['chest_circumference_from']);}
                                        }
                                        if($attibute['id'] === 'WAIST_CIRCUMFERENCE_FROM'){
                                            if( (float) $attibute['values'][0]['name'] != (float)$row['waist_circumference_from']){
                                                array_push($alterData, array(
                                                    "colum_name"=>'WAIST_CIRCUMFERENCE_FROM',
                                                    "value" => $row['waist_circumference_from'],
                                                    "gender" => $valueGender
                                                ));
                                                unset($rows[$key]['waist_circumference_from']);
                                            }else{unset($rows[$key]['waist_circumference_from']);}
                                        }
                                        if($attibute['id'] === 'CHEST_CIRCUMFERENCE_TO' && $info['domain_id'] !== "MLB-SHORTS"){
                                            if( (float) $attibute['values'][0]['name'] != (float)$row['chest_circumference_to']){
                                                array_push($alterData, array(
                                                    "colum_name"=>'CHEST_CIRCUMFERENCE_TO',
                                                    "value" => $row['chest_circumference_to'],
                                                    "gender" => $valueGender
                                                ));
                                                unset($rows[$key]['chest_circumference_to']);
                                            }else{unset($rows[$key]['chest_circumference_to']);}
                                        }
                                        if($attibute['id'] === 'WAIST_CIRCUMFERENCE_TO'){
                                            if( (float) $attibute['values'][0]['name'] != (float)$row['waist_circumference_to']){
                                                array_push($alterData, array(
                                                    "colum_name"=>'WAIST_CIRCUMFERENCE_TO',
                                                    "value" => $row['waist_circumference_to'],
                                                    "gender" => $valueGender
                                                ));
                                                unset($rows[$key]['waist_circumference_to']);
                                            }else{unset($rows[$key]['waist_circumference_to']);}
                                        }
                                        if($attibute['id'] === 'PERSON_HEIGHT_FROM'){
                                            if( (float) $attibute['values'][0]['name'] != (float)$row['person_height_from']){
                                                array_push($alterData, array(
                                                    "colum_name"=>'PERSON_HEIGHT_FROM',
                                                    "value" => $row['person_height_from'],
                                                    "gender" => $valueGender
                                                ));
                                                unset($rows[$key]['person_height_from']);
                                            }else{unset($rows[$key]['person_height_from']);}
                                        }
                                        if($attibute['id'] === 'PERSON_HEIGHT_TO'){
                                            if( (float) $attibute['values'][0]['name'] != (float)$row['person_height_to']){
                                                array_push($alterData, array(
                                                    "colum_name"=>'PERSON_HEIGHT_TO',
                                                    "value" => $row['person_height_to'],
                                                    "gender" => $valueGender
                                                ));
                                                unset($rows[$key]['person_height_to']);
                                            }else{unset($rows[$key]['person_height_to']);}
                                        }
                                        if($attibute['id'] === 'HIP_CIRCUMFERENCE_FROM'){
                                            if( (float) $attibute['values'][0]['name'] != (float)$row['hip_circumference_from']){
                                                array_push($alterData, array(
                                                    "colum_name"=>'HIP_CIRCUMFERENCE_FROM',
                                                    "value" => $row['hip_circumference_from'],
                                                    "gender" => $valueGender
                                                ));
                                                unset($rows[$key]['hip_circumference_from']);
                                            }else{unset($rows[$key]['hip_circumference_from']);}
                                        }
                                        if($attibute['id'] === 'HIP_CIRCUMFERENCE_TO'){
                                            if( (float) $attibute['values'][0]['name'] != (float)$row['hip_circumference_to']){
                                                array_push($alterData, array(
                                                    "colum_name"=>'HIP_CIRCUMFERENCE_TO',
                                                    "value" => $row['hip_circumference_to'],
                                                    "gender" => $valueGender
                                                ));
                                                unset($rows[$key]['hip_circumference_to']);
                                            }else{unset($rows[$key]['hip_circumference_to']);}
                                        }
                                    }
                                }
                            }

                            if(isset($rows[$key]['chest_circumference_to']) AND $rows[$key]['chest_circumference_to'] AND $info['domain_id'] !== "MLB-SHORTS"){
                                array_push($alterData, array(
                                    "colum_name"=>'CHEST_CIRCUMFERENCE_TO',
                                    "value" => $row['chest_circumference_to'],
                                    "gender" => $valueGender
                                ));
                            }
                            if(isset($rows[$key]['waist_circumference_to']) AND $rows[$key]['waist_circumference_to']){
                                array_push($alterData, array(
                                    "colum_name"=>'WAIST_CIRCUMFERENCE_TO',
                                    "value" => $row['waist_circumference_to'],
                                    "gender" => $valueGender
                                ));
                            }
                            if(isset($rows[$key]['person_height_from']) AND $rows[$key]['person_height_from']){
                                array_push($alterData, array(
                                    "colum_name"=>'PERSON_HEIGHT_FROM',
                                    "value" => $row['person_height_from'],
                                    "gender" => $valueGender
                                ));
                            }
                            if(isset($rows[$key]['person_height_to']) AND $rows[$key]['person_height_to']){
                                array_push($alterData, array(
                                    "colum_name"=>'PERSON_HEIGHT_TO',
                                    "value" => $row['person_height_to'],
                                    "gender" => $valueGender
                                ));
                            }
                            if(isset($rows[$key]['hip_circumference_from']) AND $rows[$key]['hip_circumference_from']){
                                array_push($alterData, array(
                                    "colum_name"=>'HIP_CIRCUMFERENCE_FROM',
                                    "value" => $row['hip_circumference_from'],
                                    "gender" => $valueGender
                                ));
                            }
                            if(isset($rows[$key]['hip_circumference_to']) AND $rows[$key]['hip_circumference_to']){
                                array_push($alterData, array(
                                    "colum_name"=>'HIP_CIRCUMFERENCE_TO',
                                    "value" => $row['hip_circumference_to'],
                                    "gender" => $valueGender
                                ));
                            }
                        
                            //Atualiza informações da linha.
                            if($alterData)
                                $newList = $this->setAlterChats($row['id'],$selected,$alterData, substr($info['domain_id'],4 , 100));
                            }else{
                                array_push($addRows,array(
                                    "data" => $row,
                                ));
                            }
                        }
                }
            //Atualiza Novas linhas.
            if($addRows)
               $newList = $this->setAddChartsRow($addRows,$selected,$valueGender, substr($info['domain_id'],4 , 100));
        }

        if($newList){
            $this->request->post['rows'] = $this->listCharts($newList->rows, $rows);
            if(!$selected){
                $this->request->post['selected'] = $newList->id;
            }
        }

        $this->request->post['type'] = "SPECIFIC";

        if($info['boolDatabase'] != "false" AND $info['insert'] == 'false' AND $newList){
            $this->model_mercadolivre_measure_manufacturer->deleteMeasured(array("list" => $list['names'][0]['grid_id']));
        }

        if( $info['boolDatabase'] != "false"){
            if($newList){$result = $this->model_mercadolivre_measure_manufacturer->setCharts();};
        }else{
            $result = $this->model_mercadolivre_measure_manufacturer->setCharts();
        }
    }

    protected function listCharts($list, $rows){
        $line = [];
        foreach ($list as $key => $ml){

            array_push($line, array("id" => $ml->id));
                $line[$key] = array_merge($line[$key], $rows[$key]);
            foreach ($ml->attributes as $attrKey => $attr){

                if($attr->id === 'FILTRABLE_SIZE'){
                    $values = [];
                    foreach ($attr->values as $value) {
                        $values[] = $value->name;
                    };
                };

                if($attr->id == 'SIZE'){
                    $line[$key] = array_merge($line[$key] , array("size" => (string)(float) $attr->values[0]->name));
                }
                if($attr->id == 'FOOT_LENGTH'){
                    $line[$key] = array_merge($line[$key] , array("length" => (string)(float) $attr->values[0]->name));
                }
                if(strrpos($attr->id , 'US_SIZE') !== false){
                    $line[$key] = array_merge($line[$key] , array("us" => (string)(float) $attr->values[0]->name));
                }
                if(strrpos($attr->id , 'EU_SIZE') !== false){
                    $line[$key] =  array_merge($line[$key] , array("eu" => (string)(float) $attr->values[0]->name));
                }
                if($attr->id == 'UK_SIZE'){
                    $line[$key] = array_merge($line[$key] , array("uk" => (string)(float) $attr->values[0]->name));
                }
                //NEW
                if($attr->id == 'FILTRABLE_SIZE'){
                    $line[$key] = array_merge($line[$key] , array("filtrable_size" => (array) $values));
                }
                if($attr->id == 'CHEST_CIRCUMFERENCE_FROM'){
                    $line[$key] = array_merge($line[$key] , array("chest_circumference_from" => (string)(float) $attr->values[0]->name));
                }
                if($attr->id == 'CHEST_CIRCUMFERENCE_TO'){
                    $line[$key] = array_merge($line[$key] , array("chest_circumference_to" => (string)(float) $attr->values[0]->name));
                }
                if($attr->id == 'WAIST_CIRCUMFERENCE_FROM'){
                    $line[$key] = array_merge($line[$key] , array("waist_circumference_from" => (string)(float) $attr->values[0]->name));
                }
                if($attr->id == 'WAIST_CIRCUMFERENCE_TO'){
                    $line[$key] = array_merge($line[$key] , array("waist_circumference_to" => (string)(float) $attr->values[0]->name));
                }
                if($attr->id == 'PERSON_HEIGHT_FROM'){
                    $line[$key] = array_merge($line[$key] , array("person_height_from" => (string)(float) $attr->values[0]->name));
                }
                if($attr->id == 'PERSON_HEIGHT_TO'){
                    $line[$key] = array_merge($line[$key] , array("person_height_to" => (string)(float) $attr->values[0]->name));
                }
                if($attr->id == 'HIP_CIRCUMFERENCE_FROM'){
                    $line[$key] = array_merge($line[$key] , array("hip_circumference_from" => (string)(float) $attr->values[0]->name));
                }
                if($attr->id == 'HIP_CIRCUMFERENCE_TO'){
                    $line[$key] = array_merge($line[$key] , array("hip_circumference_to" => (string)(float) $attr->values[0]->name));
                }
            }
        }
        return $line;
    }

    public function delete(){
        $this->loadLanguage();
        $this->loadModel();

        $list = isset($this->request->post['list'])? $this->request->post['list'] : false;
        if($list){
            $result = $this->model_mercadolivre_measure_manufacturer->deleteMeasured($list);
        }else{
            $result = false;
        }

        $this->response->setOutputJson($result);
    }

    protected function actionUrls()
    {
        parent::actionUrls();
        $this->dataVue['actionSubCategory'] = $this->url->link("$this->referencePathFile/getSubCategory", "token=" . $this->session->data['token'] , "SSL");
        $this->dataVue['actionGetGender']   = $this->url->link("$this->referencePathFile/GetGender", "token=" . $this->session->data['token'] , "SSL");
        $this->dataVue['actionGetChart']    = $this->url->link("$this->referencePathFile/GetChart", "token=" . $this->session->data['token'] , "SSL");
        $this->dataVue['actionGetChartSql']    = $this->url->link("$this->referencePathFile/GetChartSql", "token=" . $this->session->data['token'] , "SSL");

    }

    public function filter(){
        $this->loadModel();

        $page = isset($this->request->post['page']) ? $this->request->post['page'] : 1;
        $filters = isset($this->request->post['filters']) ? $this->request->post['filters'] : [];

        $list = $this->model_mercadolivre_measure_manufacturer->getMeasured($filters,$page);
        $listTotal = $this->model_mercadolivre_measure_manufacturer->getMeasuredTotal($filters,$page);

        $renderPagination = parent::renderPagination($listTotal,$page);

        $info = array();

        foreach ($list as $item){
            $info[] = array(
                'measure_manufacturer_GRID_id'  => $item['measure_GRID_id'],
                'manufacturer_id'               => $item['manufacturer_id'],
                'GENDER'                        => $item['GENDER'],
                'SIZE_GRID_ID'                  => $item['SIZE_GRID_ID'],
                'manufacturer_description'      => $item['manufacturer_description'],
                'name'                          => $item['name'],
                'image'                         => $item['image'],
                'domain_id'                     => $item['domain_id'],
            );
        }
        if (isset($this->request->post['ajax']) && $this->request->post['ajax']){
            return $this->response->setOutputJson(['list' => $info, 'pagination' => $renderPagination , 'limit' => $this->config->get('config_admin_limit')]);
        }else{
            $this->dataVue['list'] = $info;
            $this->dataVue['pagination'] = $renderPagination;
            $this->dataVue['limit'] = (int) $this->config->get('config_admin_limit');
        }

    }

    protected function getCategoryMain(){

        $result = [];
        foreach($this->model_mercadolivre_mercadolivre->getMercadoCategory() as $value){
            $result[] = array(
                'id'  => $value['mercaId'],
                'name' => $value['name'],
            );
        }
        return $result;

    }

    protected function getManufacturer(){
        $result = [];
        foreach($this->model_catalog_manufacturer->getManufacturers(false) as $value){
            $result[] = array(
                'id'  => $value['manufacturer_id'],
                'name' => $value['name'],
            );
        }
        return $result;
    }

    //NEW
    public function getSubCategory(){
        $result = [];

        $id = $this->request->post['id'];
        $respCat = $this->mercadolivre->getCategory($id);

        if(count($respCat['categories'])) {
            foreach ($respCat['categories'] as $value) {
                $result[] = array(
                    'id' => $value['id'],
                    'name' => $value['name'],
                );
            }
            return $this->response->setOutputJson(array("$id" => $result));
        }else{

            $respDomain = $this->mercadolivre->getDomain($id);
            if($respDomain) {

                $respDomain = $respDomain->domain_id;
                $listCharts = $this->mercadolivre->getChats();
                $result = false;

                foreach ($listCharts->domains as $values) {
                    if ($values->domain_id == $respDomain) {
                        $result = true;
                        break;
                    }
                }

                if ($result) {
                    return $this->response->setOutputJson(array("domain" => $respDomain));
                } else {
                    return $this->response->setOutputJson(array("notFind" => true));
                }
            }else{
                return $this->response->setOutputJson(array("notFind" => true));
            }
        }
    }

    public function getGender(){

        $domain = $this->request->post['domain'];
        $result = [];

        $listCharts = $this->mercadolivre->getChats();
        foreach ($listCharts->domains as $values) {
            $result += array($values->domain_id => $this->mercadolivre->getChatsGender($values));
        }



        return $this->response->setOutputJson($result[$domain]);
    }

    public function GetChartSql(){
        $this->loadModel();
        $result = $this->model_mercadolivre_measure_manufacturer->getChartsSql();

        return $this->response->setOutputJson($result);
    }

    public function GetChart(){

        $this->loadModel();
        $data = $this->request->post['data'];
        $result = [];
        $listCharts = [];

        array_push($data, $this->model_catalog_manufacturer->getManufacturer($data['brand']));

        //Busca na API para que possa cadastrar
        if(!$listCharts AND $data['boolDatabase'] == 'false'){
            $listCharts = $this->mercadolivre->getBrandMercadoLivre($data);

            if(!$listCharts->charts){
                $listCharts = $this->mercadolivre->getBrandMercadoLivre($data, 'SPECIFIC');
            }

            if(!$listCharts->charts){
                $names[] = [];
                $result[] = [];
                $insert = true;
            }else{
                $insert = false;
            }

            foreach ($listCharts->charts as $value) {
                $names[] = array(
                    "id" => $value->id,
                    "name" => $value->names->MLB,
                    "type" => $value->type
                );

                $result[] = array(
                    $value->id => $value->rows,
                );

            }
            return $this->response->setOutputJson(array('names' => $names, 'rows' => $result,'insert' => $insert));
        }else{
            $listCharts = $this->model_mercadolivre_measure_manufacturer->getCharts($data);
            $gender = $listCharts[0]['GENDER'];
            $names[] = array(
                "id" => $listCharts[0]['SIZE_GRID_ID'],
                "name" => $listCharts[0]['manufacturer_description'],
                "type" =>  $listCharts[0]['type'],
                "grid_id" =>  $listCharts[0]['measure_GRID_id'],
            );

            if($listCharts[0]['domain_id'] === 'MLB-SNEAKERS'){
                foreach ($listCharts as $key => $value) {
                    $results = array(
                        array(  "id" => $value['SIZE_GRID_ROW_ID'],
                                "attributes" => array([
                                  "id" => "SIZE",
                                  "values" => array([
                                      "name" => $value['BR_SIZE']])
                                ],
                                [
                                    "id" => "BR_SIZE",
                                    "values" => array([
                                        "name" => $value['BR_SIZE']])
                                ],
                                [
                                    "id" => "FOOT_LENGTH",
                                    "values" => array([
                                        "name" => $value['FOOT_LENGTH']])
                                ])
                                )
                    );
    
                    if($value['US_SIZE']){
                        $results[0]['attributes'] = array_merge($results[0]['attributes'],
                            array([
                                "id" => "US_SIZE",
                                "values" => array([
                                    "name" => $value['US_SIZE']])])
                        );
                    }
    
                    if($value['EU_SIZE']){
                        $results[0]['attributes'] = array_merge($results[0]['attributes'],
                            array([
                                "id" => "EU_SIZE",
                                "values" => array([
                                    "name" => $value['EU_SIZE']])])
                        );
                    }
    
                    if($value['UK_SIZE']){
                        $results[0]['attributes'] = array_merge($results[0]['attributes'],
                            array([
                                "id" => "UK_SIZE",
                                "values" => array([
                                    "name" => $value['UK_SIZE']])])
                        );
                    }
    
                    if($value['productsize_id']){
                        $results[0]['attributes'] = array_merge($results[0]['attributes'],
                            array([
                                "id" => "productsize_id",
                                "values" => array([
                                    "name" => $value['productsize_id']])])
                        );
                    }
    
                    if(!isset($result[$value['SIZE_GRID_ID']])){
                        $result = array($value['SIZE_GRID_ID'] => []);
                    }
    
                    array_push($result[$value['SIZE_GRID_ID']], $results[0]);
                }
            }else{
                foreach ($listCharts as $key => $value) {
                    if($listCharts[0]['domain_id'] !== 'MLB-SHORTS'){
                        $results = array(
                            array(  "id" => $value['SIZE_GRID_ROW_ID'],
                                    "attributes" => array([
                                      "id" => "FILTRABLE_SIZE",
                                      "values" => array([
                                          "name" => $value['filtrable_size']])
                                    ],
                                    [
                                        "id" => "CHEST_CIRCUMFERENCE_FROM",
                                        "values" => array([
                                            "name" => $value['chest_circumference_from']])
                                    ],
                                    [
                                        "id" => "WAIST_CIRCUMFERENCE_FROM",
                                        "values" => array([
                                            "name" => $value['waist_circumference_from']])
                                    ])
                            )
                        );
                    }else{
                        $results = array(
                            array(  "id" => $value['SIZE_GRID_ROW_ID'],
                                    "attributes" => array([
                                      "id" => "FILTRABLE_SIZE",
                                      "values" => array([
                                          "name" => $value['filtrable_size']])
                                    ],
                                    [
                                        "id" => "WAIST_CIRCUMFERENCE_FROM",
                                        "values" => array([
                                            "name" => $value['waist_circumference_from']])
                                    ])
                            )
                        );
                    }
                    
                    if($value['chest_circumference_to'] && $listCharts[0]['domain_id'] !== 'MLB-SHORTS'){
                        $results[0]['attributes'] = array_merge($results[0]['attributes'],
                            array([
                                "id" => "CHEST_CIRCUMFERENCE_TO",
                                "values" => array([
                                    "name" => $value['chest_circumference_to']])])
                        );
                    }
    
                    if($value['waist_circumference_to']){
                        $results[0]['attributes'] = array_merge($results[0]['attributes'],
                            array([
                                "id" => "WAIST_CIRCUMFERENCE_TO",
                                "values" => array([
                                    "name" => $value['waist_circumference_to']])])
                        );
                    }
    
                    if($value['person_height_from']){
                        $results[0]['attributes'] = array_merge($results[0]['attributes'],
                            array([
                                "id" => "PERSON_HEIGHT_FROM",
                                "values" => array([
                                    "name" => $value['person_height_from']])])
                        );
                    }

                    if($value['person_height_to']){
                        $results[0]['attributes'] = array_merge($results[0]['attributes'],
                            array([
                                "id" => "PERSON_HEIGHT_TO",
                                "values" => array([
                                    "name" => $value['person_height_to']])])
                        );
                    }

                    if($value['hip_circumference_from']){
                        $results[0]['attributes'] = array_merge($results[0]['attributes'],
                            array([
                                "id" => "HIP_CIRCUMFERENCE_FROM",
                                "values" => array([
                                    "name" => $value['hip_circumference_from']])])
                        );
                    }
  
                    if($value['hip_circumference_to']){
                        $results[0]['attributes'] = array_merge($results[0]['attributes'],
                            array([
                                "id" => "HIP_CIRCUMFERENCE_TO",
                                "values" => array([
                                    "name" => $value['hip_circumference_to']])])
                        );
                    }
    
                    if($value['productsize_id']){
                        $results[0]['attributes'] = array_merge($results[0]['attributes'],
                            array([
                                "id" => "productsize_id",
                                "values" => array([
                                    "name" => $value['productsize_id']])])
                        );
                    }
    
                    if(!isset($result[$value['SIZE_GRID_ID']])){
                        $result = array($value['SIZE_GRID_ID'] => []);
                    }
    
                    array_push($result[$value['SIZE_GRID_ID']], $results[0]);
    
                }
            }
                     
            return $this->response->setOutputJson(array('names' => $names, 'rows' => $result, "read" => true, 'gender' =>  $gender));
        }
    }

    protected function getSystemSize(){
        $this->loadModel();

        $result = [];

        $listCharts = $this->model_mercadolivre_measure_manufacturer->getSystemSize();
        foreach ($listCharts as $value) {
            $result[] = array(
                "id" =>     $value['productsize_id'],
                "name" =>   $value['description']
            );
        }
        return $result;
    }

    protected function setAlterChats($ROW_ID,$CHART_ID,$alterdata,$domain){
        return $this->mercadolivre->setAlterChats($ROW_ID,$CHART_ID,$alterdata,$domain);
    }
    protected function setAddChartsRow($addRows,$selected,$valueGender,$domain){
        return $this->mercadolivre->setAddChartsRow($addRows,$selected,$valueGender,$domain);
    }
}
?>