<?php

loadController('base/module');

class ControllerModuleBanners extends ControllerBaseModule
{

    protected $referencePathFile = 'module/banners';

    private $post = [];

    protected function loadLanguage()
    {
        parent::loadLanguage();
        $this->dataVue['language'] = array_merge($this->language->getData(), $this->load->language('module/banners'));
    }

    protected function loadScripts()
    {
        parent::loadScript();
    }

    protected function loadModel()
    {
        $this->load->dmodel('design/layout');
        $this->load->model('design/banner');
        $this->load->dmodel('tool/image');
        $this->load->model('setting/analyze');
        $this->load->model('catalog/category');

        parent::loadModel();
    }

    public function mapImages($banners)
    {
        foreach ($banners as $key => $banner) {
            $images = [];
            $banner_images = $this->model_design_banner->getBannerImages($banner['banner_id']);
            foreach ($banner_images as $banner_image) {
                $exist_dir_banner_image = file_exists(DIR_IMAGE . $banner_image['image']);

                $image = ($banner_image['image'] && $exist_dir_banner_image)
                    ? $banner_image['image']
                    : 'no_image.jpg';

                $thumb = $this->dmodel_tool_image->resize(
                    $image,
                    Type_MiniatureSmall::Tp_width,
                    Type_MiniatureSmall::Tp_height
                );

                $images[] = [
                    'banner_image_description' => [
                        1 => [
                            'title' => $banner_image['banner_image_description'][1]['title']
                        ]
                    ],
                    'link' => $banner_image['link'],
                    'image' => $image,
                    'thumb' => $thumb,
                ];
            }

            $banners[$key]['banner_image'] = $images;
        }
        return $banners;
    }

