<?php
$loader = $this->registry->get('load');
$loader->controller('marketplace/mktjobs');

class ControllerShopeeShopeejobs extends ControllerMarketplaceMktJobs
{

    public function __construct($registry)
    {
        parent::__construct($registry);

    }

    public function atualizarPedidos()
    {
        $this->ftrgeralregistry->permissaoAcessoUrl($this->dmodel_setting_task->getTaskByType(Type_TaskUrl::TP_TaskShopeePedido));

        if ($this->config->get('shopee_status')) {
            $data = array(
                'date_last_acting' => $this->db->dataAtual(),
                'type' => Type_TaskUrl::TP_TaskShopeePedido
            );
            $this->dmodel_setting_task->editDateTaskByType($data);

            $minutos = Type_ExecTimeTask::Tp_ExecTime_3min / 60;
            $tempoLimite = (new DateTime($this->db->dataAtual()))->add(new DateInterval('PT' . $minutos . 'M'));

            $this->load->dmodel('shopee/shopeepedido');
            $this->dmodel_shopee_shopeepedido->processOrder($tempoLimite);
        } else {
            throw new Exception('Configuração de verificação de pedidos desabilitada!');
        }
    }

    public function atualizarProdutos()
    {
        if ($this->config->get('shopee_status') && (isset($this->request->get['update']))) {
            $this->load->dmodel('marketplace/mktproduto');
            $this->load->dmodel('marketplace/mktprodutoshopee');
            $this->load->dmodel('setting/task');
            $this->load->type('tipocomum');

            ini_set('memory_limit', '32M');

            if (isset($this->request->get['update'])) {
                switch ($this->request->get['update']) {
                    case 'estoque':
                        $this->ftrgeralregistry->permissaoAcessoUrl($this->dmodel_setting_task->getTaskByType(Type_TaskUrl::TP_TaskShopeeEstoque));
                        $result = $this->dmodel_setting_task->getTaskByType(['type' => Type_TaskUrl::TP_TaskShopeeEstoque]);

                        $dataTask = array(
                            'date_last_acting' => $this->db->dataAtual(),
                            'type' => Type_TaskUrl::TP_TaskShopeeEstoque
                        );
                        $this->dmodel_setting_task->editDateTaskByType($dataTask);

                        $minutos = Type_ExecTimeTask::Tp_ExecTime_3min / 60;
                        $tempoLimite = (new DateTime($this->db->dataAtual()))->add(new DateInterval('PT' . $minutos . 'M'));

                        $data = array(
                            'date_estoque' => true,
                        );

                        $results = $this->dmodel_marketplace_mktprodutoshopee->getMktProdutos($data);

                        if (count($results) > 0) {
                            $shopeeproducts = array_chunk($results, 10);

                            foreach ($shopeeproducts as $key => $values) {
                                $dataAtt = $this->db->dataAtual();
                                $productReturnList = array();
                                $productType = array();
                                foreach ($values as $key => $value) {
                                    try {
                                        $productReturn = $this->dmodel_marketplace_mktproduto->synchronizeProductEstoquePreco($value['product_key_id'], $value['marketId'], Type_MarketPlace::Tp_Shopee, $value['tipo_produto'], false, true);

                                        if ($productReturn) {
                                            $productReturnList[$value['product_key_id']][Type_MarketPlace::Tp_Shopee] = $productReturn;
                                            $productType[$value['product_key_id']][Type_MarketPlace::Tp_Shopee] = $value['tipo_produto'];
                                        }

                                    }  catch (ExceptionErrorShow $e) {
                                        //erros de exibição não é para serem salvos na tabela de oc_marketplace_product
                                    }   catch (Exception $e) {
                                        $this->dmodel_marketplace_mktproduto->setError($e->getMessage(), $value['product_key_id'], Type_MarketPlace::Tp_Shopee, $value['tipo_produto']);
                                    }
                                }
                                
                                foreach ($productReturnList as $product_id => $return) {
                                    $dataUpdate = [
                                        'marketplace_price_id' => (int)$return[Type_MarketPlace::Tp_Shopee]->getMarketplacePriceId(),
                                        'marketplaceprice_config_md5' => $return[Type_MarketPlace::Tp_Shopee]->getMarketplacepriceConfigMd5(),
                                        'date_att_price' => $dataAtt,
                                    ];

                                    $this->dmodel_marketplace_mktproduto->saveProductMarketPlaceFromProd($return[Type_MarketPlace::Tp_Shopee], $product_id, $productType[$product_id][Type_MarketPlace::Tp_Shopee],
                                        $dataAtt, null, $dataUpdate);
                                }

                                if (($tempoLimite) && (new DateTime($this->db->dataAtual()) > $tempoLimite)) {
                                    break;
                                }
                            }
                        }
                        break;
                    case 'produto':
                        $this->ftrgeralregistry->permissaoAcessoUrl($this->dmodel_setting_task->getTaskByType(Type_TaskUrl::TP_TaskShopeeProduto));
                        $result = $this->dmodel_setting_task->getTaskByType(['type' => Type_TaskUrl::TP_TaskShopeeProduto]);

                        $dataTask = array(
                            'date_last_acting' => $this->db->dataAtual(),
                            'type' => Type_TaskUrl::TP_TaskShopeeProduto
                        );
                        $this->dmodel_setting_task->editDateTaskByType($dataTask);

                        $minutos = Type_ExecTimeTask::Tp_ExecTime_3min / 60;
                        $tempoLimite = (new DateTime($this->db->dataAtual()))->add(new DateInterval('PT' . $minutos . 'M'));

                        $config_md5 = $this->config->get('shopee_configs_md5');
                        $config_md5_mktfield = 'marketplace_config_md5';

                        $data = array(
                            'date_produto' => true,
                            'config_md5' => $config_md5,
                            'config_md5_mktfield' => $config_md5_mktfield,
                            'link_type' => Type_MarketplaceLink::Tp_Total,
                        );

                        $dataUpdate = array($config_md5_mktfield => $config_md5);

                        $results = $this->dmodel_marketplace_mktprodutoshopee->getMktProdutos($data);
                        if (count($results) > 0) {
                            $products = array_chunk($results, 10);
                            foreach ($products as $key => $values) {
                                $dataAtt = $this->db->dataAtual();
                                $productReturnList = array();
                                $productType = array();
                                foreach ($values as $key => $value) {
                                    try {
                                        $productReturn = $this->dmodel_marketplace_mktproduto->synchronizeProduct($value['product_key_id'], $value['tipo_produto'], Type_MarketPlace::Tp_Shopee, false, true);

                                        $productReturnList[$value['product_key_id']][Type_MarketPlace::Tp_Shopee] = $productReturn;
                                        $productType[$value['product_key_id']][Type_MarketPlace::Tp_Shopee] = $value['tipo_produto'];
                                    } catch (Exception $e) {
                                        $saveInfos[Type_MarketPlace::Tp_Shopee] = $this->marketplace->getProduto(Type_MarketPlace::Tp_Shopee, $value['marketId']);
                                        $this->dmodel_marketplace_mktproduto->UpdateProductMarketPlace($value['product_key_id'], null, Type_MarketPlace::Tp_Shopee, $value['tipo_produto']);
                                        $this->dmodel_marketplace_mktproduto->setError($e->getMessage(), $value['product_key_id'], Type_MarketPlace::Tp_Shopee, $value['tipo_produto']);
                                    }
                                }
                                foreach ($productReturnList as $product_id => $return) {
                                    $dataUpdate = array_merge($dataUpdate, [
                                        'marketplace_price_id' => (int)$return[Type_MarketPlace::Tp_Shopee]->getMarketplacePriceId(),
                                        'marketplaceprice_config_md5' => $return[Type_MarketPlace::Tp_Shopee]->getMarketplacepriceConfigMd5()
                                    ]);

                                    $this->dmodel_marketplace_mktproduto->saveProductMarketPlaceFromProd($return[Type_MarketPlace::Tp_Shopee], $product_id, $productType[$product_id][Type_MarketPlace::Tp_Shopee],
                                        null, $dataAtt, $dataUpdate);
                                }

                                if (($tempoLimite) && (new DateTime($this->db->dataAtual()) > $tempoLimite)) {
                                    break;
                                }
                            }
                        }
                        break;
                }
            }

        } else {
            throw new Exception('Configuração de atualização de produtos da Shopee desabilitada!');
        }
    }

}