<?php

class ControllerUserUserPermission extends Controller
{
  private $error = array();

  public function index()
  {
    $this->language->load('user/user_group');

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

    $this->load->model('user/user_group');

    $this->getList();
  }

  public function insert(){
    $this->language->load('user/user_group');

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

    $this->load->model('user/user_group');
    $this->load->model('user/user_group_permission');

    if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
      $this->model_user_user_group->addUserGroup($this->request->post);

      $userGroupId = $this->db->getLastId();

      $permissionAll = json_decode(htmlspecialchars_decode($this->request->post['list'], ENT_COMPAT), true);
      $permissionAccess = $this->request->post['permission']['access'] ?? array();
      $permissionModify = $this->request->post['permission']['modify'] ?? array();

      foreach ($permissionAll as $value){
        $permission[] = array(
          'permission' => $value,
          'access' => in_array($value, $permissionAccess) ? 1 : 0,
          'modify' => in_array($value, $permissionModify) ? 1 : 0);
      }

      $this->model_user_user_group_permission->editUserGroupPermissionMulti($userGroupId, $permission);

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

      $url = '';

      if (isset($this->request->get['sort'])) {
        $url .= '&sort=' . $this->request->get['sort'];
      }

      if (isset($this->request->get['order'])) {
        $url .= '&order=' . $this->request->get['order'];
      }

      if (isset($this->request->get['page'])) {
        $url .= '&page=' . $this->request->get['page'];
      }

      return $this->response->setOutputJson(['redirect' =>  $this->url->link('user/user_permission', 'token=' . $this->session->data['token'] . $url, 'SSL')]);
    }

