<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Crons extends CI_Controller {
   
	public function __construct(){
        parent::__construct();
        $this->QuerySize = 1000;
		uses_functions('phone');
    }


	public function index()
    {
        $max = date('i:59');
		define('MAX_VALIDATION_PAYOUT_MOBILE',24*3600);
		define('MAX_VALIDATION_PAYOUT_BANK',72*24*3600);
		define('MAX_VALIDATION_PAYIN_MOBILE',24*3600);

		

		$min = date('i:s');

			$min = date('i:s');
			/*
			$query = "delete from transactions where (montant = 0 or montant is null) and lower(statut)='failed'";
			
			$this->db->query($query);
			$query = "delete from curls order by id limit 1000";
			
			//$this->db->query($query);
			$query = "delete from logs order by id limit 1000";
			
			//$this->db->query($query);*/
			
			
			$query = "select transactions.* from transactions left join webservices on webservices.service_code = transactions.service_code where lower(transactions.status) = 'pending'  order by date_created DESC limit ".$this->QuerySize."";
			
			$traitement = $this->db->query($query)->result_array();
			
			uses_class('finance');
			$finance = new finance();//
			
			if(empty($traitement)) $traitement = array();
			else
			{
				foreach($traitement as $line)
				{
					unset($status);	
					

					
					$DELTA = strtotime(datetime())-strtotime($line['date_created']);
					
					$temoin = substr($line['transaction_id'],0,3);
					
					$status = strtoupper($finance->getStatus($line));
					
					if(empty($status)) $status = "PENDING";
	
					if($status=='PENDING')
					{
						
						switch($temoin)
						{
							case 'POM':
								if($DELTA>MAX_VALIDATION_PAYOUT_MOBILE)
								{
									$status = "SUCCESS";
									$this->db->query("update transactions set compensated = 1 where transaction_id = '".$line['transaction_id']."'");
								}
								
								
							break;
							case 'PIM':
	
								if($DELTA>MAX_VALIDATION_PAYIN_MOBILE)
								{
									$status = "FAILED";
									$this->db->query("update transactions set compensated = 1 where transaction_id = '".$line['transaction_id']."'");
								}
								
								

							break;
							case 'POB':
	
								if($DELTA>MAX_VALIDATION_PAYOUT_BANK)
								{
									$status = "SUCCESS";
									$this->db->query("update transactions set compensated = 1 where transaction_id = '".$line['transaction_id']."'");
								}
								
								
							break;
							case 'REV':
							case 'APP':
							case 'PTP':
							case 'POT':
									if($DELTA>MAX_VALIDATION_PAYOUT_BANK)
									{
										$status = "FAILED";
										$this->db->query("update transactions set compensated = 1 where transaction_id = '".$line['transaction_id']."'");
									}
									
									
							break;
						}
					}
					
					
					if($status!='PENDING')
					{
						$finance->valideTransaction($status,$line);
					}
					
				}
			}

	}
}