<?php



/*

************************************************************************

Copyright [2013] [PagSeguro Internet Ltda.]



Licensed under the Apache License, Version 2.0 (the "License");

you may not use this file except in compliance with the License.

You may obtain a copy of the License at



http://www.apache.org/licenses/LICENSE-2.0



Unless required by applicable law or agreed to in writing, software

distributed under the License is distributed on an "AS IS" BASIS,

WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

See the License for the specific language governing permissions and

limitations under the License.

************************************************************************

*/



/**

* Class Controller Payment PagSeguro Notification

* Class responsible for receiving and handling of notifications sent by PagSeguro.

*/

class ControllerPaymentPagSeguroAbandoned extends Controller

{



	private $obj_xml;



	private $initialDate;



	private $finalDate;



	private $page;



	private $maxPageResults;



	public function index(){


		if($this->config->get('pagseguro_status')){

			$this->load->dmodel('setting/task');
			$this->load->type('tipocomum');
	
			$result =	$this->dmodel_setting_task->getTaskByType(Type_TaskUrl::Tp_TaskPagSegAbandonado);
			$time   = (($result['time_execution']*60) - 60);
			ini_set('max_execution_time', $time);				

			$data = array(
				'date_last_acting' => $this->db->dataAtual(),
				'type' => Type_TaskUrl::Tp_TaskPagSegAbandonado
			);
			$this->dmodel_setting_task->editDateTaskByType($data);				

			$this->_load();
			$this->_addPagSeguroLibrary();
			$this->_createDados();
			$this->_searchTransactionsAbandoned();
			$this->_updateOrderAbandoned();				
		}else{
			throw new Exception('Configuração de verificação de pedidos abandonados do pagseguro esta desabilitada!');
		}

	}



	/**

	* Load Model PagSeguro.

	*/

	private function _load(){

		$this->load->dmodel('checkout/order');

		$this->load->model('payment/pagseguro');

	}



	/**

	* Add Libary PagSeguro.

	*/

	private function _addPagSeguroLibrary(){

		include_once DIR_APPLICATION . 'controller/payment/PagSeguroLibrary/PagSeguroLibrary.php';

	}



	private function _createDados(){



		if  ((isset($_POST['date_initial'])) && (!empty($_POST['date_initial']))){

			$datainitial = explode('/', $_POST['date_initial']);

			$this->initialDate = date('c', mktime(00, 00, 00, $datainitial[1], $datainitial[0], $datainitial[2]));

		}else{

			$this->initialDate = date('c', mktime(00, 00,  00, date("m"), date("d")-3, date("Y")));

		}



		if  ((isset($_POST['date_ended'])) && (!empty($_POST['date_ended']))){

			$datainitial = explode('/', $_POST['date_ended']);

			$this->finalDate = str_replace('00', '59', date('c', mktime(23, 59, 59, $datainitial[1], $datainitial[0], $datainitial[2])));

		}else{

			$this->finalDate = str_replace('00', '59', date('c', mktime(23, 59,  59, date("m"), date("d")-1, date("Y"))));

		}



		$this->page = 1;

		$this->maxPageResults = 1000;

	}



	private function _searchTransactionsAbandoned(){



		$url =  'https://ws.pagseguro.uol.com.br/v2/transactions/abandoned?initialDate='.$this->initialDate.

		'&finalDate='.$this->finalDate.

		'&page='.$this->page.

		'&maxPageResults='.$this->maxPageResults.

		'&email='.$this->config->get('pagseguro_email').

		'&token='.$this->config->get('pagseguro_token').'';



		$this->obj_xml = $this->pagseguro->ConsultarPedidosAbandonados($url);

		$this->session->data['success'] = 'Pedidos Abandonados do Pagseguro Atualizados com Sucesso';

	}



	/**

	* Update table order and order_history

	* @param type $id_order_status

	*/

	private function _updateOrderAbandoned(){

		if(($this->obj_xml) &&  ($this->obj_xml->resultsInThisPage>0)){

			$this->load->dmodel('checkout/order');

			foreach($this->obj_xml->transactions->transaction as $order){

				$tz  				= new DateTimeZone('America/Sao_Paulo');
				$datapedido = new DateTime($order->date);				
				$datapedido->add(new DateInterval('P2D'));
				$datapedido->setTimeZone($tz);

				$datadia = DateTime::createFromFormat('Y-m-d H:i:s', date('Y-m-d H:i:s'));				
				$datadia->setTimeZone($tz);				

				if($datapedido > $datadia){
					return false;
				}				

				$order = $this->dmodel_checkout_order->getOrder($order->reference);
				if($order['order_status_id']==$this->config->get('pagseguro_awaiting_order_id')){
					$this->dmodel_checkout_order->update($order['order_id'], $this->config->get('pagseguro_abandoned_order_id'), '');
				}				
				/*$this->model_payment_pagseguro->updateOrder($order->reference, $this->config->get('pagseguro_abandoned_order_id'), $order->code);

				$this->model_payment_pagseguro->saveOrderHistory($order->reference, $this->config->get('pagseguro_abandoned_order_id'));*/

			}

		}

	}

}