    protected function loadData()
    {
        parent::loadData();

        $this->dataVue['Type_Status'] = Type_Status::getEnumList();
        $this->dataVue['Type_ModulePosition'] = Type_ModulePosition::getEnumList(true);
        $this->dataVue['Type_DsimDnao'] = Type_DsimDnao::getEnumList();
        $this->dataVue['Type_Tamanho'] = Type_Tamanho::getEnumList();
        $this->dataVue['Type_AutoOrManual'] = Type_AutoOrManual::getEnumList();
        $this->dataVue['Type_AdvancedOrSimple'] = Type_AdvancedOrSimple::getEnumList();
        $this->dataVue['Type_Screen'] = Type_Screen::getEnumList();
        $this->dataVue['Type_ScreenPosition'] = Type_ScreenPosition::getEnumList();
        $this->dataVue['Type_ScreenTime'] = Type_ScreenTime::getEnumList();
        $this->dataVue['Type_ModulesListBanner'] = Type_ModulesListBanner::getEnumList();
        $this->dataVue['Type_OpenLink'] = Type_OpenLink::getEnumList();
        $this->dataVue['Type_ModelBannerProduct'] = Type_ModelBannerProduct::getEnumList();
        $this->dataVue['Type_IdLayout'] = $this->load->TypeForTwig('Type_IdLayout'); //desta forma pois ele é usado para comparar e nao popular um componente select

        $this->document->addTypesForJs(array(
            Type_DsimDnao::getTypeForJs(),
        ));

        $banner_home_page = $this->model_setting_setting->getSetting('hero');

        $initialArrayBanners = [
            'banner_image' => [],
            'banner_product' => [],
            'banner_dinamico' => []
        ];

        $banner_home_page = array_merge($initialArrayBanners, $banner_home_page);

        if (empty($banner_home_page['banner_group'])) {
            $bannerGroup = [];
            $arrayGroupNames = ['Imagens', 'Produtos', 'Dinâmicos'];
            $index = 0;
            foreach ($initialArrayBanners as $key => $item) {
                $bannerGroup[] = ['type' => $key,
                    'order' => $index,
                    'name' => $arrayGroupNames[$index]];
                $index++;
            }
            $banner_home_page['banner_group'] = $bannerGroup;
        }

        $banner_home_page['banner_image'] = array_values(array_map(function ($banner_image) {

            $exist_dir_banner_image = file_exists(DIR_IMAGE . $banner_image['image']);

            $image = ($banner_image['image'] && $exist_dir_banner_image)
                ? $banner_image['image']
                : 'no_image.jpg';

            $banner_image['thumb'] = $this->dmodel_tool_image->resize(
                $image,
                Type_MiniatureSmall::Tp_width,
                Type_MiniatureSmall::Tp_height
            );

            if (isset($banner_image['analyze_id'])) {
                $acompanhamentos = $this->model_setting_analyze->getAnalyze($banner_image['analyze_id']);

                if (!$acompanhamentos) {
                    $this->model_setting_analyze->deleteAnalyze($banner_image['analyze_id']);
                    $banner_image['analyze'] = '';
                    $banner_image['analyze_id'] = '';
                } else {
                    $banner_image['analyze_quantity'] = $acompanhamentos['quantidade'];
                }
            }

            $banner_image['target'] = isset($banner_image['target']) ? $banner_image['target'] : Type_OpenLink::Tp_OpenOtherPage;

            return $banner_image;
        }, $banner_home_page['banner_image']));

        $banner_home_page['banner_product'] = array_values(array_map(function ($banner_product) {

            $exist_dir_banner_product = file_exists(DIR_IMAGE . $banner_product['image']);

            $image = ($banner_product['image'] && $exist_dir_banner_product)
                ? $banner_product['image']
                : 'no_image.jpg';

            $banner_product['thumb'] = $this->dmodel_tool_image->resize(
                $image,
                Type_MiniatureSmall::Tp_width,
                Type_MiniatureSmall::Tp_height
            );

            if (isset($banner_product['analyze_id'])) {
                $acompanhamentos = $this->model_setting_analyze->getAnalyze($banner_product['analyze_id']);

                if (!$acompanhamentos) {
                    $this->model_setting_analyze->deleteAnalyze($banner_product['analyze_id']);
                    $banner_product['analyze'] = '';
                    $banner_product['analyze_id'] = '';
                } else {
                    $banner_product['analyze_quantity'] = $acompanhamentos['quantidade'];
                }
            }

            return $banner_product;
        }, $banner_home_page['banner_product']));

        $this->dataVue['banner_home_page'] = $banner_home_page;

        $banners = $this->model_design_banner->getBanners();

        $this->dataVue['banners'] = $this->mapImages($banners);

        $modules_banners = $this->config->get('banner_module');
        $modules_carousels = $this->config->get('carousel_module');
        $modules_mosaics = $this->config->get('mosaic_module');

        $this->dataVue['configurations'] = [
            'banners' => !empty($modules_banners) ? array_values($modules_banners) : [],
            'carousels' => !empty($modules_carousels) ? array_values($modules_carousels) : [],
            'mosaics' => !empty($modules_mosaics) ? array_values($modules_mosaics) : [],
        ];

        $categories = $this->model_catalog_category->getCategories(array());
        $categories = array_map(function ($categorie) {
            $categorie = array_slice($categorie, 0, 2);
            return $categorie;
        }, $categories);


        foreach ($categories as $value){
            $categories = array_merge($categories , array([Type_SelectSearch::getEnumList()[0] =>  $value['category_id'], Type_SelectSearch::getEnumList()[1] =>  $value['name']]));
            array_shift($categories);
        }

        $categories = array_merge(array([Type_SelectSearch::getEnumList()[0] => -1, Type_SelectSearch::getEnumList()[1] => 'Todos']), $categories);
        $this->dataVue['categories'] = $categories;

        $this->dataVue['layouts'] = $this->dmodel_design_layout->getLayouts();
        $this->dataVue['no_image'] = $this->dmodel_tool_image->resize(
            'no_image.jpg',
            Type_MiniatureSmall::Tp_width,
            Type_MiniatureSmall::Tp_height
        );

        $this->dataVue['mosaic_styles'] = [
            [
                'type' => '1',
                'image' => 'view/image/mosaic/mosaic-1.jpg'
            ],
            [
                'type' => '2',
                'image' => 'view/image/mosaic/mosaic-2.jpg'
            ],
            [
                'type' => '3',
                'image' => 'view/image/mosaic/mosaic-3.jpg'
            ],
            [
                'type' => '4',
                'image' => 'view/image/mosaic/mosaic-4.jpg'
            ]
        ];
    }

