<?php 
final class DModelmercadolivremelipergunta extends Model {

	public function processAPIQuestions($tempoLimite = false){

		if(!$this->config->get('mercadolivre_status')){
			throw new Exception('Configuração de verificação de perguntas desabilitada!');
		}		

		$this->db->query("DELETE FROM `" . DB_PREFIX . "marketplace_api_call` WHERE tipo_integracao = " . Type_MarketPlace::Tp_Mercadolivre . " AND done = 1");
		$api_questions=$this->db->query("SELECT * FROM `".DB_PREFIX."marketplace_api_call` WHERE tipo_integracao = " . Type_MarketPlace::Tp_Mercadolivre . " AND callType='questions' and `done` = '0' ")->rows;
		 if($api_questions){

			$api_questions_group = array_chunk($api_questions, 50) ;
			 foreach ($api_questions_group as $key => $api_questions) {
				 try {
						 $this->db->startTransaction();
						 foreach($api_questions as $api_question){ 

								try{
									$questions 	 = $this->mercadolivre->getQuestions($api_question['callId']);
									$getquestion = $this->validaQuestion($api_question['callId']);

									/*a validação com status é para quando o anuncio que esta com a pergunta vinculada seja excluido
									  as perguntas vinculadas a ele sejam excluidas também.*/
									if(((!$questions) && ($getquestion)) || (($questions) && ($questions->status == Type_MercadoLivreQuestionStatus::Tp_ClosedUnanswered) )) {
										$this->deleteQuestion($api_question['callId']);
									}elseif($questions && $getquestion){
										$this->updateQuestion($questions);
									}elseif($questions && (!$getquestion)){
										$this->addQuestions($questions);
									}								
									
									$this->mercadolivre->raiseGlobalErrors();									
									$this->db->query("UPDATE `" . DB_PREFIX . "marketplace_api_call` SET done = '1' WHERE tipo_integracao = " . Type_MarketPlace::Tp_Mercadolivre . " AND callId = '" . $api_question['callId'] . "' and callType='" . $api_question['callType'] . "';");
								}catch (Exception $e){
									$this->mercadolivre->setErrorML('MERCADOLIVRE Questions API Error: '.$e);
									throw $e;
								}
						}
					 $this->db->commit();
				 }catch (Exception $e) {
						 $this->db->rollback();
				 }

         if (($tempoLimite) && (new DateTime($this->db->dataAtual()) > $tempoLimite)){
           break;
         }

			 }
		}
	}
	
	public function validaQuestion($questionid){

		$sql = "SELECT * FROM ".DB_PREFIX."mercadolivre_product_questions WHERE question_id = ".$questionid;

		$query = $this->db->query($sql);

		if($query->rows){
			return true;
		}else{
			return false;
		}
		
	}	
	
	public function addQuestions($question){

		$this->load->helper('ftr_geral');
		
		$userinfo = $this->mercadolivre->getUserInfo($question->from->id);

		$data = array(
			'mercaId'  				=> $this->db->escape($question->item_id),
			'question_id'			=> $this->db->escape($question->id),
			'pergunta' 				=> $this->db->escape($question->text),
			'data_criacao_pergunta' => $this->db->escape(ftr_geral::dateTimeZone($question->date_created)),
			'status_pergunta' 		=> $this->db->escape($question->status),
			'cli_nick_pergunta'		=> (isset($userinfo) && ($userinfo)) ? $userinfo->nickname : NULL,
			'cli_link'				=> (isset($userinfo) && ($userinfo)) ? $userinfo->permalink : NULL,
			'cli_address'			=> (isset($userinfo) && ($userinfo)) ? $userinfo->address->city.'/'.$userinfo->address->state : NULL
		);

		if(is_object($question->answer) && property_exists($question->answer, 'text')){
			$dataAnswer = array(
				'resposta' 							=> isset($question->answer) ? $this->db->escape($question->answer->text) : NULL,
				'status_resposta' 			=> isset($question->answer) ? $this->db->escape($question->answer->status) : NULL,
				'data_criacao_resposta'	=> isset($question->answer) ? $this->db->escape(ftr_geral::dateTimeZone($question->answer->date_created)) : NULL
			);
			$data = array_merge($data, $dataAnswer);
		}

		$sql = "INSERT INTO " . DB_PREFIX . "mercadolivre_product_questions SET ";

		foreach($data as $key => $value){
			$sql.= ' '.$key.' = "'.$value.'",' ;
		}
		
		$sql = substr($sql, 0, -1);

		$this->db->query($sql);
		
	}	

	public function deleteQuestion($questionid){

		$sql = "DELETE FROM ".DB_PREFIX."mercadolivre_product_questions WHERE question_id = ".$questionid;
		$this->db->query($sql);

	}	

	public function updateQuestion($questions){

		$this->deleteQuestion($questions->id);
		$this->addQuestions($questions);

	}

	public function addAnswer($data = array()){

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

		$sql = "UPDATE ".DB_PREFIX."mercadolivre_product_questions SET status_pergunta ='".$this->db->escape($data->status)."' , resposta = '".$this->db->escape($data->answer->text)."', status_resposta = '".$this->db->escape($data->answer->status)."', data_criacao_resposta = '".$this->db->escape(ftr_geral::dateTimeZone($data->answer->date_created))."' WHERE question_id = ".$this->db->escape($data->id)."";

		$this->db->query($sql);

	}


  
}