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

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

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

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

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

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

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

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

    $this->data['Type_DsimDnao'] = $this->load->typeForTwig('Type_DsimDnao');


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

      $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_limit']                      = $this->language->get('entry_limit');
    $this->data['entry_image']                      = $this->language->get('entry_image');
    $this->data['entry_category']                   = $this->language->get('entry_category');
    $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_display']                    = $this->language->get('entry_display');
    $this->data['entry_normal']                     = $this->language->get('entry_normal');
    $this->data['entry_carousel']                   = $this->language->get('entry_carousel');
    $this->data['entry_subcats']                    = $this->language->get('entry_subcats');
    $this->data['entry_snone']                      = $this->language->get('entry_snone');
    $this->data['entry_filtering']                  = $this->language->get('entry_filtering');
    $this->data['entry_ctabs']                      = $this->language->get('entry_ctabs');
    $this->data['entry_pmin']                       = $this->language->get('entry_pmin');
    $this->data['entry_sort_order']                 = $this->language->get('entry_sort_order');
    $this->data['text_lpbc_module_interests']       = $this->language->get('Exibir apenas área de interesse para usuários logado:');
    $this->data['text_lpbc_module_interests_limit'] = $this->language->get('Quantidade máxima de exibições de módulos na página principal:');
    $this->data['text_lpbc_module_interests_order'] = $this->language->get('Ordem de exibição:');


    $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');

    $results = $this->model_catalog_category->getCategories(0);

    foreach ($results as $result) {
      if ($result['status']) {
        $this->data['categories'][] = array(
          'category_id' => $result['category_id'],
          'name'        => $result['name']
        );
      }
    }

    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/lpbc', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL'),
      'separator' => ' :: '
    );

    $this->data['action'] = $this->url->link('module/lpbc', '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['lpbc_module'])) {
        $modules = $this->request->post['lpbc_module'];
    } elseif ($this->config->get('lpbc_module')) {
        $modules = $this->config->get('lpbc_module');
    }

    $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;

    $modules_interests = array();

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

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

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

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

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

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

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

    $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/lpbc'));
  }

  private function validate() {

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

    if (isset($this->request->post['lpbc_module_interests_status'])) {
        $moduleType = $this->request->post['lpbc_module_interests_status'] == 1 ? 'lpbc_module_interests' : 'lpbc_module';

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

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

            if ($value['position'] == Type_ModulePosition::Tp_AppMobile) {
                $layoutArray['layout_app'][$value['category_id']][$key] = $value['layout_id'];
            } else {
                $layoutArray['layout'][$value['category_id']][$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 $key1 => $layoutArrayByCategory){
                foreach ($layoutArrayByCategory as $key2 => $values) {
                    $validalayoutArray = array_unique($values);
                    if(count($validalayoutArray) != count($values)) {
                        $this->error['warning'] = $this->language->get('error_layout');
                    }
                }
            }

        }
    }
    }
    if (!$this->error) {
      return TRUE;
    } else {
      return FALSE;
    }
  }
}