    protected function validate()
    {
        $this->load->language('module/banners');
        $this->post = $this->request->post;

        extract($this->request->post);

        $error = [];

        $banner_image = isset($bannerHomePage['banner_image']) ? $bannerHomePage['banner_image'] : [];
        $banner_product = isset($bannerHomePage['banner_product']) ? $bannerHomePage['banner_product'] : [];
        $banner_dinamico = isset($bannerHomePage['banner_dinamico']) ? $bannerHomePage['banner_dinamico'] : [];
        $banner_group = isset($bannerHomePage['banner_group']) ? $bannerHomePage['banner_group'] : [];

        unset($bannerHomePage['banner_image']);
        unset($bannerHomePage['banner_product']);
        unset($bannerHomePage['banner_dinamico']);
        unset($bannerHomePage['banner_group']);

        $error['bannerHomePage'] = [];

        $bannerHomePageUpdateImage = [];
        $bannerHomePageUpdateProduct = [];
        $bannerHomePageUpdateDinamico = [];

        foreach ($banner_image as $key => $value) {

            $extra_validations = isset($value['analyze']) && $value['analyze'] == '1' ? [
                "banner_image[$key][link]" => [
                    'value' => $value['link'] ?? '',
                    'validates' => ['isEmpty'],
                ],
            ] : [];

            $bannerHomePageUpdateImage = array_merge($bannerHomePageUpdateImage, $this->validate->execute(array_merge([
                "banner_image[$key][banner_image_description][1][title]" => [
                    'value' => $value['banner_image_description'][1]['title'],
                    'validates' => ['isEmpty'],
                ],
                "banner_image[$key][target]" => [
                    'value' => $value['target'],
                    'validates' => ['isEmpty'],
                ],
                "banner_image[$key][image]" => [
                    'value' => $value['image'],
                    'validates' => ['isEmpty'],
                ],
            ], $extra_validations)));
        }

        $bannerHomePageUpdateImage ? $error['bannerHomePage']['bannerHomePageUpdateImage'] = $bannerHomePageUpdateImage : '';

        foreach ($banner_product as $key => $value) {
            $bannerHomePageUpdateProduct = array_merge($bannerHomePageUpdateProduct, $this->validate->execute([
                "banner_product[$key][banner_product_description][1][title]" => [
                    'value' => $value['banner_product_description'][1]['title'],
                    'validates' => ['isEmpty'],
                ],
            ]));
        }

        $bannerHomePageUpdateProduct ? $error['bannerHomePage']['bannerHomePageUpdateProduct'] = $bannerHomePageUpdateProduct : '';

        foreach ($banner_dinamico as $key => $value) {
            $bannerHomePageUpdateDinamico = array_merge($bannerHomePageUpdateDinamico, $this->validate->execute([
                "banner_dinamico[$key][banner_dinamico_quantidade]" => [
                    'value' => $value['banner_dinamico_quantidade'],
                    'validates' => ['isEmpty'],
                ],
            ]));
        }

        $bannerHomePageUpdateDinamico ? $error['bannerHomePage']['bannerHomePageUpdateDinamico'] = $bannerHomePageUpdateDinamico : '';

        $error['bannerHomePageConfig'] = $this->validate->execute([
            'banner_altura' => [
                'value' => $bannerHomePage['banner_altura'],
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isMinMaxNumber',
                        'min' => 0,
                        'max' => 1920
                    ]
                ],
            ],
            'banner_largura' => [
                'value' => $bannerHomePage['banner_largura'],
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isMinMaxNumber',
                        'min' => 0,
                        'max' => 1920
                    ]
                ],
            ],
            'banner_responsive_altura' => [
                'value' => $bannerHomePage['banner_responsive_altura'],
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isMinMaxNumber',
                        'min' => 0,
                        'max' => 1920
                    ]
                ],
            ],
            'banner_responsive_largura' => [
                'value' => $bannerHomePage['banner_responsive_largura'],
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isMinMaxNumber',
                        'min' => 0,
                        'max' => 1920
                    ]
                ],
            ],
        ]);

        array_filter($error['bannerHomePage']);

        // Errors design banners
        $bannerConfig = [];
        $bannerUpdateImage = [];

        $error['banners'] = [];

        if (isset($banners)) {
            foreach ($banners as $key => $banner) {
                $bannerConfig = array_merge($bannerConfig, $this->validate->execute([
                    "banners[$key][name]" => [
                        'value' => $banner['name'],
                        'validates' => ['isEmpty'],
                    ],
                    "banners[$key][status]" => [
                        'value' => $banner['status'],
                        'validates' => ['isEmpty'],
                    ],
                ]));

                if (isset($banner['banner_image'])) {
                    foreach ($banner['banner_image'] as $keyImg => $image) {
                        $bannerUpdateImage = array_merge($bannerUpdateImage, $this->validate->execute([
                            "banners[$key][banner_image][$keyImg][image]" => [
                                'value' => $image['image'],
                                'validates' => ['isEmpty'],
                            ],
                            "banners[$key][banner_image_description][1][title]" => [
                                'value' => $image['banner_image_description'][1]['title'],
                                'validates' => ['isEmpty'],
                            ],
                        ]));
                    }
                }
            }
        }

        $bannerConfig ? $error['banners']['bannerConfig'] = $bannerConfig : '';
        $bannerUpdateImage ? $error['banners']['bannerUpdateImage'] = $bannerUpdateImage : '';

        $bannerUpdateLayout = [];

        $error['modules'] = [];

        // Errors modules banners, carousels and mosaics
        if (isset($modules)) {
            if (isset($modules['banners'])) {
                foreach ($modules['banners'] as $key => $banner) {
                    $arrayValidateBanner = [
                        "banners[$key][height]" => [
                            'value' => $banner['height'],
                            'validates' => ['isEmpty'],
                        ],
                        "banners[$key][width]" => [
                            'value' => $banner['width'],
                            'validates' => ['isEmpty'],
                        ],
                        "banners[$key][sort_order]" => [
                            'value' => $banner['sort_order'],
                            'validates' => ['isEmpty'],
                        ],
                        "banners[$key][style]" => [
                            'value' => $banner['style'],
                            'validates' => ['isEmpty'],
                        ],
                        "banners[$key][layout_id]" => [
                            'value' => $banner['layout_id'],
                            'validates' => ['isEmpty'],
                        ],
                    ];

                    if(isset($banner['category_id'])){
                        $arrayValidateBanner["banners[$key][category_id]"] = [
                            'value' => $banner['category_id'],
                            'validates' => ['isEmpty'],
                        ];
                    }

                    $bannerUpdateLayout = array_merge($bannerUpdateLayout, $this->validate->execute($arrayValidateBanner));
                }
            }

            if (isset($modules['carousels'])) {
                foreach ($modules['carousels'] as $key => $carousel) {
                    $arrayValidateCarousels = [
                        "carousels[$key][height]" => [
                            'value' => $carousel['height'],
                            'validates' => ['isEmpty'],
                        ],
                        "carousels[$key][width]" => [
                            'value' => $carousel['width'],
                            'validates' => ['isEmpty'],
                        ],
                        "carousels[$key][sort_order]" => [
                            'value' => $carousel['sort_order'],
                            'validates' => ['isEmpty'],
                        ],
                        "carousels[$key][style]" => [
                            'value' => $carousel['style'],
                            'validates' => ['isEmpty'],
                        ],
                        "carousels[$key][layout_id]" => [
                            'value' => $carousel['layout_id'],
                            'validates' => ['isEmpty'],
                        ],
                    ];

                    if(isset($carousel['category_id'])){
                        $arrayValidateCarousels["carousels[$key][category_id]"] = [
                            'value' => $carousel['category_id'],
                            'validates' => ['isEmpty'],
                        ];
                    }

                    $bannerUpdateLayout = array_merge($bannerUpdateLayout, $this->validate->execute($arrayValidateCarousels));
                }
            }

            if (isset($modules['mosaics'])) {
                foreach ($modules['mosaics'] as $key => $mosaic) {
                    $arrayValidateMosaics = [
                        "mosaics[$key][min_size]" => [
                            'value' => $mosaic['min_size'],
                            'validates' => ['isEmpty'],
                        ],
                        "mosaics[$key][sort_order]" => [
                            'value' => $mosaic['sort_order'],
                            'validates' => ['isEmpty'],
                        ],
                        "mosaics[$key][style]" => [
                            'value' => $mosaic['style'],
                            'validates' => ['isEmpty'],
                        ],
                        "mosaics[$key][layout_id]" => [
                            'value' => $mosaic['layout_id'],
                            'validates' => ['isEmpty'],
                        ],
                    ];

                    if(isset($mosaic['category_id'])){
                        $arrayValidateMosaics["mosaics[$key][category_id]"] = [
                            'value' => $mosaic['category_id'],
                            'validates' => ['isEmpty'],
                        ];
                    }

                    $bannerUpdateLayout = array_merge($bannerUpdateLayout, $this->validate->execute($arrayValidateMosaics));
                }
            }
        }

        $bannerUpdateLayout ? $error['modules']['bannerUpdateLayout'] = $bannerUpdateLayout : '';

        return array_filter($error);
    }

    public function save()
    {
        $type = $this->request->get['type'];
        parent::save();
        if (!$this->errors) {
            $this->responseJson['redirect'] = $this->url->link($this->referencePathFile, 'token=' . $this->token . '&type=' . $type, 'SSL');
            $this->response->setOutputJson($this->responseJson);
        }
    }

    public function saveSetting()
    {
        $this->load->model('setting/setting');
        $this->load->model('setting/analyze');

        $banner_home_page = $this->model_setting_setting->getSetting('hero');

        if (isset($this->post['excluded'])) {
            foreach ($this->post['excluded'] as $bannerIdDelete) {
                $this->model_design_banner->deleteBanner($bannerIdDelete);
            }
        }

        $newBanner = [];

        if (isset($this->post['banners'])) {
            $this->load->model('design/banner');

            $bannerIdsDb = $this->model_design_banner->getIdsBanners();


            foreach ($this->post['banners'] as $key => $banner) {
                if (!in_array($banner['banner_id'], $bannerIdsDb)) {
                    $newBannerId = $this->model_design_banner->addBanner($this->post['banners'][$key]);
                    $newBanner[$banner['banner_id']] = $newBannerId;
                } else {
                    $this->model_design_banner->editBanner(
                        $banner['banner_id'],
                        $this->post['banners'][$key]
                    );
                }
            }
        }

        if (isset($this->post['modules'])) {
            if (isset($this->post['modules']['banners'])) {
                $this->setBanners('banners', $newBanner);
                if ($this->hasNewBanner('banners')) {
                    $data = [];
                    $data['banner_module'] = $this->post['modules']['banners'];
                    $this->model_setting_setting->editSetting('banner', $data);
                } else {
                    $this->model_setting_setting->editSettingValue(
                        'banner',
                        'banner_module',
                        $this->post['modules']['banners']
                    );
                }
            } else {
                $this->model_setting_setting->deleteSetting('banner');
            }

            if (isset($this->post['modules']['carousels'])) {
                $this->setBanners('carousels', $newBanner);
                if ($this->hasNewBanner('carousels')) {
                    $data = [];
                    $data['carousel_module'] = $this->post['modules']['carousels'];
                    $this->model_setting_setting->editSetting('carousel', $data);
                } else {
                    $this->model_setting_setting->editSettingValue(
                        'carousel',
                        'carousel_module',
                        $this->post['modules']['carousels']
                    );
                }
            } else {
                $this->model_setting_setting->deleteSetting('carousel');
            }


            if (isset($this->post['modules']['mosaics'])) {
                $this->setBanners('mosaics', $newBanner);
                if ($this->hasNewBanner('mosaics')) {
                    $data = [];
                    $data['mosaic_module'] = $this->post['modules']['mosaics'];
                    $this->model_setting_setting->editSetting('mosaic', $data);
                } else {
                    $this->model_setting_setting->editSettingValue(
                        'mosaic',
                        'mosaic_module',
                        $this->post['modules']['mosaics']
                    );
                }
            } else {
                $this->model_setting_setting->deleteSetting('mosaic');
            }

        } else {
            $this->model_setting_setting->deleteSetting('banner');
            $this->model_setting_setting->deleteSetting('carousel');
            $this->model_setting_setting->deleteSetting('mosaic');
        }

        if (isset($this->post['bannerHomePage']['banner_image'])) {
            $indexGroup = array_search('banner_image', array_column($this->post['bannerHomePage']['banner_group'], 'type'));

            foreach ($this->post['bannerHomePage']['banner_image'] as $banner_image_id => $banner_image) {
                $this->post['bannerHomePage']['banner_image'][$banner_image_id]['banner_order'] = $banner_image_id;
                $this->post['bannerHomePage']['banner_image'][$banner_image_id]['banner_group_order'] = $this->post['bannerHomePage']['banner_group'][$indexGroup]['order'];

                if (isset($this->post['bannerHomePage']['banner_image'][$banner_image_id]['link'])) {
                    $this->post['bannerHomePage']['banner_image'][$banner_image_id]['link'] = htmlspecialchars_decode($this->post['bannerHomePage']['banner_image'][$banner_image_id]['link']);
                }

                if (isset($banner_image['analyze']) && !$banner_image['analyze_id']) {
                    $analyze_id = $this->model_setting_analyze->addAnalyze(array(
                        'analyze_title' => 'BANNER - ' . $banner_image['banner_image_description'][1]['title'],
                        'analyze_code' => ftr_geral::getUnicCodeAnalize()
                    ));

                    $this->post['bannerHomePage']['banner_image'][$banner_image_id]['analyze_id'] = $analyze_id;
                    $json['acompanhamentos'][] = array("banner_image[$banner_image_id][analyze_id]" => $analyze_id);

                } elseif (!isset($banner_image['analyze']) && isset($banner_image['analyze_id']) && $banner_image['analyze_id']) {
                    $this->model_setting_analyze->deleteAnalyze($banner_image['analyze_id']);
                    $json['acompanhamentos'][] = array("banner_image[$banner_image_id][analyze_id]" => '');
                }
            }

            if (!isset($banner_home_page['banner_image'])) {
                $this->model_setting_setting->insertSettingValue(
                    'hero',
                    'banner_image',
                    $this->post['bannerHomePage']['banner_image']
                );
            } else {
                $this->model_setting_setting->editSettingValue(
                    'hero',
                    'banner_image',
                    $this->post['bannerHomePage']['banner_image']
                );
            }

        } else {
            $this->model_setting_setting->deleteSettingValue(
                'hero',
                'banner_image'
            );
        }

        if (isset($this->post['bannerHomePage']['banner_product'])) {
            $indexGroup = array_search('banner_product', array_column($this->post['bannerHomePage']['banner_group'], 'type'));

            foreach ($this->post['bannerHomePage']['banner_product'] as $banner_product_id => $banner_product) {
                $this->post['bannerHomePage']['banner_product'][$banner_product_id]['banner_order'] = $banner_product_id;
                $this->post['bannerHomePage']['banner_product'][$banner_product_id]['banner_group_order'] = $this->post['bannerHomePage']['banner_group'][$indexGroup]['order'];

                if (isset($banner_product['analyze']) && !$banner_product['analyze_id']) {
                    $analyze_id = $this->model_setting_analyze->addAnalyze(array(
                        'analyze_title' => 'BANNER - ' . $banner_product['banner_product_description'][1]['title'],
                        'analyze_code' => ftr_geral::getUnicCodeAnalize()
                    ));

                    $this->post['bannerHomePage']['banner_product'][$banner_product_id]['analyze_id'] = $analyze_id;
                    $json['acompanhamentos'][] = array("banner_product[$banner_product_id][analyze_id]" => $analyze_id);

                } elseif (!isset($banner_product['analyze']) && isset($banner_product['analyze_id']) && $banner_product['analyze_id']) {
                    $this->model_setting_analyze->deleteAnalyze($banner_product['analyze_id']);
                    $json['acompanhamentos'][] = array("banner_product[$banner_product_id][analyze_id]" => '');
                }
            }

            if (!isset($banner_home_page['banner_product'])) {
                $this->model_setting_setting->insertSettingValue(
                    'hero',
                    'banner_product',
                    $this->post['bannerHomePage']['banner_product']
                );
            } else {
                $this->model_setting_setting->editSettingValue(
                    'hero',
                    'banner_product',
                    $this->post['bannerHomePage']['banner_product']
                );
            }

        } else {
            $this->model_setting_setting->deleteSettingValue(
                'hero',
                'banner_product'
            );
        }

        if (isset($this->post['bannerHomePage']['banner_dinamico'])) {
            $indexGroup = array_search('banner_dinamico', array_column($this->post['bannerHomePage']['banner_group'], 'type'));

            foreach ($this->post['bannerHomePage']['banner_dinamico'] as $banner_dinamico_id => $banner_dinamico) {
                $this->post['bannerHomePage']['banner_dinamico'][$banner_dinamico_id]['banner_dinamico_ordem'] = $banner_dinamico_id;
                $this->post['bannerHomePage']['banner_dinamico'][$banner_dinamico_id]['banner_group_order'] = $this->post['bannerHomePage']['banner_group'][$indexGroup]['order'];
            }

            if (!isset($banner_home_page['banner_dinamico'])) {
                $this->model_setting_setting->insertSettingValue(
                    'hero',
                    'banner_dinamico',
                    $this->post['bannerHomePage']['banner_dinamico']
                );
            } else {
                $this->model_setting_setting->editSettingValue(
                    'hero',
                    'banner_dinamico',
                    $this->post['bannerHomePage']['banner_dinamico']
                );
            }

        } else {
            $this->model_setting_setting->deleteSettingValue(
                'hero',
                'banner_dinamico'
            );
        }

        if (isset($this->post['bannerHomePage']['banner_group'])) {

            foreach ($this->post['bannerHomePage']['banner_group'] as $banner_group_id => $banner_group) {
                $this->post['bannerHomePage']['banner_group'][$banner_group_id]['order'] = $banner_group_id;
            }

            if (!isset($banner_home_page['banner_group'])) {
                $this->model_setting_setting->insertSettingValue(
                    'hero',
                    'banner_group',
                    $this->post['bannerHomePage']['banner_group']
                );
            } else {
                $this->model_setting_setting->editSettingValue(
                    'hero',
                    'banner_group',
                    $this->post['bannerHomePage']['banner_group']
                );
            }

        } else {
            $this->model_setting_setting->deleteSettingValue(
                'hero',
                'banner_group'
            );
        }

        $config = array_filter($this->post['bannerHomePage'], function ($key) {
            return !in_array($key, ['banner_image', 'banner_product', 'banner_dinamico', 'banner_group']);
        }, ARRAY_FILTER_USE_KEY);

        $this->model_setting_setting->editSettingForKey('hero', $config);

    }

    public function setBanners($module, $newBanners)
    {
        if ($newBanners) {
            // $key contem o banner_id da interface
            // $value contem o banner_id da base
            foreach ($newBanners as $key => $value) {
                $index = array_search($key, array_column($this->post['modules'][$module], 'banner_id'));
                if ($index !== false && isset($this->post['modules'][$module][$index])) {
                    $this->post['modules'][$module][$index]['banner_id'] = $value;
                }
            }
        }
    }

    public function hasNewBanner($module)
    {
        $indice = array_search('true', array_column($this->post['modules'][$module], 'first_module'));

        if ($indice === false) {
            return false;
        } else {
            unset($this->post['modules'][$module][$indice]['first_module']);
            return true;
        }
    }

    public function install()
    {
        $this->load->model('setting/extension');
        $this->model_setting_extension->install('module', 'banner');
        $this->model_setting_extension->install('module', 'carousel');
        $this->model_setting_extension->install('module', 'mosaic');
    }

    public function uninstall()
    {
        $this->load->model('setting/extension');
        $this->model_setting_extension->uninstallSetting('module', 'banner');
        $this->model_setting_extension->uninstallSetting('module', 'carousel');
        $this->model_setting_extension->uninstallSetting('module', 'mosaic');
    }

}
