<?php

class ControllerModuleMercadolivreSearchOrder extends Controller
{
    private $error = array();

    public function index()
    {
        $this->load->helper('ftr_geral');

        $this->load->language('module/mercadolivre');
        $this->load->model('mercadolivre/mercadolivre');
        $this->load->model('setting/setting');

        $this->document->addScript(array(
            'view/javascript/mercadolivre-searchorder.js',
        ));

        $this->data['heading_title'] = $this->language->get('heading_title_search');
        $this->data['text_module'] = $this->language->get('text_module');
        $this->data['text_setting'] = $this->language->get('text_setting');
        $this->data['tab_order_all'] = $this->language->get('tab_order_all');

        $this->data['button_back'] = $this->language->get('button_back');
        $this->data['button_filter'] = $this->language->get('button_filter');

        $this->data['column_date_start'] = $this->language->get('column_date_start');
        $this->data['column_date_end'] = $this->language->get('column_date_end');
        $this->data['column_name_apelido'] = $this->language->get('column_name_apelido');
        $this->data['button_filter_selected'] = $this->language->get('button_filter_selected');

        $this->data['cancel'] = $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL');

        $this->document->setTitle($this->language->get('heading_title_search'));

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

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

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

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

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

        $url = '';

        if (isset($this->request->get['filter_date_start'])) {
            $url .= '&filter_date_start=' . urlencode(html_entity_decode($this->request->get['filter_date_start'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($this->request->get['filter_date_end'])) {
            $url .= '&filter_date_end=' . urlencode(html_entity_decode($this->request->get['filter_date_end'], ENT_QUOTES, 'UTF-8'));
        }

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

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

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


        $this->data['filter_date_start'] = $filter_date_start;
        $this->data['filter_date_end'] = $filter_date_end;
        $this->data['filter_name'] = $filter_name;

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

        $this->data['back'] = $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL');

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

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

    }


    public function searchorderfilter()
    {

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

        $json = array();
        $filter_date_start = '';
        $filter_date_end = '';
        $filter_name = '';

        if (isset($this->request->get['filter_name']) && ($this->request->get['filter_name'] != '')) {
            $filter_name = $this->request->get['filter_name'];
        } else {
            if (isset($this->request->get['filter_date_start']) && ($this->request->get['filter_date_start'] != '')) {
                $filter_date_start = ftr_geral::formatDate($this->request->get['filter_date_start'], 'en');
            } else {
                $json['error']['filter_date_start'] = 'Data inicial não especificada.';
            }

            if (isset($this->request->get['filter_date_end']) && ($this->request->get['filter_date_end'] != '')) {
                $filter_date_end = ftr_geral::formatDate($this->request->get['filter_date_end'], 'en');
            } else {
                $json['error']['filter_date_end'] = 'Data final não especificada.';
            }
        }

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

        if (!$json) {

            $data = array(
                'filter_date_start' => $filter_date_start,
                'filter_date_end' => $filter_date_end,
                'filter_name' => $filter_name,
                'offset' => ($page - 1) * $this->config->get('config_admin_limit'),
                'limit' => Type_DefaultValues::Tp_MlOrderSearchLimit,
                'order.status' => 'paid',
                'sort' => 'date_desc'
            );

            $results = $this->mercadolivre->getSearchOrderMercadoLivre($data);

            if (isset($results['results'])) {

                $searchorders = array();
                $searchordersitems = array();
                $searchorderstotal = array();

                $this->load->model('mercadolivre/mercadolivre');
                $this->load->dmodel('mercadolivre/melipedido');

                foreach ($results['results'] as $key => $result) {

                    $index = isset($result->shipping->id) ? $result->shipping->id : $result->id;

                    $searchorderstotal[$index] = 0;

                    foreach ($result->order_items as $key => $order_item) {
                        $searchordersitems[$index][] = array(
                            'order_item_id' => $order_item->item->id,
                            'order_item_title' => preg_replace('/[^A-Za-z0-9-]/', ' ', $order_item->item->title),
                            'order_item_listing_type_id' => Type_MercadoLivremercaListType::getNickFromValue($order_item->listing_type_id, true),
                            'order_item_quantity' => $order_item->quantity,
                            'order_item_unit_price' => $this->currency->format($order_item->unit_price)
                        );
                    }

                    $resultMlOrder = $this->model_mercadolivre_mercadolivre->getMlOrder($result->id);

                    $searchorderstotal[$index] += $result->total_amount;

                    $searchorders[$index][] = array(
                        'order_id' => $result->id,
                        'order_status' => Type_MercadoLivreStatus::getNickFromValue($result->status),
                        'order_date_created' => ftr_geral::getDataZoneFormat($result->date_created),
                        'order_href' => ($resultMlOrder) ? $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $resultMlOrder['order_id'], 'SSL') : false
                    );

                }

                if ($results['paging-total'] > 0) {

                    $pagination = new PaginationJson();
                    $pagination->total = $results['paging-total'];
                    $pagination->page = $page;
                    $pagination->limit = $this->config->get('config_admin_limit');
                    $pagination->text = $this->language->get('text_pagination');
                    $pagination->classjs = 'js-search-order-filter';

                    foreach ($searchorders as $key => $searchorder) {
                        $searchorders[$key] = array(
                            'order_data' => $searchorders[$key],
                            'order_items' => json_encode($searchordersitems[$key]),
                            'order_total' => $this->currency->format($searchorderstotal[$key])
                        );
                    }

                    $json['pagination'] = $pagination->render();
                    $json['orders'] = $searchorders;

                }

            } else {
                $json['result_error'] = $results['error'];
            }
        }

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

//Essa funcao é usada apenas na tela de consulta de Pedidos do mercado livre (onde sincroniza pedido a pedido manualmente)
    public function searchorderdownload()
    {

        $json = array();

        if (isset($this->request->get['filter_order_id']) && ($this->request->get['filter_order_id'] != '')) {
            $filter_order_ids = is_array($this->request->get['filter_order_id']) ? $this->request->get['filter_order_id'] : explode(',', $this->request->get['filter_order_id']);
        } else {
            $json['warning'] = 'Id do pedido no mercado livre não informado!';
        }


        if (!$json) {
            $this->load->model('mercadolivre/mercadolivre');
            $this->load->dmodel('mercadolivre/melipedido');
            foreach ($filter_order_ids as $filter_order_id) {

                try {
                    //na SearchProcessAPIOrder ele chama a funcao de sincronizar o pedido selecionado manualmente passando um parametro para
                    //ignorar a data configurada nas cfg do Mercado Livre pois é baixa manual
                    $this->dmodel_mercadolivre_melipedido->SearchProcessAPIOrder($filter_order_id);
                    $order = $this->model_mercadolivre_mercadolivre->getMlOrder($filter_order_id);

                    $results = $this->model_mercadolivre_mercadolivre->getMercaOrderIds($order['order_id']);
                    foreach ($results as $key => $result) {
                        $json['order_href'][$result['mktOrderId']] = str_replace('&amp;', '&', $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $order['order_id'], 'SSL'));
                    }
                    $json['success'] = "Pedido baixado com sucesso!";
                } catch (Exception $e) {
                    $json['warning'] = 'Ocorreu um erro ao baixar o(s) pedido(s) verifique as configurações e tente novamente!';
                    $json['warning_item'][$filter_order_id] = $e->getMessage();
                }

            }

        }

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


}