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

  public function index(){

    $this->load->model('mercadolivre/mercadolivre');
    $this->load->model('catalog/product');
    $this->load->type('tipocomum');
    $this->load->helper('ftr_geral');
    $this->load->dmodel('mercadolivre/meliproduto');

    $language = $this->load->language('module/mercadolivre');
    $this->data = array_merge($language, $this->data);

    $this->getList();
  }


	public function getLinkUrl($request, $remove=array()){
		$url = '';

		foreach ($remove as $key => $value) {
			unset($request[$value]);
		}

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

            if (isset($request['type'])) {
              $url .= '&type=' . $request['type'];
        }

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

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

        if(isset($request['filter_mercaid'])){
          $url .= '&filter_mercaid='.$request['filter_mercaid'];
        }

        if(isset($request['filter_model'])){
          $url .= '&filter_model='.$request['filter_model'];
        }

        if(isset($request['filter_data_start'])){
          $url .= '&filter_data_start='.$request['filter_data_start'];
        }

        if(isset($request['filter_data_end'])){
          $url .= '&filter_data_end='.$request['filter_data_end'];
        }

        if(isset($request['filter_question_status'])){
          $url .= '&filter_question_status='.$request['filter_question_status'];
        }

        return $url;
  }

  public function getList(){

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

    $this->data['token'] = $this->session->data['token'];
    $this->data['type'] = $this->request->get['type'];

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

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

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

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

    $this->data['url'] = array(
      'cancel'       => $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL'),
      'clear_filter' => $this->url->link('module/mercadolivre/question', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL'),
      'retorno'      => $this->url->link('module/mercadolivre/question', 'token='.$this->session->data['token'].$this->getLinkUrl($this->request->get), 'SSL')
    );

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

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

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

    if (isset($this->request->get['sort'])) {
        $filter_sort = $this->request->get['sort'];
    } else {
        $filter_sort = 'sort_unanswered' ;
    }

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

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

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

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

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

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

    $this->load->model('mercadolivre/questions');

    $data = array(
      'start'                  => ($page - 1) * $this->config->get('config_admin_limit'),
      'limit'                  => $this->config->get('config_admin_limit') ,
      'order'                  => $filter_order,
      'sort'                   => $filter_sort,
      'filter_mercaid'         => $filter_mercaid,
      'filter_content_model'   => $filter_content_model,
      'filter_model'           => $filter_model,
      'filter_data_start'      => ftr_geral::formatDate($filter_data_start,'en'),
      'filter_data_end'        => ftr_geral::formatDate($filter_data_end,'en'),
      'filter_question_status' => $filter_question_status
    );

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

    $questions = $this->model_mercadolivre_questions->getQuestionsList($data);

    foreach ($questions as $key => $question) {

        $type = ftr_geral::isIsset($this->config->get('config_product_code')) ? $this->config->get('config_product_code') : Type_ListCodProduct::Tp_CodReferencia ;
        switch ($type) {
            case Type_ListCodProduct::Tp_CodReferencia:
            $model = $question['model'];
            break;
            case Type_ListCodProduct::Tp_CodProdEcommerce:
            $model = $question['product_id'];
            break;
            case Type_ListCodProduct::Tp_CodProdFuturaServer:
            $model = $question['id_futura'];
            break;
            case Type_ListCodProduct::Tp_CodBarras:
            $model = $question['codigo_barra'];
            break;
            default:
            $model = $question['model'];
        }

        $this->data['questions'][] = array(
            'mercaId'         => $question['marketId'],
            'name'            => $question['name'],
            'list_question'   => sprintf($this->language->get('text_list_question'), $question['respondidas'], $question['total_questions']),
            'product_id'      => $model,
            'href'          => $this->url->link('module/mercadolivre/question/info', 'token='.$this->session->data['token'].'&mercaid='.$question['marketId'].'&type='.$this->request->get['type'], 'SSL')
        );
    }

    $question_total = $this->model_mercadolivre_questions->getQuestionsTotalList($data);

	$pagination        = new Pagination();
	$pagination->total = $question_total;
	$pagination->page  = $page;
	$pagination->limit = $this->config->get('config_admin_limit');
	$pagination->text  = $this->language->get('text_pagination');
    $pagination->url   = $this->url->link('module/mercadolivre/question', 'token=' . $this->session->data['token'] . $this->getLinkUrl($this->request->get, ['page']) . '&page={page}', 'SSL');

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

    $this->data['filter'] = array(
      'sort'   => $filter_sort,
      'order'  => $filter_order,
      'count'  => count(explode('&', $this->getLinkUrl($this->request->get, ['page','type', 'sort', 'order']))) - 1,
      'filter' => $this->getLinkUrl($this->request->get, ['type','sort','order'])
    );

    $this->data['filter_mercaid']         = $filter_mercaid;
    $this->data['filter_content_model']   = $filter_content_model;
    $this->data['filter_model']           = $filter_model;
    $this->data['filter_data_start']      = $filter_data_start;
    $this->data['filter_data_end']        = $filter_data_end;
    $this->data['filter_question_status'] = $filter_question_status;

    $this->data['select_sort_by']  = $this->getSortOrder($filter_sort);
    $this->data['select_order_by'] = $this->getOrder($filter_order, $filter_sort);

		$contentTotal = Type_FilterContent::getEnumList();
		foreach ($contentTotal as $key => $value) {
			$this->data['content_model'][] = array(
				'content_model_id' 		 => $key,
				'content_model_name' 	 => $value,
				'content_model_status' => isset($this->request->get['filter_content_model']) ? ftr_geral::isSelected($key, $this->request->get['filter_content_model']) : false
      );
    }

    $contentQuestions = Type_MercadoLivreQuestionStatus::getEnumList();
    foreach ($contentQuestions as $key => $value) {
      if(in_array($key, [Type_MercadoLivreQuestionStatus::Tp_Answered, Type_MercadoLivreQuestionStatus::Tp_Unanswered])){
        $this->data['contentQuestions'][] = array(
          'content_question_id'     => $key,
          'content_question_name'   => $value,
          'content_question_status' => isset($this->request->get['filter_question_status']) ? ftr_geral::isChecked($key, $this->request->get['filter_question_status']) : false
        );
      }
    }

    $this->template = 'module/mercadolivre/question_list.twig';

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

    $this->response->setOutput($this->render());

  }

  public function getForm(){

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

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

    $this->data['token'] = $this->session->data['token'];
    $this->data['type'] = $this->request->get['type'];

    $this->document->addScript(array(
      'view/javascript/mercadolivre.question.js',
      'view/javascript/answers.js'
    ));

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

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

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

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

    $this->data['url'] = array(
      'cancel'       => $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL'),
      'clear_filter' => $this->url->link('module/mercadolivre/question', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL'),
      'retorno'      => $this->url->link('module/mercadolivre/question', 'token='.$this->session->data['token'].$this->getLinkUrl($this->request->get), 'SSL'),
      'answer'       => $this->url->link('module/mercadolivre/question/answer', 'token='.$this->session->data['token'], 'SSL')
    );

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

    $this->load->model('mercadolivre/questions');

  	$mercaid = isset($this->request->get['mercaid']) ? $this->request->get['mercaid'] : NULL ;
    $questionsInfo = $this->model_mercadolivre_questions->getQuestionInfo($mercaid);

    $this->data['questionsInfo'] = array_merge($questionsInfo,
    ['linkprod' => $this->url->link('catalog/product/update', 'token='.$this->session->data['token'].'&product_id='.$questionsInfo['product_id'], 'SSl')]
    );

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

    $questions = $this->model_mercadolivre_questions->getQuestions($data);

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

    foreach ($questions as $key => $value) {
      $this->data['questions'][] = array(
        'product_question_id'   => $value['product_question_id'],
        'mercaId'               => $value['mercaId'],
        'question_id'           => $value['question_id'],
        'pergunta'              => $value['pergunta'],
        'data_criacao_pergunta' => ftr_geral::formatDate($value['data_criacao_pergunta_cast'], 'br'),
        'status_pergunta'       => $value['status_pergunta'],
        'resposta'              => $value['resposta'],
        'data_criacao_resposta' => ftr_geral::formatDate($value['data_criacao_resposta_cast'], 'br'),
        'status_resposta'       => $value['status_resposta'],
        'cli_nick_pergunta'     => $value['cli_nick_pergunta'],
        'cli_link'              => $value['cli_link'],
        'cli_address'           => $value['cli_address']
      );
    }

    $questions_total = $this->model_mercadolivre_questions->getQuestionsTotal($data);

    $url = $this->getLinkUrl(['page']);
		$pagination        = new Pagination();
		$pagination->total = $questions_total;
		$pagination->page  = $page;
		$pagination->limit = $this->config->get('config_admin_limit');
		$pagination->text  = $this->language->get('text_pagination');
    $pagination->url   = $this->url->link('module/mercadolivre/question/info', 'token=' . $this->session->data['token'].'&type='.$this->request->get['type'].'&mercaid='.$mercaid.$url . '&page={page}', 'SSL');

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

    $this->data['urlAjax'] = array(
      'delete' => $this->url->link('module/mercadolivre/question/delete', 'token=' . $this->session->data['token'], 'SSL')
    );

    $this->template = 'module/mercadolivre/question_info.twig';

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

    $this->response->setOutput($this->render());

  }

	public function info() {
    $this->load->model('mercadolivre/mercadolivre');
    $this->load->model('catalog/product');
    $this->load->helper('ftr_geral');
    $this->load->dmodel('mercadolivre/meliproduto');

    $language = $this->load->language('module/mercadolivre');
    $this->data = array_merge($language, $this->data);


		$this->getForm();
  }

  public function delete(){

    $this->load->language('module/mercadolivre');
    $this->load->dmodel('mercadolivre/melipergunta');

    $json = array();

    if($this->request->post['question_id']){
      $question_id = $this->request->post['question_id'];
    }else{
      $json['warning'] = $this->language->get('error_question_id');
    }

    if(!$json){
      try{
        $result = $this->mercadolivre->deleteQuestion($question_id);
        if($result){
          $this->dmodel_mercadolivre_melipergunta->deleteQuestion($question_id);
          $json['success'] = true ;
        }else{
          throw new exception("Não foi possível deletar a pergunta!");
        }
      }catch(Exception $e){
        $json['warning'] = $this->language->get('error_question_id');
        $this->mercadolivre->setErrorML('MERCADOLIVRE Delete Questions API Error: '.$e);
      }
    }

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

  }

  public function answer(){

    $this->load->language('module/mercadolivre');
    $this->load->helper('ftr_geral');
    $this->load->dmodel('mercadolivre/melipergunta');

    $json = array();

    if($this->request->post['question_id']){
      $question_id = $this->request->post['question_id'];
    }else{
      $json['warning'] = $this->language->get('error_question_id');
    }

    if($this->request->post['answer']){
      $answer = $this->request->post['answer'];
    }else{
      $json['warning'] = $this->language->get('error_answer');
    }

    if(!$json){

      $data = array(
        'question_id'   => $question_id,
        'resposta'      => $answer,
      );

      try{
        $results = $this->mercadolivre->answerQuestion($data);
        if($results){
          $this->dmodel_mercadolivre_melipergunta->addAnswer($results);
          $json['success'] = true    ;
          $json['answer']  = $results->answer->text ;
          $json['data']    = ftr_geral::formatDate(ftr_geral::dateTimeZone($results->answer->date_created), 'br', true) ;
        }else{
          throw new exception("Pergunta não encontrada para vincular a resposta!");
        }
      }catch(Exception $e){
        $json['warning'] = $this->language->get('error_answer');
        $this->mercadolivre->setErrorML('MERCADOLIVRE Answer Questions API Error: '.$e);
      }
    }

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

  }

  public function getSortOrder($filter_sort){

    $ignore = array('sort', 'page');

    $select_sort_by = array();

    $select_sort_by[] = array(
      'text'     => 'Perguntas não respondidas',
      'value'    => 'sort_unanswered',
      'selected' => (isset($filter_sort) && ($filter_sort=='sort_unanswered')) ? 'selected' : '',
      'type'     => 'number',
      'href'     => $this->url->link('module/mercadolivre/question', 'token='.$this->session->data['token'].$this->getLinkUrl($this->request->get, $ignore).'&sort=sort_unanswered', 'SSL')
    );

    $select_sort_by[] = array(
      'text'     => 'Nome do Produto',
      'value'    => 'sort_name',
      'selected' => (isset($filter_sort) && ($filter_sort=='sort_name')) ? 'selected' : '',
      'type'     => 'text',
      'href'     => $this->url->link('module/mercadolivre/question', 'token='.$this->session->data['token'].$this->getLinkUrl($this->request->get, $ignore).'&sort=sort_name', 'SSL')
    );

    $select_sort_by[] = array(
      'text'     => 'Quantidade de perguntas',
      'value'    => 'sort_qtd',
      'selected' => (isset($filter_sort) && ($filter_sort=='sort_qtd')) ? 'selected' : '',
      'type'     => 'number',
      'href'     => $this->url->link('module/mercadolivre/question', 'token='.$this->session->data['token'].$this->getLinkUrl($this->request->get, $ignore).'&sort=sort_qtd', 'SSL')
    );

    return $select_sort_by;

  }

  public function getOrder($filter_order, $filter_sort){

    $ignore = array('order', 'page');

    $arrayOrderType = array(
      'text'   => array('sort_name'),
      'number' => array('sort_unanswered', 'sort_qtd')
    );

    $select_order_by = array();

    $select_order_by[] = array(
      'type'    => 'text',
      'text'    => 'de A a Z',
      'checked' =>  (isset($filter_order) && ($filter_order=='ASC') && in_array($filter_sort, $arrayOrderType['text'])) ? 'checked' : '',
      'value'   => 'ASC',
      'href'    => $this->url->link('module/mercadolivre/question', 'token='.$this->session->data['token'].$this->getLinkUrl($this->request->get, $ignore).'&order=ASC', 'SSL')
    );

    $select_order_by[] = array(
      'type'    => 'text',
      'text'    => 'de Z a A',
      'checked' =>  (isset($filter_order) && ($filter_order=='DESC') && in_array($filter_sort, $arrayOrderType['text'])) ? 'checked' : '',
      'value'   => 'DESC',
      'href'    => $this->url->link('module/mercadolivre/question', 'token='.$this->session->data['token'].$this->getLinkUrl($this->request->get, $ignore).'&order=DESC', 'SSL')
    );

    $select_order_by[] = array(
      'type'    => 'number',
      'text'    => 'Crescente',
      'checked' =>  (isset($filter_order) && ($filter_order=='ASC') && in_array($filter_sort, $arrayOrderType['number'])) ? 'checked' : '',
      'value'   => 'ASC',
      'href'    => $this->url->link('module/mercadolivre/question', 'token='.$this->session->data['token'].$this->getLinkUrl($this->request->get, $ignore).'&order=ASC', 'SSL')
    );

    $select_order_by[] = array(
      'type'    => 'number',
      'text'    => 'Decrescente',
      'checked' =>  (isset($filter_order) && ($filter_order=='DESC') && in_array($filter_sort, $arrayOrderType['number'])) ? 'checked' : '',
      'value'   => 'DESC',
      'href'    => $this->url->link('module/mercadolivre/question', 'token='.$this->session->data['token'].$this->getLinkUrl($this->request->get, $ignore).'&order=DESC', 'SSL')
    );

    return $select_order_by;
  }


}
