<?php

use system\entity\filter\baseFilter;

class ControllerModuleGaleriapageBulkSetting extends Controller
{

    public function index()
    {
        $this->load->language('module/galeriapage');
        $this->load->language('module/galeriapage-extra');
        $this->load->dmodel('marketplace/mktproduto');
        $this->load->dmodel('marketplace/mktprodutogaleriapage');
        $this->load->model('catalog/product');
        $this->load->dmodel('galeriapage/gpproduto');
        $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;
            $product_id = is_array($data['product_id']) ? $data['product_id'] : explode(',', $data['product_id']);

            foreach ($product_id as $product_key_id) {
                try {
                    $this->dmodel_galeriapage_gpproduto->updateProductGpInfo($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);

                    if(!isset($this->session->data['warning_mkt_global'])) {
                        $this->session->data['success'] = $this->language->get('save_success');
                    } else {
                        $this->session->data['warning_mkt_global'] = $this->session->data['warning_mkt_global'];
                    }

                } 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['text_custom_title'] = $this->language->get('text_custom_title');
        $this->data['button_save'] = $this->language->get('button_save');
        $this->data['button_cancel'] = $this->language->get('button_cancel');
        $this->data['text_table_price'] = $this->language->get('text_table_price');
        $this->data['text_department'] = $this->language->get('text_department');
        $this->data['text_category'] = $this->language->get('text_category');
        $this->data['text_subcategory'] = $this->language->get('text_subcategory');

        $this->data['token'] = $this->session->data['token'];
        $this->data['action'] = $this->url->link('module/galeriapage/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_mktprodutogaleriapage->getProductGrid($this->data['products'][0]['product_grid_id']);
                $mkt_data = $this->dmodel_marketplace_mktproduto->getMarketplacesUniqueProductsFromGrid($this->data['products'][0]['product_grid_id'], $type_marketplace);
                $custom_title_enabled = empty($mkt_data);
            } else {
                $type_products = Type_ProdutoMkt::Tp_MktProd_Normal;
                $product_info = $this->dmodel_marketplace_mktprodutogaleriapage->getProduct($this->data['products'][0]['product_id']);
                $custom_title_enabled = empty($product_info['product_marketId']);
            }

            $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'] : (isset($product_info['gp_custom_title']) ? $product_info['gp_custom_title'] : $product_info['name']));
        $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['gp_department_id'] = isset($product_info['gp_department_id']) ? $product_info['gp_department_id'] : '';
        $this->data['gp_category_id'] = isset($product_info['gp_category_id']) ? $product_info['gp_category_id'] : '';
        $this->data['gp_subcategory_id'] = isset($product_info['gp_subcategory_id']) ? $product_info['gp_subcategory_id'] : '';

        $this->data['custom_title_enabled'] = !$custom_title_enabled ? 'disabled' : '';

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

        $this->loadCategories();

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


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

    public function category()
    {
        $galeriapage = new GaleriaPage($this->registry);
        $cats = $galeriapage->getCategoriesByDeptId($this->request->get['department_id']);
        echo json_encode($cats);
    }

    public function subCategory()
    {
        $galeriapage = new GaleriaPage($this->registry);
        $subcats = $galeriapage->getSubCategoriesByCatId($this->request->get['category_id']);
        echo json_encode($subcats);
    }

    public function loadCategories()
    {
        $galeriapage = new GaleriaPage($this->registry);
        $depts = $galeriapage->getAllDepartments();

        $this->data['department_array'] = array();
        $this->data['category_array'] = array();
        $this->data['subcategory_array'] = array();

        foreach ($depts->data as $key => $value) {
            $this->data['department_array'][] = array(
                'label' => $value->name,
                'value' => $value->id,
                'active' => ftr_geral::isSelected($value->id, $this->data['gp_department_id'])
            );
        }

        if (empty($this->data['gp_department_id'])) {
            $emptyOption = array('label' => "Selecione um departamento", 'value' => 0, 'active' => true);
            array_unshift($this->data['department_array'], $emptyOption);
        } else {
            $cats = $galeriapage->getCategoriesByDeptId($this->data['gp_department_id']);

            foreach ($cats->data as $key => $value) {
                $this->data['category_array'][] = array(
                    'label' => $value->name,
                    'value' => $value->id,
                    'active' => ftr_geral::isSelected($value->id, $this->data['gp_category_id'])
                );
            }

            if (empty($this->data['gp_category_id'])) {
                $emptyOption = array('label' => "Selecione um categoria", 'value' => 0, 'active' => true);
                array_unshift($this->data['category_array'], $emptyOption);
            } else {
                $subcats = $galeriapage->getSubCategoriesByCatId($this->data['gp_category_id']);

                foreach ($subcats->data as $key => $value) {
                    $this->data['subcategory_array'][] = array(
                        'label' => $value->name,
                        'value' => $value->id,
                        'active' => ftr_geral::isSelected($value->id, $this->data['gp_subcategory_id'])
                    );
                }

                if (empty($this->data['gp_subcategory_id'])) {
                    $emptyOption = array('label' => "Selecione um sub-categoria", 'value' => 0, 'active' => true);
                    array_unshift($this->data['subcategory_array'], $emptyOption);
                }
            }
        }

        $this->data['category_enabled'] = empty($this->data['gp_department_id']) ? "disabled" : "";
        $this->data['subcategory_enabled'] = empty($this->data['gp_category_id']) ? "disabled" : "";
    }


    public function validate()
    {
        $json = array();
        $this->load->type('tipogaleriapage');

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

}