<?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);
        $errors = [];

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

        $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);

            }
        }

        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 = [];
            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,
                    ));
                }
            }
            //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 == '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));
                }
            }
        }
        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);
            $names[] = array(
                "id" => $listCharts[0]['SIZE_GRID_ID'],
                "name" => $listCharts[0]['manufacturer_description'],
                "type" =>  $listCharts[0]['type'],
                "grid_id" =>  $listCharts[0]['measure_GRID_id'],
            );


            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]);

            }
            return $this->response->setOutputJson(array('names' => $names, 'rows' => $result, "read" => true));
        }
    }

    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);
    }
}
?>