<?

$database = array('user'=>'gladis_peru',
			 'host'=>'localhost', 
			 'pass'=>'xvpolknmTY',
			  'db'=>'gladis_bd');
  
$link = mysql_connect($database['host'], $database['user'], $database['pass']);

$c = mysql_select_db($database['db'],$link);


$sql = "select IdPrestamo,MontoTotal,SaldoPrestamo,Estado,UsuarioCreacion 	
		from `cr_prestamo`
		where SaldoPrestamo > 0
			and origen = 'R'
			and eliminado=0
			
			
		";

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

while($row = mysql_fetch_array($result)){
	$MontoTotal = round($row['MontoTotal'],2);
	$sqlP = "select Sum(MontoPago) as sumaPagos
			from `cr_pago`
			where IdPrestamo = '".$row['IdPrestamo']."'
			
		";
	
	$result2 = mysql_query($sqlP,$link);
	echo "<table>";
	while($rowP = mysql_fetch_array($result2)){
		if(round($row['SaldoPrestamo'],2) == round(round($MontoTotal,2) - round($rowP['sumaPagos'],2),2)){
			if($row['Estado'] == 'C'){
				$sqlP = "select *
							from `cr_prestamo`
							where IdPrestamoReferencia = '".$row['IdPrestamo']."'
							
						";
					$result4 = mysql_query($sqlP,$link);
					
					if(mysql_num_rows($result4)==0){
						echo "<tr>";
						echo "<td>";
						echo $row['IdPrestamo'];
						echo "</td>";
						echo "<td>";
						echo $row['UsuarioCreacion'];
						echo "</td>";
						echo "<td>";
						echo $row['SaldoPrestamo'];	
						echo "</td>";
						echo "<td>";
						echo (round($MontoTotal,2) - round($rowP['sumaPagos'],2));	
						echo "</td>";
						echo "</tr>";
					}
			}
			/*if(round($MontoTotal,2) - round($rowP['sumaPagos'],2) == 0){
				if($row['Estado'] == 'C'){
					$sqlP = "select *
							from `cr_prestamo`
							where IdPrestamoReferencia = '".$row['IdPrestamo']."'
							
						";
					$result3 = mysql_query($sqlP,$link);
					
					if(mysql_num_rows($result3)==0){
						
						echo "<tr>";
						echo "<td>";
						echo $row['IdPrestamo'];
						echo "</td>";
						echo "<td>";
						echo $row['SaldoPrestamo'];	
						echo "</td>";
						echo "<td>";
						echo (round($MontoTotal,2) - round($rowP['sumaPagos'],2));	
						echo "</td>";
						echo "</tr>";
					}
				}
				$sqlU = "update `cr_prestamo`
							set SaldoPrestamo = '0.00'
							where IdPrestamo = '".$row['IdPrestamo']."'
							
						";
				$resultU = mysql_query($sqlU,$link);
				//echo $row['IdPrestamo']." ".$row['SaldoPrestamo']."---- ".(round($MontoTotal,2) - round($rowP['sumaPagos'],2))." <br>";
			}*/
			
			
			
			
		}
		echo "</table>";
	}
}

?>