<?php

class ControllerModuleMercadolivreError extends Controller
{

    private $error = array();

    public function index()
    {
        $this->load->helper('ftr_geral');
        $this->load->dmodel('mercadolivre/meliproduto');
        $this->load->model('mercadolivre/error');
        $this->load->model('setting/setting');

        $language = $this->load->language('module/mercadolivre');;
        $this->data = array_merge($this->data, $language);

        $this->document->setTitle($language['text_heading_title_error']);
        $this->document->setTitle($language['text_heading_title_error']);

        $this->data['token'] = $this->session->data['token'];
        $this->data['type'] = $this->request->get['type'];

        $this->document->addScript(array(
            'view/javascript/page.products.mercadolivre.js',
            '../catalog/view/theme/vista/js/accordion-futura.js',
            'view/javascript/page.products.js',
            'view/public/js/validate.js'
        ));

        $this->data['breadcrumbs'] = array();

        $this->data['breadcrumbs'][] = array(
            'text' => $language['text_home'],
            'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
            'separator' => false
        );

        $this->data['breadcrumbs'][] = array(
            'text' => $language['heading_title'],
            'href' => $this->url->link('module/mercadolivre/error', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL'),
            'separator' => ' :: '
        );

        $this->data['breadcrumbs'][] = array(
            'text' => $language['text_heading_title_error'],
            'href' => $this->url->link('module/mercadolivre/error', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL'),
            'separator' => ' :: '
        );

        $this->data['url'] = array(
            'cancel' => $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL'),
            'clear_filter' => $this->url->link('module/mercadolivre/error', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL'),
            'retorno' => $this->url->link('module/mercadolivre/error', 'token=' . $this->session->data['token'] . $this->getLinkUrl(), 'SSL')
        );

        if (isset($this->error['warning'])) {
            $this->data['error_warning'] = $this->error['warning'];
        } else {
            $this->data['error_warning'] = '';
        }

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }

        if (isset($this->request->get['filter_product_ml_id'])) {
            $filter_product_ml_id = $this->request->get['filter_product_ml_id'];
        } else {
            $filter_product_ml_id = null;
        }

        if (isset($this->request->get['filter_model'])) {
            $filter_model = $this->request->get['filter_model'];
            $filter_content_model = $this->request->get['filter_content_model'];
        } else {
            $filter_model = null;
            $filter_content_model = null;
        }

        if (isset($this->request->get['filter_name'])) {
            $filter_name = $this->request->get['filter_name'];
        } else {
            $filter_name = null;
        }

        $this->data['type_marketplace'] = Type_MarketPlace::Tp_Mercadolivre;


        $data = array(
            'filter_product_ml_id' => $filter_product_ml_id,
            'filter_model' => $filter_model,
            'filter_content_model' => $filter_content_model,
            'filter_name' => $filter_name,
            'start' => ($page - 1) * $this->config->get('config_admin_limit'),
            'limit' => $this->config->get('config_admin_limit'),
            'filter_error_marketplace' => true,
            'type_marketplace' => $this->data['type_marketplace']
        );

        $results = $this->model_mercadolivre_error->getErrors($data);
        $error_total = $this->model_mercadolivre_error->getErrorsTotal($data);

        $contentTotal = Type_FilterContent::getEnumList();
        foreach ($contentTotal as $key => $value) {
            $this->data['content_model'][] = array(
                'content_model_id' => $key,
                'content_model_name' => $value,
                'content_model_status' => isset($this->request->get['filter_content_model']) ? ftr_geral::isSelected($key, $this->request->get['filter_content_model']) : false
            );
        }

        $this->data['errors'] = array();

        foreach ($results as $key => $result) {

            $type = ftr_geral::isIsset($this->config->get('config_product_code')) ? $this->config->get('config_product_code') : Type_ListCodProduct::Tp_CodReferencia;
            switch ($type) {
                case Type_ListCodProduct::Tp_CodReferencia:
                    $model = $result['model'];
                    break;
                case Type_ListCodProduct::Tp_CodProdEcommerce:
                    $model = $result['product_id'];
                    break;
                case Type_ListCodProduct::Tp_CodProdFuturaServer:
                    $model = $result['id_futura'];
                    break;
                case Type_ListCodProduct::Tp_CodBarras:
                    $model = $result['codigo_barra'];
                    break;
                default:
                    $model = $result['model'];
            }

            if (isset($this->session->data['mkt_error_grade'][$result['product_key_id']])) {
                $mkt_error_grade = $this->session->data['mkt_error_grade'][$result['product_key_id']];
                unset($this->session->data['mkt_error_grade'][$result['product_key_id']]);
            } else {
                $mkt_error_grade = false;
            }

            if (isset($this->session->data['mkt_error'][$result['product_key_id']])) {
                $ml_error = $this->session->data['mkt_error'][$result['product_key_id']];
                unset($this->session->data['mkt_error'][$result['product_key_id']]);
            } else {
                $ml_error = false;
            }

            if (isset($this->session->data['ml_warning'][$result['product_key_id']])) {
                $ml_warning = $this->session->data['ml_warning'][$result['product_key_id']];
                unset($this->session->data['ml_warning'][$result['product_key_id']]);
            } else {
                $ml_warning = false;
            }

            if ($result['IsGrid']) {
                $type_product = Type_ProdutoMkt::Tp_MktProd_Grade;
            } else {
                $type_product = Type_ProdutoMkt::Tp_MktProd_Normal;
            }

            $paramKey = '&product_id=' . $result['product_key_id'] . '&type_product=' . $type_product . '&type_marketplace=' . Type_MarketPlace::Tp_Mercadolivre;
            $mktError = array(
                'finalizar' => $this->url->link('marketplace/Marketplacecalls/desvincular', 'token=' . $this->session->data['token'] . $paramKey, 'SSL'),
                'desvincular' => $this->url->link('marketplace/Marketplacecalls/desynchronize', 'token=' . $this->session->data['token'] . $paramKey, 'SSL')
            );

            $this->data['errors'][] = array(
                'product_id' => $result['product_id'],
                'type_product' => $type_product,
                'product_key_id' => $result['product_key_id'],
                'cod_mercadolivre' => $result['product_mercaId'],
                'cod_ecommerce' => $model,
                'help' => (array_key_exists($result['cod_error'], Type_MercadoLivreLinkHelp::getEnumList())) ? Type_MercadoLivreLinkHelp::getNickFromValue($result['cod_error']) . '#' . $result['cod_error'] : false,
                'name' => $result['name'],
                'msg_error' => $result['mensagem_error'],
                'cod_error' => $result['cod_error'],
                'ml_error' => $ml_error,
                'ml_warning' => $ml_warning,
                'mkt_error_grade' => $mkt_error_grade,
                'mktError' => $mktError,
                'selected' => isset($this->request->post['selected']) && in_array($result['product_id'], $this->request->post['selected'])
            );

        }

        $url = $this->getLinkUrl(['page']);

        $pagination = new Pagination();
        $pagination->total = $error_total;
        $pagination->page = $page;
        $pagination->limit = $this->config->get('config_admin_limit');
        $pagination->text = $this->language->get('text_pagination');
        $pagination->url = $this->url->link('module/mercadolivre/error', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

        $this->data['pagination'] = $pagination->render();

        $url = $this->getLinkUrl(['page', 'type']);
        $this->data['filter_count'] = count(explode('&', $url)) - 1;
        $this->data['filter_product_ml_id'] = $filter_product_ml_id;
        $this->data['filter_model'] = $filter_model;
        $this->data['filter_content_model'] = $filter_content_model;
        $this->data['filter_name'] = $filter_name;


        $this->children = array(
            'common/header',
            'common/footer'
        );

        $this->response->setOutput($this->render('module/mercadolivre/error'));

    }


    public function getLinkUrl($remove = array())
    {
        $url = '';

        foreach ($remove as $key => $value) {
            unset($this->request->get[$value]);
        }

        if (isset($this->request->get['page'])) {
            $url .= '&page=' . $this->request->get['page'];
        }

        if (isset($this->request->get['type'])) {
            $url .= '&type=' . $this->request->get['type'];
        }

        if (isset($this->request->get['filter_product_ml_id'])) {
            $url .= '&filter_product_ml_id=' . $this->request->get['filter_product_ml_id'];
        }

        if (isset($this->request->get['filter_model'])) {
            $url .= '&filter_model=' . $this->request->get['filter_model'];
        }

        if (isset($this->request->get['filter_content_model'])) {
            $url .= '&filter_content_model=' . $this->request->get['filter_content_model'];
        }

        if (isset($this->request->get['filter_name'])) {
            $url .= '&filter_name=' . $this->request->get['filter_name'];
        }

        return $url;
    }


    public function grade()
    {

        if ($this->request->get['product_grid_id']) {
            $product_grid_id = $this->request->get['product_grid_id'];
        } else {
            $this->error['error_grade'] = 'Id da grade não encontrado, contate a <a href="http://www.futurasistemas.com.br/pag/entre-em-contato/" target="_blank">Futura Sistemas.</a>';
        }

        if ($this->request->get['urlretorno']) {
            $urlretorno = str_replace('&amp;', '&', urldecode($this->request->get['urlretorno']));
        } else {
            $urlretorno = '';
        }

        $this->load->type('tipomarketplace');
        $this->load->model('catalog/product');

        $results = $this->model_catalog_product->getProductMercadolivreGrade($product_grid_id);

        if ($results) {

            $this->data['anuncios'] = array();

            foreach ($results as $key => $result) {
                $this->data['product_name'] = $result['name'];

                $url = array(
                    'token' => $this->session->data['token'],
                    'product_id' => $result['product_key_id'],
                    'action' => Type_AcaoAnuncio::Tp_AcAnReplace,
                    'type_marketplace' => Type_MarketPlace::Tp_Mercadolivre,
                    'product_grid_id' => $product_grid_id,
                    'urlretorno' => $urlretorno
                );

                $this->data['anuncios'][] = array(
                    'marketid' => $result['marketId'],
                    'status' => $result['status'],
                    'url' => $result['url'],
                    'product_key_id' => $result['product_key_id'],
                    'disabled' => ($result['status'] == Type_MercadoLivreItemStatus::Tp_Closed) ? true : false,
                    'link' => $this->url->link('marketplace/Marketplacecalls/synchronizederrorgrid', http_build_query($url, '', '&'), 'SSL')
                );
            }

        }

        $url = array(
            'token' => $this->session->data['token'],
            'product_id' => $product_grid_id,
            'action' => Type_AcaoAnuncio::Tp_AcAnNew,
            'type_marketplace' => Type_MarketPlace::Tp_Mercadolivre,
            'urlretorno' => $urlretorno
        );

        $this->data['link'] = $this->url->link('marketplace/Marketplacecalls/synchronizederrorgrid', http_build_query($url, '', '&'), 'SSL');

        if (isset($this->error['error_grade'])) {
            $this->data['error_grade'] = $this->error['error_grade'];
        } else {
            $this->data['error_grade'] = false;
        }

        $this->template = 'module/mercadolivre/error_grade.twig';

        $this->response->setOutput($this->render());

    }


}