<?php
class ControllerModuleLatest extends Controller {
	private $error = array();

	public function index() {
		$language = $this->language->load('module/latest');

    $this->data = array_merge($this->data, $language);

    $this->data['languageForJS'] = array(
      'module/latest' => $language
    );

    $this->load->helper('ftr_geral');

    $this->data['ftr_geral'] = new ftr_geral();

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('setting/setting');
		$this->load->helper('ftr_geral');
		$this->load->type('tipocomum');

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

    $this->document->addScript('admin/public/js/module/latest.js');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
			$this->model_setting_setting->editSetting('latest', $this->request->post);

			$this->cache->delete('product');

			$this->session->data['success'] = $this->language->get('text_success');

			$this->redirect($this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL'));
		}

		$this->data['heading_title'] = $this->language->get('heading_title');

		$this->data['text_enabled'] = $this->language->get('text_enabled');
		$this->data['text_disabled'] = $this->language->get('text_disabled');
		$this->data['text_content_top'] = $this->language->get('text_content_top');
		$this->data['text_content_bottom'] = $this->language->get('text_content_bottom');
		$this->data['text_column_left'] = $this->language->get('text_column_left');
		$this->data['text_column_right'] = $this->language->get('text_column_right');
		$this->data['text_title'] = $this->language->get('text_title');

		$this->data['entry_type'] = $this->language->get('entry_type');
    $this->data['entry_limit'] = $this->language->get('entry_limit');
		$this->data['entry_image'] = $this->language->get('entry_image');
		$this->data['entry_layout'] = $this->language->get('entry_layout');
		$this->data['entry_position'] = $this->language->get('entry_position');
		$this->data['entry_status'] = $this->language->get('entry_status');
		$this->data['entry_sort_order'] = $this->language->get('entry_sort_order');

		$this->data['button_save'] = $this->language->get('button_save');
		$this->data['button_cancel'] = $this->language->get('button_cancel');
		$this->data['button_add_module'] = $this->language->get('button_add_module');
		$this->data['button_remove'] = $this->language->get('button_remove');

		if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}

		if (isset($this->error['image'])) {
			$this->data['error_image'] = $this->error['image'];
		} else {
			$this->data['error_image'] = array();
		}

		if (isset($this->error['limit'])) {
			$this->data['error_limit'] = $this->error['limit'];
		} else {
			$this->data['error_limit'] = array();
		}

    if (isset($this->error['grid_limit'])) {
        $this->data['error_grid_limit'] = $this->error['grid_limit'];
    } else {
        $this->data['error_grid_limit'] = array();
    }

		if (isset($this->error['sort_order'])) {
			$this->data['error_sort_order'] = $this->error['sort_order'];
		} else {
			$this->data['error_sort_order'] = array();
		}

		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
			'separator' => false
		);

		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_module'),
			'href'      => $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL'),
			'separator' => ' :: '
		);

		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('module/latest', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL'),
			'separator' => ' :: '
		);

		$this->data['action'] = $this->url->link('module/latest', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL');

		$this->data['cancel'] = $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL');

		$modules = array();

		if (isset($this->request->post['latest_module'])) {
			$modules = $this->request->post['latest_module'];
		} elseif ($this->config->get('latest_module')) {
			$modules = $this->config->get('latest_module');
		}

		if(isset($this->request->post['latest_title'])){
			$this->data['latest_title'] = $this->request->post['latest_title'];
		}else{
			$this->data['latest_title'] = $this->config->get('latest_title');
    }

    $this->data['modules'] = array();

    if($modules){
      foreach ($modules as $key => $module) {
        if(!in_array('entry_type', array_keys($module))){
          $modules[$key]['entry_type'] = '';
        }
        if(!in_array('limit', array_keys($module))){
          $modules[$key]['limit'] = Type_DefaultValues::Tp_LimitModules24;
        }
      }
    }

    $this->data['modules'] = $modules;

		$this->load->dmodel('design/layout');

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

		$this->data['layouts'] = $this->dmodel_design_layout->getLayouts($data);

        $this->data['positions'] = Type_ModulePosition::getEnumList(true);

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

		$this->response->setOutput($this->render($this->template = 'module/latest'));
	}

	protected function validate() {
		if (!$this->user->hasPermission('modify', 'module/latest')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		if (isset($this->request->post['latest_module'])) {
            $layoutArray = array(
                'layout' => array(),
                'layout_app' => array()
            );

			foreach ($this->request->post['latest_module'] as $key => $value) {

        if ($value['position'] == Type_ModulePosition::Tp_AppMobile) {
          $layoutArray['layout_app'][$key] = $value['layout_id'];
        } else {
          $layoutArray['layout'][$key] = $value['layout_id'];
        }

        if (((isset($value['entry_type']) && $value['entry_type'] == Type_DsimDnao::Tp_Sim) || ($value['position'] == Type_ModulePosition::Tp_ColumnLeft))
            && ((!isset($value['limit'])) or ($value['limit']==""))) {
            $this->error['grid_limit'][$key] = $this->language->get('error_grid_limit');
        }

        if (isset($value['limit'])) {
            if (in_array($value['position'], [Type_ModulePosition::Tp_ContentTop, Type_ModulePosition::Tp_ContentBottom])
              && isset($value['entry_type']) && $value['entry_type'] == Type_DsimDnao::Tp_Sim) {

              if ($value['limit'] > Type_DefaultValues::Tp_LimitModules99) {
                  $this->error['limit'][$key] = sprintf($this->language->get('error_limit'), Type_DefaultValues::Tp_limitModules99);
              }

            } else if (($value['position'] == Type_ModulePosition::Tp_ColumnLeft)
                || (($value['position'] == Type_ModulePosition::Tp_AppMobile)
                && isset($value['entry_type']) && $value['entry_type'] == Type_DsimDnao::Tp_Sim)) {

              if ($value['limit'] > Type_DefaultValues::Tp_LimitModules24) {
                  $this->error['limit'][$key] = sprintf($this->language->get('error_limit'), Type_DefaultValues::Tp_LimitModules24);
              }

            }
        }

        if($value['sort_order']==""){
					$this->error['sort_order'][$key]	= $this->language->get('error_sort_order');
				}

			}

      foreach ($layoutArray as $key => $value) {
          $validalayoutArray = array_unique($value);
          if(count($validalayoutArray) != count($value)) {
              $this->error['warning'] = $this->language->get('error_layout');
          }
      }
		}

		if (!$this->error) {
			return true;
		} else {
		    if (!isset($this->error['warning'])) {
		        $this->error['warning'] = $this->language->get('error_warning');
            }
			return false;
		}
	}
}
