<?php

class ControllerModuleTask extends Controller
{

  private $error = array();
  private $configData = array();

  public function index()
  {

    $this->load->type('tipocomum');
    $this->load->helper('ftr_geral');
    $language = $this->load->language('module/task');

    $this->document->addScript(array(
      'view/javascript/page.task.js'
    ));

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

    $this->data['ftr_geral'] = new ftr_geral;
    $this->data['Type_TaskTypeGroup']   = $this->load->typeForTwig('Type_TaskTypeGroup');
    $this->data['Type_Status']          = $this->load->typeForTwig('Type_Status');
    $this->data['Type_TaskConfigTime']  = $this->load->typeForTwig('Type_TaskConfigTime');
    $this->data['Type_PreConfigTask']   = $this->load->typeForTwig('Type_PreConfigTask');

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

    $this->load->dmodel('setting/task');

    if (($this->request->server['REQUEST_METHOD'] == 'POST') && ($this->validate())) {


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


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

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

    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'] = '';
    }

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

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

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

    $tasks = $this->dmodel_setting_task->getTasks();

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

    $showMarketplaceLinks = $this->config->get('config_sistema_marketplace');
    $taskTypeGroupToIgnore = [
        Type_TaskTypeGroup::Tp_TaskMercadoLivre,
        Type_TaskTypeGroup::Tp_TaskSkyhub,
        Type_TaskTypeGroup::Tp_TaskGaleriaPage,
        Type_TaskTypeGroup::Tp_TaskShopee,
        Type_TaskTypeGroup::Tp_TaskMarketplace,
    ];
    $taskTypeGroupOrder = Type_TaskTypeGroup::getOthers();

    foreach ($tasks as $key => $task) {

      if(!$showMarketplaceLinks){
        //quando é so ecommerce ele esconde as tarefas dos marketplaces
        if(in_array($task['type_group'], $taskTypeGroupToIgnore)){
          continue;
        }
      }

      $status = array();
      $warning = "";

      switch ($key) {
        case Type_TaskConfigStatus::Tp_TaskVerificaPedidos :
          $status = array(
            'module' => true,
            'option' => $this->config->get(Type_TaskConfigStatus::getNickFromConstValue($key))
          );
          break;
        case Type_TaskConfigStatus::Tp_TaskVerificaNfe :
            $status = array(
              'module' => true,
              'option' => $this->config->get(Type_TaskConfigStatus::getNickFromConstValue($key))
            );
            break;
        case Type_TaskConfigStatus::Tp_TaskSendTask:
        case Type_TaskConfigStatus::TP_TaskDelTempfiles:
          $status = array(
            'module' => Type_TaskConfigStatus::getNickFromConstValue($key)
          );
          break;
        case Type_TaskConfigStatus::Tp_TaskMarketplaceSendStatus:
          $configKeys = explode('|', Type_TaskConfigStatus::getNickFromConstValue($key));
          $moduleStatus = false;
          foreach ($configKeys as $configKey) {
            if ($this->config->get($configKey)){
              $moduleStatus = true;
              break;
            }
          }
          $status = array(
            'module' => $moduleStatus
          );
          break;
        default:
          $status = array(
            'module' => $this->config->get(Type_TaskConfigStatus::getNickFromConstValue($key))
          );
      }

      $dominio = ($key == Type_TaskUrl::Tp_TaskShopLineSonda) ? true : false;

      if (is_null($task['predefined_execution'])) {
        $predefined_execution = Type_PreConfigTask::getNickFromValue(Type_PreConfigTask::Tp_PreConfigTask_Manual);
      } else {
        $predefined_execution = Type_PreConfigTask::getNickFromValue($task['predefined_execution']);
      }

      $this->data['tasks'][$task['type_group']]['task'][] = array(
        'task_id' => $task['taskcontrol_id'],
        'url' => $this->urlloja->link(Type_TaskUrl::getNickFromValue($key), '', 'SSL', !$dominio, $dominio),
        'type' => $key,
        'status' => $status,
        'date_last_acting' => is_null($task['date_last_acting']) ? '' : ftr_geral::formatDate($task['date_last_acting'], 'br', true),
        'time_execution' => $task['time_execution'],
        'time_default' => $task['time_default'],
        'description' => $task['description'],
        'warning' => $warning,
        'predefined_execution' => $predefined_execution,
      );

    }

    foreach ($this->data['tasks'] as $key => $value){
        $this->data['tasks'][$key]['group'] = $key;
        $this->data['tasks'][$key]['order'] = $taskTypeGroupOrder[$key];
    }

    function compara($a, $b)
    {
        return (($a['order'] > $b['order']) ? 1 : -1);
    }

    usort($this->data['tasks'], "compara");

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

    $this->response->setOutput($this->render('module/task'));
  }

  private function validate()
  {

    $this->load->language('module/task');

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

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

  public function save()
  {

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

    $json = array();

    if (isset($this->request->post['task_id'])) {
      $task_id = $this->request->post['task_id'];
    } else {
      $json['error'] = 'Id\'\s das tarefas não encontrados';
    }

    if (isset($this->request->post['status'])) {
      $status = $this->request->post['status'];
    } else {
      $json['error'] = 'Status das tarefas não encontrados';
    }

    if (isset($this->request->post['time_execution'])) {
      $time_execution = $this->request->post['time_execution'];
    } else {
      $json['error'] = 'Tempo de execução não encontrado';
    }

    if (isset($this->request->post['type'])) {
      $type = $this->request->post['type'];
    } else {
      $json['error'] = 'Tipo não encontrado';
    }

    if (!$json) {

      $this->load->dmodel('setting/task');

      $data = array();

      foreach ($task_id as $key => $value) {

        $key_time_execution =  array_search($value, array_column($time_execution, 'control_id'));

        $data[] = array(
          'task_id' => $value,
          'time_execution' => isset($time_execution[$key_time_execution]) ? $time_execution[$key_time_execution]['value'] : 0
        );

        switch ($type[$key]) {
          case Type_TaskUrl::Tp_TaskVerificaPedidos:
            $this->load->model('setting/setting');
            $setting = array(
              'config_verifica_pedidos' => $status[$key]
            );
            $this->model_setting_setting->editSettingForKey('task', $setting);
            break;
          case Type_TaskUrl::Tp_TaskVerificaNfe:
            $this->load->model('setting/setting');
            $setting = array(
              'config_verifica_notafiscal' => $status[$key]
            );
            $this->model_setting_setting->editSettingForKey('task', $setting);
            break;
        }

      }

      try {
        $this->dmodel_setting_task->editAllTasks($data);
        $this->session->data['success'] = 'Controle de tarefas salvo com sucesso!';
        $json['redirect'] = str_replace('&amp;', '&', $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info='.Type_TitleModules::Tp_Config, 'SSL'));
      } catch (Exception $e) {
        $json['error'] = 'Erro ao salvar as url, tente novamente mais tarde.';
      }

    }

    $this->response->setOutputJson($json);

  }

}
