<?php

use system\entity\filter\baseFilter;

class ControllerModuleSkyhubBulkSetting extends Controller
{

    public function index()
    {
        $this->load->language('module/skyhub');
        $this->load->language('module/skyhub-extra');
        $this->load->dmodel('marketplace/mktproduto');
        $this->load->dmodel('marketplace/mktprodutoskyhub');
        $this->load->model('catalog/product');
        $this->load->dmodel('skyhub/skyproduto');
        $this->load->dmodel('marketplace/mktprice');

        $this->load->helper('ftr_geral');
        $arrayIgnore = array('route', 'pids', 'unique', 'type', 'redirect');
        $url = ftr_geral::getUrlLink($arrayIgnore, $this->request->get);

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

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->request->post['product_id']) {
            $data = $this->request->post;
            if ($data['custom_title']) {
                $data['custom_title'] = html_entity_decode($data['custom_title']);
            }
            $product_id = is_array($data['product_id']) ? $data['product_id'] : explode(',', $data['product_id']);

            foreach ($product_id as $product_key_id) {
                try {
                    $this->dmodel_skyhub_skyproduto->updateProductSkyData($data, $product_key_id, $this->request->post['type_product'][$product_key_id]);
                    $this->dmodel_marketplace_mktproduto->synchronizeProduct($product_key_id, $data['type_product'][$product_key_id],
                        $type_marketplace, true, false, $data);
                    $this->session->data['success'] = $this->language->get('save_success');
                } catch (Exception $e) {
                    $this->session->data['error_warning'] = $this->language->get('save_error');
                    $this->session->data['mkt_error'][$product_key_id] = $e->getMessage();
                    $original_exception = $e->getPrevious();
                    if (isset($original_exception)) {
                        $this->session->data['mkt_error_original'][$product_key_id] = $original_exception->getMessage();
                    }
                }
            }

            $redirect = (isset($data['redirect']) && ($data['redirect'] != '')) ? $data['redirect'] : $this->url->link('catalog/product', $url, 'SSL');

            $this->redirect($redirect);
        }

        $this->data['entry_custom_title'] = $this->language->get('entry_custom_title');
        $this->data['button_save'] = $this->language->get('button_save');
        $this->data['button_cancel'] = $this->language->get('button_cancel');
        $this->data['entry_product_origem'] = $this->language->get('entry_product_origem');
        $this->data['entry_product_warranty'] = $this->language->get('entry_product_warranty');
        $this->data['entry_parcelamento_maximo'] = $this->language->get('entry_parcelamento_maximo');
        $this->data['entry_table_price'] = $this->language->get('entry_table_price');


        $this->data['token'] = $this->session->data['token'];
        $this->data['action'] = $this->url->link('module/skyhub/bulksetting', $url, 'SSL');

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

        if ((isset($this->request->get['pids']) && $this->request->get['pids'])) {
            $auxProdutos = false;
            $auxGrade = false;

            $type_products = explode(",", $this->request->get['type_products']);

            $ids_produtos = explode(",", $this->request->get['pids']);
            foreach ($ids_produtos as $key => $id_prod) {
                if ($type_products[$key] == Type_ProdutoMkt::Tp_MktProd_Grade) {
                    $auxGrade[] = $id_prod;
                } else {
                    $auxProdutos[] = $id_prod;
                }
            }

            $dataProd = array(
                'ids_produto' => $auxProdutos,
                'ids_grade' => $auxGrade,
            );

            $this->data['products'] = $this->model_catalog_product->getProducts($dataProd);
        } else {
            $this->data['products'] = array();
        }

        $product_key_id = false;
        if (isset($this->data['products'])) {
            if ($this->data['products'][0]['IsGrid']) {
                $type_products = Type_ProdutoMkt::Tp_MktProd_Grade;
                $product_info = $this->dmodel_marketplace_mktprodutoskyhub->getProductGrid($this->data['products'][0]['product_grid_id']);
            } else {
                $type_products = Type_ProdutoMkt::Tp_MktProd_Normal;
                $product_info = $this->dmodel_marketplace_mktprodutoskyhub->getProduct($this->data['products'][0]['product_id']);
            }

            $product_key_id = $this->data['products'][0]['product_key_id'];
            $this->data['type_product'] = $type_products;
        } else {
            $product_info = Array();
        }

        $this->data['marketplace_price_id'] = (isset($product_info['marketplace_price_id']) && !empty($product_info['marketplace_price_id'])) ? $product_info['marketplace_price_id'] : '';

        $this->data['mkt_custom_title'] = isset($product_info['mkt_custom_title']) ? $product_info['mkt_custom_title'] : '';

        $this->data['product_marketId'] = isset($product_info['product_marketId']) ? $product_info['product_marketId'] : false;

        $this->data['product_id'] = isset($this->data['products']) ? $product_key_id : 0;

        $this->data['skyhuborigem'] = isset($product_info['origem_produto']) ? $product_info['origem_produto'] : '';

        $this->data['skyhubwarranty'] = isset($product_info['garantia']) ? $product_info['garantia'] : '';

        $this->data['skyhubparcelamento'] = isset($product_info['parcelamento_maximo']) ? $product_info['parcelamento_maximo'] : '';

        $this->data['skyhuborigem_arrays'] = array();
        foreach (TypeSkyHubOrigem::getEnumList() as $key => $value) {
            $this->data['skyhuborigem_arrays'][] = array(
                'label' => $value,
                'value' => $key,
                'active' => ftr_geral::isSelected($key, $this->data['skyhuborigem'])
            );
        }

        $baseFilter = new BaseFilter();
        $baseFilter->setWhere('tipo_integracao', Type_OperationsComparation::Equals, Type_MarketPlace::Tp_SkyHub);
        $this->data['marketplace_prices'] = $this->dmodel_marketplace_mktprice->findBy($baseFilter);


        $this->template = 'module/skyhub/bulk_setting.twig';

        $this->children = array();
        $this->response->setOutputJson(['html' => $this->render('module/skyhub/bulk_setting')]);
    }


    public function validate()
    {

        $json = array();
        $this->load->type('tipomercadolivre');

        if (isset($this->request->post['skyhubwarranty']) && ($this->request->post['skyhubwarranty'] > 12)) {
            $json['error']['skyhubwarranty'] = 'A quantidade máxima de meses é 12';
        }


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

    }

}