<?php
class ControllerModuleFeatured extends Controller
{

    private function loadLanguage()
    {
        $language = $this->load->language('module/featured');
        $this->data = array_merge($this->data, $language);
    }

    private function breadcrumbs()
    {
        $token = $this->session->data['token'];
        $type = $this->request->get['type'];

        $this->data['breadcrumbs'] = [
            [
                'text' => $this->language->get('text_home'),
                'href' => $this->url->link('common/home', 'token=' . $token, 'SSL'),
            ],
            [
                'text' => $this->language->get('text_module'),
                'href' => $this->url->linkAnchor('extension/module', 'token=' . $token, 'tab-info=' . $type, 'SSL'),
            ],
            [
                'text' => $this->language->get('heading_title'),
                'href' => $this->url->link('module/featured', 'token=' . $token . '&type=' . $type, 'SSL'),
            ]
        ];
    }

    public function index()
    {
        $this->loadLanguage();
        $this->breadcrumbs();

        $this->document->addScript('admin/public/js/module/featured.js');
        $this->document->setTitle($this->language->get('heading_title'));

        $this->load->type('tipocomum');
        $this->load->model('setting/setting');
        $this->load->model('catalog/product');
        $this->load->dmodel('design/layout');
        $this->load->dmodel('tool/image');

        // Remove as opções de layout que não são usadas nos módulos de lista de produtos
        $this->data['layouts'] = $this->dmodel_design_layout->getLayouts([
            'notarray' => Type_NotListaProdutos::getEnumList()
        ]);

        $this->data['Type_ModulePosition'] = Type_ModulePosition::getRemoveArray([
            Type_ModulePosition::Tp_ColumnRight
        ], true);

        $this->data['Type_Status'] = Type_Status::getEnumList();
        $this->data['Type_DsimDnao'] = Type_DsimDnao::getEnumList();
        $this->data['Type_DefaultValues'] = Type_DefaultValues::getEnumList();
        $this->data['token'] = $this->session->data['token'];

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

        $configurations = [];
        $oldConfigurations = $this->model_setting_setting->getSetting('featured');
        // Retrocompatibilidade
        if (isset($oldConfigurations['featured_title'])) {
            unset($oldConfigurations['product']);
            unset($oldConfigurations['featured_titlefutura']);
            $oldConfigurations['featured_product'] = explode(',', $oldConfigurations['featured_product']);
            $configurations[] = $oldConfigurations;
        } elseif (isset($oldConfigurations['featured_module'])) {
            $configurations = $oldConfigurations['featured_module'];
        }

        $products = [];
        if ($configurations) {
            foreach ($configurations as $configurationKey => $configurationValue) {

                $modules = isset($configurationValue['featured_module']) ? $configurationValue['featured_module'] : [];
                $configurations[$configurationKey]['featured_module'] = [];
                foreach ($modules as $moduleKey => $moduleValue) {
                    $configurations[$configurationKey]['featured_module'][] = $moduleValue;
                }

                if (!isset($configurationValue['featured_product'])) {
                    $configurations[$configurationKey]['featured_product'] = [];
                    break;
                }

                $productsId = $configurationValue['featured_product'];
                unset($configurations[$configurationKey]['featured_product']);

                foreach ($productsId as $productIdKey => $productIdValue) {
                    $productInfo = $this->model_catalog_product->getProduct($productIdValue);
                    if ($productInfo) {
                        $thumbImage = $productInfo['image'] && file_exists(DIR_IMAGE . $productInfo['image'])
                            ? $productInfo['image']
                            : 'no_image.jpg';

                        $thumb = $this->dmodel_tool_image->resize(
                            $thumbImage,
                            Type_MiniatureMedium::Tp_width,
                            Type_MiniatureMedium::Tp_height
                        );

                        $configurations[$configurationKey]['featured_product'][] = [
                            'product_id' => $productInfo['product_id'],
                            'name' => trim($productInfo['name']),
                            'image' => $productInfo['image'],
                            'model' => $productInfo['model'],
                            'price' => $productInfo['price'],
                            'thumb' => $thumb,
                        ];
                    }
                }
            }
        }

        $url_action = $this->url->link(
            'module/featured/save',
            'token=' . $token . '&type=' . $type,
            'SSL'
        );

        $url_back = $this->url->linkAnchor(
            'extension/module',
            'token=' . $token,
            'tab-info=' . $type,
            'SSL'
        );

        $this->data['data'] = [
            'configurations' => $configurations,
            'products' => $products,
            'action' => str_replace('&amp;', '&', $url_action),
            'back' => str_replace('&amp;', '&', $url_back),
        ];

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

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

    public function save()
    {
        $this->loadLanguage();

        $response = [];

        if (!$this->user->hasPermission('modify', 'module/featured')) {
            $response['warning'] = $this->language->get('error_permission');
            return $this->response->setOutputJson($response);
        }

        $validate = $this->validate();
        if ($validate) {
            $response['errors'] = $validate;
            return $this->response->setOutputJson($response);
        }

        $this->load->model('setting/setting');
        $this->model_setting_setting->editSetting('featured', $this->request->post);
        $response['success'] = $this->language->get('text_success');

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

    private function validate()
    {
        if (!isset($this->request->post['featured_module'])) {
            return;
        }

        $request = $this->request->post['featured_module'];

        $this->load->type('tipocomum');
        $this->load->model('setting/setting');
        $this->load->dmodel('design/layout');
        $layouts = $this->dmodel_design_layout->getLayouts([
            'notarray' => Type_NotListaProdutos::getEnumList()
        ]);

        $errors = [];

        foreach ($request as $key => $value) {
            $featuredTitleError = $this->validate->execute([
                'featured_module[' . $key . '][featured_title]' => [
                    'value' => $value['featured_title'],
                    'validates' => ['isEmpty'],
                ],
            ]);

            if ($featuredTitleError) {
                $errors = array_merge($errors, $featuredTitleError);
            }


            if (!empty($value['featured_module'])) {
                $featuredModule = $value['featured_module'];

                $allRegisteredIdLayouts = array_map(function ($module) {
                    if ($module['status'] == Type_Status::Tp_Habilitado && $module['position'] != Type_ModulePosition::Tp_AppMobile) {
                        return $module['layout_id'];
                    }
                }, $featuredModule);

                $allRegisteredPosition = array_map(function ($module) {
                    if ($module['status'] == Type_Status::Tp_Habilitado) {
                        return $module['position'];
                    }
                }, $featuredModule);

                foreach ($featuredModule as $moduleKey => $moduleValue) {
                    $featuredModuleErrors = $this->validate->execute([
                        'featured_module[' . $key . '][featured_module][' . $moduleKey . '][position]' => [
                            'value' => $moduleValue['position'],
                            'validates' => ['isEmpty'],
                        ],
                        'featured_module[' . $key . '][featured_module][' . $moduleKey . '][entry_type]' => [
                            'value' => $moduleValue['entry_type'],
                            'validates' => [
                                'isEmpty',
                                [
                                    'method' => 'isYesOrNo',
                                    'type' => 'Type_DsimDnao',
                                ]
                            ],
                        ],
                        'featured_module[' . $key . '][featured_module][' . $moduleKey . '][layout_id]' => [
                            'value' => $moduleValue['layout_id'],
                            'validates' => ['isEmpty'],
                        ],
                        'featured_module[' . $key . '][featured_module][' . $moduleKey . '][status]' => [
                            'value' => $moduleValue['status'],
                            'validates' => ['isEmpty', 'isEnabledOrDisabled'],
                        ],
                        'featured_module[' . $key . '][featured_module][' . $moduleKey . '][sort_order]' => [
                            'value' => $moduleValue['sort_order'],
                            'validates' => ['isEmpty'],
                        ],
                    ]);

                    if ($featuredModuleErrors) {
                        $errors = array_merge($errors, $featuredModuleErrors);
                    }

                    $layoutsIsValid = false;
                    foreach ($layouts as $layoutKey => $layoutValue) {
                        if ($moduleValue['layout_id'] == $layoutValue['layout_id']) {
                            $layoutsIsValid = true;
                        }
                    }
                    if (!$layoutsIsValid) {
                        $errors['featured_module[' . $key . '][featured_module][' . $moduleKey . '][layout_id]'][] = 'Layout inválido';
                    }

                    $findKeyRegisteredIdLayout = [];
                    foreach ($allRegisteredIdLayouts as $registeredIdLayoutKey => $registeredIdLayoutValue) {
                        if ($registeredIdLayoutValue == $moduleValue['layout_id']) {
                            $findKeyRegisteredIdLayout[] = $registeredIdLayoutValue;
                        }
                    }

                    if ($moduleValue['status'] == Type_Status::Tp_Habilitado && count($findKeyRegisteredIdLayout) > 1) {
                        $errors['featured_module[' . $key . '][featured_module][' . $moduleKey . '][layout_id]'][] =
                            'Você não pode habilitar o módulo mais de uma vez no mesmo layout!';
                    }

                    if ($moduleValue['entry_type'] == Type_DsimDnao::Tp_Sim) {
                        $featuredModuleLimitError = $this->validate->execute([
                            'featured_module[' . $key . '][featured_module][' . $moduleKey . '][limit]' => [
                                'value' => $moduleValue['limit'],
                                'validates' => ['isEmpty', 'isIntegerNumber'],
                            ]
                        ]);

                        if ($featuredModuleLimitError) {
                            $errors = array_merge($errors, $featuredModuleLimitError);
                        }

                        $positionIsTopOrBottom = in_array($moduleValue['position'], [
                            Type_ModulePosition::Tp_ContentTop,
                            Type_ModulePosition::Tp_ContentBottom
                        ]);
                        if ($positionIsTopOrBottom && ($moduleValue['limit'] > Type_DefaultValues::Tp_LimitModules99)) {
                            $errors['featured_module[' . $key . '][featured_module][' . $moduleKey . '][limit]'][] =
                                'O limite deve ser menor que 99';
                        }

                        $positionIsLeftOrRight = in_array($moduleValue['position'], [
                            Type_ModulePosition::Tp_ColumnLeft,
                            Type_ModulePosition::Tp_ColumnRight
                        ]);
                        if ($positionIsLeftOrRight || $moduleValue['position'] == Type_ModulePosition::Tp_AppMobile) {
                            if ($moduleValue['limit'] > Type_DefaultValues::Tp_LimitModules24) {
                                $errors['featured_module[' . $key . '][featured_module][' . $moduleKey . '][limit]'][] =
                                    sprintf($this->language->get('error_limit'), Type_DefaultValues::Tp_LimitModules24);
                            }
                        }
                    }
                }
            }

        }

        return $errors;
    }
}
