<?php

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

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

        $this->load->language('module/skyhub');
        $this->load->model('setting/setting');
        $this->load->model('skyhub/skyhub');
        $this->load->dmodel('skyhub/skypedido');
        $this->load->dmodel('checkout/order');

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

        $this->data['heading_title'] = $this->language->get('heading_title_search');
        $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['column_status'] = $this->language->get('column_status');
        $this->data['column_channel'] = $this->language->get('column_channel');
        $this->data['button_filter_selected'] = $this->language->get('button_filter_selected');

        $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/skyhub/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/skyhub/searchorder', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL'),
            'separator' => ' :: '
        );

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

        $skyhub_status = array();

        $skyhub_status['0'] = 'Todos';

        foreach (TypeSkyHubOrder_Status::getEnumList() as $key => $value) {
            $status_id = $this->dmodel_skyhub_skypedido->getSkyStatus($value);
            $status = $this->dmodel_checkout_order->getOrderStatus($status_id);
            $skyhub_status[$value] = $status['descricao'];
        }

        // remove o tipo waiting_payment porque filtrara junto com book_product
        unset($skyhub_status[TypeSkyHubOrder_Status::getNickFromValue(TypeSkyHubOrder_Status::Tp_waiting_payment)]);
        $this->data['skyhub_status'] = $skyhub_status;

        $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_id'])) {
            $filter_id = $this->request->get['filter_id'];
        } else {
            $filter_id = null;
        }

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

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


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

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

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

    public function searchorderfilter()
    {

        $this->load->type('tipocomum');
        $this->load->helper('ftr_geral');
        $this->load->dmodel('skyhub/skypedido');
        $this->load->dmodel('checkout/order');

        $json = array();

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

        if (isset($this->request->get['filter_date_start']) && ($this->request->get['filter_date_start'] != '')) {
            $filter_date_start = $this->request->get['filter_date_start'];
        } else if (!$filter_id) {
            $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 = $this->request->get['filter_date_end'];
        } else if (!$filter_id) {
            $json['error']['filter_date_end'] = 'Data final não especificada.';
        }

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

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

        if (!$json) {

            $data = array();

            $data = array(
                'filter_id' => $filter_id,
                'filter_date_start' => $filter_date_start ?? false,
                'filter_date_end' => $filter_date_end ?? false,
                'filter_status' => ($filter_status == TypeSkyHubOrder_Status::getNickFromValue(TypeSkyHubOrder_Status::Tp_book_product)
                    ? array($filter_status, TypeSkyHubOrder_Status::getNickFromValue(TypeSkyHubOrder_Status::Tp_waiting_payment))
                    : array($filter_status)),
                'page' => $page,
                'per_page' => $this->config->get('config_admin_limit')
            );

            $results = array();

            $skyhub = new SkyHubUtils($this->registry);
            $results = $skyhub->getOrders($data);

            if ($results) {

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

                $this->load->model('skyhub/skyhub');

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

                    $index = $result['code'];

                    $searchorderstotal[$index] = 0;

                    foreach ($result['items'] as $key => $order_item) {
                        $searchordersitems[$index][] = array(
                            'order_item_id' => $order_item['id'],
                            'order_item_title' => preg_replace('/[^A-Za-z0-9-]/', ' ', $order_item['name']),
                            'order_item_quantity' => $order_item['qty'],
                            'order_item_unit_price' => number_format($order_item['special_price'] ?? $order_item['original_price'], 2, ',', '')
                        );
                    }

                    $resultOrder = $this->model_skyhub_skyhub->getSkyhubOrder($result['code']);

                    $mkt_tipo = $resultOrder ? $resultOrder['mkt_tipo'] : Type_MarketplaceInt::getConstFromNickValue($result['channel']);

                    if (file_exists('view/image/marketplace/' . $mkt_tipo . '.jpg')) {
                        $img = 'view/image/marketplace/' . $mkt_tipo . '.jpg';
                    } else {
                        $img = '';
                    }

                    $searchorderstotal[$index] += $result['total_ordered'];

                    $status = $this->dmodel_skyhub_skypedido->getSkyStatus($result['status']['code']);
                    $status = $this->dmodel_checkout_order->getOrderStatus($status);
                    $status = $status['descricao'];

                    $searchorders[$index][] = array(
                        'order_id' => $result['code'],
                        'order_buyer_name' => $result['customer']['name'],
                        'order_status' => $status,
                        'order_date_created' => ftr_geral::getDataZoneFormat($result['placed_at']),
                        'order_href' => ($resultOrder) ? $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $resultOrder['order_id'], 'SSL') : false,
                        'order_img' => $img
                    );

                }

                $pagination = new PaginationJson();
                $pagination->total = $results['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;
            }
        }

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

    protected function addSkyhubTracking($order, $order_id)
    {
        $this->load->dmodel('tracking/tracking');

        if (strtolower($order->getParam('shipments_carrier')) == Type_Tracking::Tp_Correios) {
            $dataTracking = array(
                'order_id' => $order_id,
                'shipping_code' => $order->getShippingName(),
                'tracking_code' => $order->getParam('shipments_code'),
                'tracking_complete' => Type_Status::Tp_Desabilitado
            );

            $this->dmodel_tracking_tracking->addTrackingEcommerce($dataTracking);
        }

        $dataOrder = array(
            'order_id' => $order_id,
            'tracking_code' => $order->getParam('shipments_code')
        );

        $this->dmodel_tracking_tracking->addTrackingOrderShipping($dataOrder);
    }

    protected function downloadSkyhubOrder($order)
    {
        // Aqui será feita uma tremenda gambiarra para baixar o pedido salvando um histórico dos status
        $status = $order->getParam('status');
        $status_type = $order->getParam('status_type');
        $approved_date = $order->getParam('approved_date') ?? '';
        $shipped_date = $order->getParam('shipped_date') ?? '';
        $hasInvoice = $order->getParam('hasInvoice') ?? '';

        $this->dmodel_skyhub_skypedido->saveMarketplaceLog();

        $this->db->startTransaction();

        try {
            if ($status_type <> TypeSkyHubOrder_Type::Tp_new) {
                $data = array('status' => TypeSkyHubOrder_Status::getNickFromConstValue(TypeSkyHubOrder_Status::Tp_book_product),
                    'status_type' => TypeSkyHubOrder_Type::Tp_new);
                $order_id = $this->dmodel_skyhub_skypedido->addOrderSkyhub($order, $data, true);

                switch ($status_type) {
                    case TypeSkyHubOrder_Type::Tp_invoiced:
                        // Pra estar no status invoiced, tem que ter passado obrigatoriamente pelo aprovado
                        $this->dmodel_skyhub_skypedido->updateOrderStatusSkyHub($order_id, TypeSkyHubOrder_Status::getNickFromConstValue(TypeSkyHubOrder_Status::Tp_payment_received),
                            TypeSkyHubOrder_Type::Tp_approved);
                        break;
                    case TypeSkyHubOrder_Type::Tp_shipped:
                    case TypeSkyHubOrder_Type::Tp_delivered:
                        // Verifica se foi aprovado pelo approved_date
                        if ($approved_date) {
                            $this->dmodel_skyhub_skypedido->updateOrderStatusSkyHub($order_id, TypeSkyHubOrder_Status::getNickFromConstValue(TypeSkyHubOrder_Status::Tp_payment_received),
                                TypeSkyHubOrder_Type::Tp_approved);
                        }
                        // Verifica se passou por faturado pela chave invoices
                        if ($hasInvoice) {
                            $this->dmodel_skyhub_skypedido->updateOrderStatusSkyHub($order_id, TypeSkyHubOrder_Status::getNickFromConstValue(TypeSkyHubOrder_Status::Tp_order_invoiced),
                                TypeSkyHubOrder_Type::Tp_invoiced);
                        }

                        if ($status_type == TypeSkyHubOrder_Type::Tp_delivered) {
                            // Verifica se passou por enviado pelo shipped_date
                            if ($shipped_date) {
                                $this->dmodel_skyhub_skypedido->updateOrderStatusSkyHub($order_id, TypeSkyHubOrder_Status::getNickFromConstValue(TypeSkyHubOrder_Status::Tp_order_shipped),
                                    TypeSkyHubOrder_Type::Tp_shipped);
                            }
                        }
                        break;
                }

                $this->dmodel_skyhub_skypedido->updateOrderStatusSkyHub($order_id, $status, $status_type);

                // adicionar rastreamento
                if ($order->hasParam('shipments_code')) {
                    $this->addSkyhubTracking($order, $order_id);
                }

            } else {
                $this->dmodel_skyhub_skypedido->addOrderSkyHub($order, array(), true);
            }

            $this->db->commit();
        } catch (Exception $e) {
            $this->db->rollback();
            throw new Exception($e->getMessage());
        }
    }

    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 skyhub não informado!';
        }

        if (!$json) {
            $this->load->model('skyhub/skyhub');
            $this->load->dmodel('skyhub/skypedido');
            $this->load->dmodel('marketplace/marketplace');
            $skyhub = new SkyHubUtils($this->registry);

            foreach ($filter_order_ids as $filter_order_id) {
                try {
                    $orderJson = $skyhub->getOrderWs($filter_order_id);
                    $order = $skyhub->orderJsonToObject($orderJson);

                    $this->downloadSkyhubOrder($order);

                    $orderMktID = $order->getMktId();
                    $orderID = $this->dmodel_marketplace_marketplace->getMktPlaceOrderId(Type_MarketPlace::Tp_SkyHub, array('mkt_order_id' => $orderMktID));
                    $orderID = $orderID['order_id'];
                    $skyhub->deleteOrderQueue($order->getMktId());

                    $json['order_href'][$order->getMktId()] = str_replace('&amp;', '&', $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $orderID, '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);
    }


}