<?php

class Cron{
	
	public function VerifyCron($pagseguro, $token, $id){
		
		include("../../plugins/PagSeguroLibrary/PagSeguroLibrary.php");		
		
		$vai = new MySQLDB();
		
		$credentials = new PagSeguroAccountCredentials(      
		    $pagseguro,       
		    $token      
		);  

		$sql = "SELECT `id`, `aluno_idaluno`, `notification_id`, `status` FROM `compra` WHERE `cliente_idcliente`=$id AND `status`!='PAID';";
		$result = $vai->ExecuteQuery($sql);

		while ($rows = mysql_fetch_object($result)) {

			/* Código identificador da transação  */    
			$transaction_id = $rows->notification_id;
			$idcompra = $rows->id;			
			$status = $rows->status;   
			$aluno_idaluno = $rows->aluno_idaluno;   			
	  
			$transaction = PagSeguroTransactionSearchService::searchByCode(  
	    		$credentials,  
	   	 		$transaction_id  
			);

			switch ($transaction->getStatus()->getValue()) {
			    case 1:
			        $trans = "WAITING_PAYMENT";
			        break;
			    case 2:
			        $trans = "IN_ANALYSIS";
			        break;
			    case 3:
			        $trans = "PAID";
			        break;
			    case 4:
			        $trans = "AVAILABLE";
			        break;
			    case 5:
			        $trans = "IN_DISPUTE";
			        break;			        			        
			    case 6:
			        $trans = "REFUNDED";
			        break;			        			        
			    case 7:
			        $trans = "CANCELLED";
			        break;			        			        			        			        
			}			
			
			if($status != $trans){
				$sql = "UPDATE `compra` SET `status`='$trans' WHERE `cliente_idcliente`=$id;";
				$vai->executeQuery($sql);								
				
				if($transaction->getStatus()->getValue() == 3){
					
					$data = date('Y-m-d');
					
					$sql = "SELECT `venda_id` FROM `compra_curso` WHERE `compra_id`=$idcompra;";
					$resulta = $vai->ExecuteQuery($sql);
					
					while ($rows = mysql_fetch_object($resulta)) {
						$sql = "INSERT INTO `aluno_venda` (`aluno_id`,`venda_id`, `liberacao`) 
								VALUES ($aluno_idaluno, $rows->venda_id, '$data');";
						$vai->executeQuery($sql);
					}					
				}	
			}								
		}
	}		
}

?>