<?php
//exit;

define('SF_ROOT_DIR', "/home/invergladi/public_html/gladis");
//define('SF_ROOT_DIR', "C://wamp/www/sinergia");
define('SF_APP',      'sys');
require_once(SF_ROOT_DIR.DIRECTORY_SEPARATOR."lib".DIRECTORY_SEPARATOR."functions".DIRECTORY_SEPARATOR."HelperHelper.php");
require_once(SF_ROOT_DIR.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.php');
require_once(SF_ROOT_DIR.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config_core_compile.php');
require_once(SF_ROOT_DIR.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR.'config_autoload.php');


$con= Conexion::getConexion();
$a_param = Conexion::getParamDbByAlias($apps);




if (!mysql_select_db($a_param['db'], $con)) {
    echo 'Could not select database';
    exit;
}

/*

$sql = "select IdPrestamo,MontoTotal,SaldoPrestamo,Estado,UsuarioCreacion 	
		from `cr_prestamo`
		where 1=1 -- SaldoPrestamo = 0
			-- and origen = 'R'
			and idPrestamo 
			and FechaInicio>='2017-01-01'
			and FechaInicio<='2018-01-01'
			";
	
$sql = "select IdPrestamo,MontoTotal,SaldoPrestamo,Estado,IdPrestamoReferencia,UsuarioCreacion 	
		from `cr_prestamo`
		where 1=1 
		
			and Estado = 'P'
and idPrestamo <= 8667 
			and eliminado=0
			
			
		";*/
echo $con."--";		
echo $sql;

$sql = "select IdPrestamo,MontoTotal,SaldoPrestamo,Estado,UsuarioCreacion 	
		from `cr_prestamo`
		where 1=1 and  estado = 'P'
						and eliminado='0'
			";

$result = mysql_query($sql,$con);

echo $result;



while($row = mysql_fetch_array($result)){
	$MontoTotal = round($row['MontoTotal'],2);
	$sqlP = "select Sum(MontoPago) as sumaPagos
			from `cr_pago`
			where IdPrestamo = '".$row['IdPrestamo']."' and tipoPago='1'
			
		";
	
	$result2 = mysql_query($sqlP,$con);
	echo "<table>";
	while($rowP = mysql_fetch_array($result2)){
				$SaldoPrestamo = round(round($MontoTotal,2) - round($rowP['sumaPagos'],2),2);
			
				$sqlU = "update `cr_prestamo`
							set 
							SaldoPrestamo = '".$SaldoPrestamo."',
							estado='P'
							where IdPrestamo = '".$row['IdPrestamo']."'
							
						";
				// echo $sqlU."<br>";
				// $resultU = mysql_query($sqlU,$con);
				
				$SaldoPrestamoA = round($row['SaldoPrestamo'],2);
				$SaldoPrestamo2 = round(round($MontoTotal,2) - round($rowP['sumaPagos'],2),2);
				if( $SaldoPrestamoA != $SaldoPrestamo2){
					echo $row['IdPrestamo']."--> ".$SaldoPrestamoA."= ".($SaldoPrestamo2)." <br>";
				}
				
			
					
					if($SaldoPrestamo2 == 0){
					
						$sqlU = "update `cr_prestamo`
							set Estado = 'C',
							SaldoPrestamo = '".$SaldoPrestamo."'
							where IdPrestamo = '".$row['IdPrestamo']."'
							
						";
						// echo "ccccccc->".$sqlU."<br>";
						// $resultU = mysql_query($sqlU,$con);
					}
					
			
			
		
		echo "</table>";
	}
}



?>