<?php

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

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

        $language = $this->load->language('module/shopee');
        $this->load->model('shopee/shopee');
        $this->load->model('setting/setting');
        $this->load->dmodel('shopee/shopeepedido');
        $this->load->dmodel('checkout/order');

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

        $this->data = array_merge($this->data, $language);

        $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/shopee/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/shopee/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'];

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

        foreach (Type_ShopeeOrderApiStatus::getEnumList() as $key => $value) {
            $status_id = $this->dmodel_shopee_shopeepedido->getShopeeStatus($key);
            if (is_null($status_id)){
                break;
            }
            $status = $this->dmodel_checkout_order->getOrderStatus($status_id);
            $shopee_status[$key] = $status['descricao'];
        }
        $this->data['shopee_status'] = $shopee_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'));
            $filter_date_start = $this->request->get['filter_date_start'];
        } else {
            $filter_date_start = null;
        }

        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'));
            $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/shopee/searchorder'));
    }


    public function searchorderfilter()
    {
        $this->load->type('tipocomum');
        $this->load->helper('ftr_geral');

        $json = array();
        $filter_date_start = '';
        $filter_date_end = '';
        $filter_status = null;
        $filter_id = '';

        if (isset($this->request->get['filter_id']) && ($this->request->get['filter_id'] != '')) {
            $filter_id = $this->request->get['filter_id'];
        } 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 selecionada';
            }

            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 selecionada';
            }

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

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

        if (!$json) {

            $data = array(
                'filter_date_start' => $filter_date_start,
                'filter_date_end' => $filter_date_end,
                'filter_id' => $filter_id,
                'filter_status' => $filter_status,
                'offset' => $offset,
                'limit' => $this->config->get('config_admin_limit'),
//                'limit' => 4, //teste
                'sort' => 'date_desc'
            );

            $results = $this->shopee->getSearchOrderShopee($data);

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

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

                $this->load->model('shopee/shopee');
                $this->load->dmodel('shopee/shopeepedido');
                $this->load->dmodel('marketplace/mktpedido');

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

                    $index = $result->order_sn;

                    $searchorderstotal[$index] = 0;

                    $mktOrderData = $this->shopee->getOrderMarketplace($result->order_sn);

                    if (!$mktOrderData){
                        continue;
                    }

                    if (isset($mktOrderData->item_list) && $mktOrderData->item_list) {
                        foreach ($mktOrderData->item_list 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_name),
                                'order_item_quantity' => $order_item->model_quantity_purchased,
                                'order_item_unit_price' => $this->currency->format($order_item->model_discounted_price)
                            );
                        }
                    }

                    $resultShopeeOrder = $this->dmodel_marketplace_mktpedido->getMktOrder($result->order_sn, Type_MarketPlace::Tp_Shopee);

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

                    $searchorders[$index][] = array(
                        'order_id' => $result->order_sn,
                        'order_status' => Type_ShopeeOrderApiStatus::getNickFromValue($mktOrderData->order_status),
                        'order_date_created' => date('d/m/Y h:i:s', $mktOrderData->create_time),
                        'order_href' => ($resultShopeeOrder) ? $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $resultShopeeOrder['order_id'], 'SSL') : false
                    );

                }

                if ($results['paging-total'] > 0) {
                    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['orders'] = $searchorders;
                    $json['hasMore'] = $results['more'];
                    $json['offset'] = $offset + $results['paging-total'];
                }
            } else {
                $json['result_error'] = $results['error'];
            }
        }

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

    //Essa funcao é usada na tela de consulta de pedidos da Shopee (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 Shopee não informado!';
        }

        if (!$json) {
            $this->load->model('shopee/shopee');
            $this->load->dmodel('shopee/shopeepedido');
            $this->load->dmodel('marketplace/mktpedido');

            foreach ($filter_order_ids as $filter_order_id) {
                try {
                    $orderMkt = $this->marketplace->getOrder(Type_MarketPlace::Tp_Shopee, $filter_order_id);
                    $this->downloadOrder($orderMkt);

                    $order = $this->dmodel_marketplace_mktpedido->getMktOrder($filter_order_id, Type_MarketPlace::Tp_Shopee);
                    $results = (isset($order['order_id']) && $order['order_id']) ? $this->model_shopee_shopee->getShopeeOrderIds($order['order_id']) : false;
                    if ($results) {
                        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);
    }

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

        $this->dmodel_shopee_shopeepedido->saveMarketplaceLog();

        $this->db->startTransaction();

        try {
            if ($status <> Type_ShopeeOrderApiStatus::Tp_Unpaid){
                $data = ['status' => Type_ShopeeOrderApiStatus::Tp_Unpaid];
                $order_id = $this->dmodel_shopee_shopeepedido->insertShopeeOrder($order->getMktId(), $data, true);
                $statusHistory = [];

                switch ($status) {
                    case Type_ShopeeOrderApiStatus::Tp_Processed:
                        $statusHistory[] = Type_ShopeeOrderApiStatus::Tp_ReadyToShip;
                        break;
                    case Type_ShopeeOrderApiStatus::Tp_Shipped:
                        $statusHistory[] = Type_ShopeeOrderApiStatus::Tp_ReadyToShip;
                        $statusHistory[] = Type_ShopeeOrderApiStatus::Tp_Processed;
                        break;
                    case Type_ShopeeOrderApiStatus::Tp_ToConfirmReceive:
                        $statusHistory[] = Type_ShopeeOrderApiStatus::Tp_ReadyToShip;
                        $statusHistory[] = Type_ShopeeOrderApiStatus::Tp_Processed;
                        $statusHistory[] = Type_ShopeeOrderApiStatus::Tp_Shipped;
                        break;
                    case Type_ShopeeOrderApiStatus::Tp_Completed:
                        $statusHistory[] = Type_ShopeeOrderApiStatus::Tp_ReadyToShip;
                        $statusHistory[] = Type_ShopeeOrderApiStatus::Tp_Processed;
                        $statusHistory[] = Type_ShopeeOrderApiStatus::Tp_Shipped;
                        $statusHistory[] = Type_ShopeeOrderApiStatus::Tp_ToConfirmReceive;
                        break;
                }

                $this->createStatusHistory($order_id, $statusHistory);

                $this->dmodel_shopee_shopeepedido->updateOrderStatusShopee($order_id, $status, $status);

                // adicionar rastreamento
                $tracking = $this->shopee->getTrackingNumber($order->getMktId());
                if ($tracking && !empty($tracking->tracking_number)) {
                    $this->dmodel_shopee_shopeepedido->addShopeeTracking($order, $order_id, $tracking);
                }

            } else {
                $this->dmodel_shopee_shopeepedido->insertShopeeOrder($order->getMktId(), [], true);
            }

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

    protected function createStatusHistory($order_id, $status_history)
    {
        if ($status_history){
            foreach ($status_history as $status){
                $statusOld = ['status' => $status];
                $this->dmodel_shopee_shopeepedido->updateOrderStatusShopee($order_id, $statusOld, $statusOld);
            }
        }
    }

}