    $this->getForm();
  }

  public function update()
  {
    $this->language->load('user/user_group');

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

    $this->load->model('user/user_group');
    $this->load->model('user/user_group_permission');
    if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
      $this->model_user_user_group->editUserGroup($this->request->get['user_group_id'], $this->request->post);

      $permissionAll = json_decode(htmlspecialchars_decode($this->request->post['list'], ENT_COMPAT), true);
      $permissionAccess = $this->request->post['permission']['access'] ?? array();
      $permissionModify = $this->request->post['permission']['modify'] ?? array();

      foreach ($permissionAll as $value){
        $permission[] = array(
          'permission' => $value,
          'access' => in_array($value, $permissionAccess) ? 1 : 0,
          'modify' => in_array($value, $permissionModify) ? 1 : 0);
      }

      $this->model_user_user_group_permission->editUserGroupPermissionMulti($this->request->get['user_group_id'], $permission);

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

      $url = '';

      if (isset($this->request->get['sort'])) {
        $url .= '&sort=' . $this->request->get['sort'];
      }

      if (isset($this->request->get['order'])) {
        $url .= '&order=' . $this->request->get['order'];
      }

      if (isset($this->request->get['page'])) {
        $url .= '&page=' . $this->request->get['page'];
      }

      return $this->response->setOutputJson(['redirect' =>  $this->url->link('user/user_permission', 'token=' . $this->session->data['token'] . $url, 'SSL')]);
    }

    $this->getForm();
  }

  public function delete()
  {
    $this->language->load('user/user_group');

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

    $this->load->model('user/user_group');

    if (isset($this->request->post['selected']) && $this->validateDelete()) {
      foreach ($this->request->post['selected'] as $user_group_id) {
        $this->model_user_user_group->deleteUserGroup($user_group_id);
      }

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

      $url = '';

      if (isset($this->request->get['sort'])) {
        $url .= '&sort=' . $this->request->get['sort'];
      }

      if (isset($this->request->get['order'])) {
        $url .= '&order=' . $this->request->get['order'];
      }

      if (isset($this->request->get['page'])) {
        $url .= '&page=' . $this->request->get['page'];
      }

      $this->redirect($this->url->link('user/user_permission', 'token=' . $this->session->data['token'] . $url, 'SSL'));
    }

    $this->getList();
  }

  protected function getList()
  {
    if (isset($this->request->get['sort'])) {
      $sort = $this->request->get['sort'];
    } else {
      $sort = 'name';
    }

    if (isset($this->request->get['order'])) {
      $order = $this->request->get['order'];
    } else {
      $order = 'ASC';
    }

    if (isset($this->request->get['page'])) {
      $page = $this->request->get['page'];
    } else {
      $page = 1;
    }

    $url = '';

    if (isset($this->request->get['sort'])) {
      $url .= '&sort=' . $this->request->get['sort'];
    }

    if (isset($this->request->get['order'])) {
      $url .= '&order=' . $this->request->get['order'];
    }

    if (isset($this->request->get['page'])) {
      $url .= '&page=' . $this->request->get['page'];
    }

    $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('heading_title'),
      'href' => $this->url->link('user/user_permission', 'token=' . $this->session->data['token'] . $url, 'SSL'),
      'separator' => ' :: '
    );

    $this->data['insert'] = $this->url->link('user/user_permission/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
    $this->data['delete'] = $this->url->link('user/user_permission/delete', 'token=' . $this->session->data['token'] . $url, 'SSL');

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

    $data = array(
      'sort' => $sort,
      'order' => $order,
      'start' => ($page - 1) * $this->config->get('config_admin_limit'),
      'limit' => $this->config->get('config_admin_limit')
    );

    $user_group_total = $this->model_user_user_group->getTotalUserGroups();

    $results = $this->model_user_user_group->getUserGroups($data);

    foreach ($results as $result) {

      $this->data['user_groups'][] = array(
        'user_group_id' => $result['user_group_id'],
        'name' => $result['name'],
        'selected' => isset($this->request->post['selected']) && in_array($result['user_group_id'], $this->request->post['selected']),
        'href' => $this->url->link('user/user_permission/update', 'token=' . $this->session->data['token'] . '&user_group_id=' . $result['user_group_id'] . $url, 'SSL')
      );
    }

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

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

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

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

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

    if (isset($this->session->data['success'])) {
      $this->data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $this->data['success'] = '';
    }

    $url = '';

    if ($order == 'ASC') {
      $url .= '&order=DESC';
    } else {
      $url .= '&order=ASC';
    }

    if (isset($this->request->get['page'])) {
      $url .= '&page=' . $this->request->get['page'];
    }

    $this->data['sort_name'] = $this->url->link('user/user_permission', 'token=' . $this->session->data['token'] . '&sort=name' . $url, 'SSL');

    $url = '';

    if (isset($this->request->get['sort'])) {
      $url .= '&sort=' . $this->request->get['sort'];
    }

    if (isset($this->request->get['order'])) {
      $url .= '&order=' . $this->request->get['order'];
    }

    $pagination = new Pagination();
    $pagination->total = $user_group_total;
    $pagination->page = $page;
    $pagination->limit = $this->config->get('config_admin_limit');
    $pagination->text = $this->language->get('text_pagination');
    $pagination->url = $this->url->link('user/user_permission', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

    $this->data['pagination'] = $pagination->render();

    $this->data['sort'] = $sort;
    $this->data['order'] = $order;

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

    $this->response->setOutput($this->render('user/user_group_list'));
  }

  protected function getForm()
  {

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

    $this->data['text_select_all'] = $this->language->get('text_select_all');
    $this->data['text_unselect_all'] = $this->language->get('text_unselect_all');
    $this->data['keypasta'] = $this->language->get('keypasta');

    $this->data['entry_name'] = $this->language->get('entry_name');
    $this->data['entry_access'] = $this->language->get('entry_access');
    $this->data['entry_modify'] = $this->language->get('entry_modify');

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

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

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

    $url = '';

    if (isset($this->request->get['sort'])) {
      $url .= '&sort=' . $this->request->get['sort'];
    }

    if (isset($this->request->get['order'])) {
      $url .= '&order=' . $this->request->get['order'];
    }

    if (isset($this->request->get['page'])) {
      $url .= '&page=' . $this->request->get['page'];
    }

    $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('heading_title'),
      'href' => $this->url->link('user/user_permission', 'token=' . $this->session->data['token'] . $url, 'SSL'),
      'separator' => ' :: '
    );

    if (!isset($this->request->get['user_group_id'])) {
      $this->data['action'] = $this->url->link('user/user_permission/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
    } else {
      $this->data['action'] = $this->url->link('user/user_permission/update', 'token=' . $this->session->data['token'] . '&user_group_id=' . $this->request->get['user_group_id'] . $url, 'SSL');
    }

    $this->data['cancel'] = $this->url->link('user/user_permission', 'token=' . $this->session->data['token'] . $url, 'SSL');

    if (isset($this->request->get['user_group_id']) && $this->request->server['REQUEST_METHOD'] != 'POST') {
      $user_group_info = $this->model_user_user_group->getUserGroup($this->request->get['user_group_id']);
      $user_group_permission = $this->model_user_user_group_permission->getUserGroupPermission($this->request->get['user_group_id']);
    }


    if (isset($this->request->post['name'])) {
      $this->data['name'] = $this->request->post['name'];
    } elseif (!empty($user_group_info)) {
      $this->data['name'] = $user_group_info['name'];
    } else {
      $this->data['name'] = '';
    }

    $usergroup_logged = $this->user->getUserGroup();

    if ($usergroup_logged > 1) {
      $ignoreAccess = array(
        'common/home',
        'common/startup',
        'common/upload',
        'common/imagemanager',
        'common/recordmanager',
        'common/login',
        'common/logout',
        'common/forgotten',
        'common/manual',
        'common/adsbanner',
        'common/reset',
        'common/notification',
        'common/nav',
        'error/not_found',
        'error/permission',
        'common/footer',
        'common/header',
        'catalog/filter',
        'catalog/option',
        'catalog/profile',
        'catalog/download',
        'catalog/filter',
        'module/preco_dinamico',
        'tool/backup',
        'extension/openbay',
        'extension/manager',
        'localisation/tax_class',
        'localisation/tax_rate',
        'report/affiliate_commission',
        'report/sale_tax',
        'sale/affiliate',
        'sale/voucher',
        'sale/voucher_theme',
        'tool/backup',
        'tool/error_log',
        'tool/error_log_mercadolivre',
        'design/custom_field',
        'user/trocasenha',
        'extension/easyconfigure',
        'module/redirecionamento301',
        'marketplace/Marketplacecalls',
        'setting/store',
        'common/seo_url'
      );
      $ignoreModify = array(
        'common/home',
        'common/startup',
        'common/upload',
        'common/imagemanager',
        'common/recordmanager',
        'common/login',
        'common/logout',
        'common/forgotten',
        'common/nav',
        'common/reset',
        'common/notification',
        'error/not_found',
        'error/permission',
        'common/footer',
        'common/header',
        'catalog/filter',
        'catalog/option',
        'catalog/profile',
        'catalog/download',
        'catalog/filter',
        'module/preco_dinamico',
        'tool/backup',
        'catalog/category',
        'catalog/manufacturer',
        'catalog/product',
        'extension/openbay',
        'extension/manager',
        'localisation/tax_class',
        'localisation/tax_rate',
        'report/affiliate_commission',
        'report/sale_tax',
        'sale/affiliate',
        'sale/voucher',
        'sale/voucher_theme',
        'tool/backup',
        'tool/error_log',
        'tool/error_log_mercadolivre',
        'design/custom_field',
        'user/trocasenha',
        'extension/easyconfigure',
        'module/redirecionamento301',
        'common/seo_url'
      );
      if(defined('PREFIX_NAME')){
        $ignoreAccess[] = 'specific/'.PREFIX_NAME.'/common/nav';
        $ignoreModify[] = 'specific/'.PREFIX_NAME.'/common/nav';
      }
    } else {
      $ignoreAccess = array(
        'common/home',
        'common/startup',
        'common/upload',
        'common/imagemanager',
        'common/recordmanager',
        'common/login',
        'common/logout',
        'common/adsbanner',
        'common/manual',
        'common/forgotten',
        'common/reset',
        'common/notification',
        'common/nav',
        'catalog/download',
        'catalog/filter',
        'catalog/option',
        'catalog/profile',
        'error/not_found',
        'error/permission',
        'common/footer',
        'common/header',
        'extension/openbay',
        'extension/manager',
        'localisation/tax_class',
        'localisation/tax_rate',
        'report/affiliate_commission',
        'report/sale_tax',
        'sale/affiliate',
        'sale/voucher',
        'sale/voucher_theme',
        'tool/backup',
        'tool/error_log',
        'tool/error_log_mercadolivre',
        'design/custom_field',
        'user/trocasenha',
        'extension/easyconfigure',
        'marketplace/Marketplacecalls',
        'module/redirecionamento301',
        'setting/store',
        'common/seo_url'
      );
      $ignoreModify = array(
        'common/home',
        'common/startup',
        'common/upload',
        'common/imagemanager',
        'common/recordmanager',
        'common/login',
        'common/logout',
        'common/forgotten',
        'common/reset',
        'common/notification',
        'common/nav',
        'catalog/download',
        'catalog/filter',
        'catalog/option',
        'catalog/profile',
        'error/not_found',
        'error/permission',
        'common/footer',
        'common/header',
        'extension/openbay',
        'extension/manager',
        'localisation/tax_class',
        'localisation/tax_rate',
        'report/affiliate_commission',
        'report/sale_tax',
        'sale/affiliate',
        'sale/voucher',
        'sale/voucher_theme',
        'tool/backup',
        'tool/error_log',
        'tool/error_log_mercadolivre',
        'design/custom_field',
        'user/trocasenha',
        'extension/easyconfigure',
        'module/redirecionamento301',
        'common/seo_url'
      );
      if(defined('PREFIX_NAME')){
        $ignoreAccess[] = 'specific/'.PREFIX_NAME.'/common/nav';
        $ignoreModify[] = 'specific/'.PREFIX_NAME.'/common/nav';
      }
    }

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

    $this->language->load('user/user_permission');

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

    $paths = glob(DIR_APPLICATION . 'controller/*/*.php');

    if(defined('PREFIX_NAME')){
      $specific = glob(DIR_APPLICATION . 'controller/specific/'.PREFIX_NAME.'/*/*.php');
      $paths = array_merge($paths, $specific);
    }

    foreach ($paths as $path) {

      $arq = explode('/', $path);
      $pasta = substr(strrchr(dirname($path), '/'), 1);

      if($pasta == 'base'){
        continue;
      }

      if(defined('PREFIX_NAME') && in_array(PREFIX_NAME,$arq)){
        $caminho = 'specific/'.PREFIX_NAME.'/'.$pasta . '/' . basename($path, '.php');
      }else{
        $caminho = $pasta . '/' . basename($path, '.php');
      }

      if (!in_array($caminho, $ignoreAccess)) {
        $access = true;
      } else {
        $access = false;
      }

      if (!in_array($caminho, $ignoreModify)) {
        $modify = true;
      } else {
        $modify = false;
      }

      if ($access) {
        if(defined('PREFIX_NAME') && (is_file(strtolower(DIR_LANGUAGE.$this->language->getDirectory().'/'.$caminho.'.php')))){
          $this->load->language($caminho);
        }else{
          $this->load->language($caminho);
        }

        $this->data['groupnames'][$pasta] = $this->language->get('heading_title_'.$pasta);

        $this->data['arquivos'][$pasta][] = array(
          'teste' => $pasta,
          'value' => $caminho,
          'name' => ucwords(strip_tags($this->language->get('heading_title'))),
          'action' => array(
            'access' => $access,
            'modify' => $modify
          )
        );
      }
    }

    $permissionGroup = Type_PermissaoFuncao::getEnumList(true);

    foreach (Type_PermissaoFuncao::getEnumList() as $key => $value) {
      $this->data['arquivos'][$permissionGroup[$key]][] = array(
        'value' => $key,
        'name' => $value['title'],
        'description' => $value['description'],
        'action' => array(
          'access' => true,
          'modify' => false
        )
      );
    }

    if (isset($user_group_permission)){
      $permissionAccess = array_column(array_filter($user_group_permission, function ($value) {return $value['access'];}), 'permission');
      $permissionModify = array_column(array_filter($user_group_permission, function ($value) {return $value['modify'];}), 'permission');
    }

    if (isset($this->request->post['permission']['access'])) {
      $this->data['access'] = $this->request->post['permission']['access'];
    } elseif (isset($permissionAccess)) {
      $this->data['access'] = $permissionAccess;
    } else {
      $this->data['access'] = array();
    }

    if (isset($this->request->post['permission']['modify'])) {
      $this->data['modify'] = $this->request->post['permission']['modify'];
    } elseif (isset($permissionModify)) {
      $this->data['modify'] = $permissionModify;
    } else {
      $this->data['modify'] = array();
    }

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

    $this->response->setOutput($this->render('user/user_group_form'));
  }

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

    if ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 64)) {
      $this->error['name'] = $this->language->get('error_name');
    }

    $usergroup_info = $this->model_user_user_group->getGroupByGroupname($this->request->post['name']);

    if (!isset($this->request->get['user_group_id'])) {
      if ($usergroup_info) {
        $this->error['warning'] = $this->language->get('error_exists');
      }
    } else {
      if ($usergroup_info && ($this->request->get['user_group_id'] != $usergroup_info['user_group_id'])) {
        $this->error['warning'] = $this->language->get('error_exists');
      }
    }

    if (!$this->error) {
      return true;
    } else {
      return false;
    }
  }

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

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

    foreach ($this->request->post['selected'] as $user_group_id) {
      $user_total = $this->model_user_user->getTotalUsersByGroupId($user_group_id);

      if ($user_total) {
        $this->error['warning'] = sprintf($this->language->get('error_user'), $user_total);
      }
    }

    if (!$this->error) {
      return true;
    } else {
      return false;
    }
  }
}
