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

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

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

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

    $this->load->type('tipocomum');

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

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

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

		$this->load->model('setting/setting');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
			$this->model_setting_setting->editSetting('random', $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['entry_type']          = $this->language->get('entry_type');
    $this->data['entry_column_title']  = $this->language->get('entry_column_title');
    $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/random', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL'),
			'separator' => ' :: '
		);

		$this->data['action'] = $this->url->link('module/random', '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');

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

		$modules = array();

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

    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::getRemoveArray([Type_ModulePosition::Tp_ColumnRight], true);

		$this->children = array(
			'common/header',
			'common/footer'
		);
		$this->response->setOutput($this->render('module/random'));
	}

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

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

			foreach ($this->request->post['random_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 (in_array($value['position'], [Type_ModulePosition::Tp_ColumnLeft, Type_ModulePosition::Tp_ColumnRight])
                    || (($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 {
			return false;
		}
	}
}
