<?php

class ControllerModuleBanner extends Controller
{
    protected function index($setting)
    {
        static $module = 0;

        $is_category_page = isset($this->request->get['route']) && $this->request->get['route'] == 'product/category';
        $is_category_layout = isset($setting['layout_id']) && $setting['layout_id'] == Type_IdLayout::Tp_Idcategory;
        $has_current_page_category_id = isset($this->request->get['path']);
        $has_banner_category_id_config = isset($setting['category_id']);
        $has_show_in_subsequent_config = isset($setting['show_in_subsequent_categories']);

        if($is_category_page && $is_category_layout &&
            $has_current_page_category_id && $has_banner_category_id_config)
        {
            $current_page_category_id = null;
            $valid_category_to_show = false;
            $path = $this->request->get['path']; //path eh onde vem os category id, sao separados por underline quando é uma sub-categoria
            $parts = explode('_', (string)$path);

            if($has_show_in_subsequent_config && $setting['show_in_subsequent_categories']){
                $valid_category_to_show = in_array($setting['category_id'], $parts);
            } else {
                $current_page_category_id = (int)array_pop($parts);
            }

            $show_banner = $setting['category_id'] == "-1" || ($current_page_category_id == (int)$setting['category_id']) || $valid_category_to_show;

            if(!$show_banner){
                return;
            }
        }

        $this->load->model('design/banner');
        $this->load->dmodel('tool/image');

        $this->data['type'] = isset($setting['type']) ? $setting['type'] : false ;
        $this->data['banners'] = array();

        $results = $this->model_design_banner->getBanner($setting['banner_id']);

        if ($results) {
            foreach ($results as $result) {
                if (file_exists(DIR_IMAGE . $result['image'])) {
                    $this->data['banners'][] = array(
                        'title' => $result['title'],
                        'link' => $result['link'],
                        'image' => $this->dmodel_tool_image->resize($result['image'], $setting['width'], $setting['height']),
                        'tamanho' => isset($setting['tamanho']) ? $setting['tamanho'] : 4
                    );
                }
            }

            $this->data['module'] = $module++;

            if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/banner.tpl')) {
                $this->template = $this->config->get('config_template') . '/template/module/banner.tpl';
            } else {
                $this->template = 'default/template/module/banner.tpl';
            }

            $this->render('module/banner');
        }
    }
}
