#!/perl/bin/perl.exe
$|=1;
#--------------------------------------------------------------------------------
#--------------------------------------------------------------------------------
# Web Software SA
# Date In: 2016-05-13
# Updates: 2016-05-13
# Author:Rodolfo Machon
# File Name: recibo_expediente_s.pl
#------------------------------------------------------------------------- 
#-------------------------------------------------------------------------
# PERL MODULES
use CGI;
use Win32::ODBC;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
#------------------------------------------------------------------------- 
#-------------------------------------------------------------------------
# HTML PRINTING ACTIVATION
print "Content-type: text/html\n\n";
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
#GET PARAMETERS
$cgiparms 		= new CGI;
$lan	  		= $cgiparms->param('lan');
$appid	  		= $cgiparms->param('appid');
$gid	  		= $cgiparms->param('gid');
$eid	  		= $cgiparms->param('eid');
$rid	  		= $cgiparms->param('rid');
$dt_emision		= $cgiparms->param('dt_emision');
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# CHECK PARAMETERS
if ($lan eq ""){print "Your are not passing LAN parameter<br>";}
if ($gid eq ""){print "Your are not passing GID parameter<br>";}
if ($eid eq ""){print "Your are not passing EID parameter<br>";}
if ($rid eq ""){print "Your are not passing RID parameter<br>";}
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# GLBAL VARIABLES
$PATH 	    = "../".$lan."/";
$file       = $lan."_recibo_expediente_s.html";
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# GET CLASE SCHEMA AND VARIABLES
if (!($dbh  = new Win32::ODBC($appid))){connect_fail($appid)}
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# PROGRAM DESCRIPTION
# PROCUREMENT
$user			    = GetUser();
$uid 			    = buscar_usuario();
($emi_id,$caj_id)   = get_recibo();
%recibo_detalle	    = get_recibo_detalle();
%recibo_periodos    = put_recibo_periodos();
# INTEGRATION
#
# PRESENTATION
insert_recibo_pago();
construct_page();
exit;
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
#SUB-ROUTINES -> LEVEL 1
sub GetUser {
        local($username) = $ENV{"REMOTE_USER"};
        local($identify) = $ENV{"REMOTE_IDENT"};
        local($user) = $username || $identify;
        return($user);
}
sub buscar_usuario {
	my $user_id = "";
	my $sql		= "select a.i8_user_id from sdm_users a where a.`v16_login`='$user'";
	if($dbh->Sql($sql)){print "false";exit;}
	while( $dbh->FetchRow() ){
	      my @row1 = $dbh->Data();
	      $user_id=$row1[0];
	}
	return $user_id;
}
sub get_recibo {
	my $str     = "0";
    my $str1    = "0";
	my $sql		= "SELECT a.i8_emisor_id,a.i8_cajero_id FROM sdm_recibos a WHERE a.c16_recibo_id='$rid'";
	if($dbh->Sql($sql)){print "false";exit;}
	while( $dbh->FetchRow() ){
	      my @row = $dbh->Data();
	      $str  = $row[0];
	      $str1 = $row[1];          
	}
	if ($str  eq "") {$str = "0";}
	if ($str1 eq "") {$str1 = "0";}
	return $str,$str1;
}
sub get_recibo_detalle {
	my %hash = ();
	my $i    = 1;
	my $sql  = "SELECT 	b.c16_tarifa_id,
						b.v128_tarifa,
						b.d82_cantidad,
						b.d82_tarifa,
						b.txt_periodos
				FROM sdm_recibos a
				INNER JOIN sdd_recibos b ON a.c16_recibo_id=b.c16_recibo_id
				WHERE  a.c16_recibo_id='$rid'
                ";
	if ( $dbh->Sql($sql) ){SQL_fail($dbh,$sql,'sub get_recibos')};
	while($dbh->FetchRow()){
		my @row     = $dbh->Data();
		$hash{$i}	= [@row];
		$i++;
	}
	return %hash;
}
sub put_recibo_periodos{
	my %hash  = ();
	foreach my $k(sort keys %recibo_detalle){		
		$recibo_detalle{$k}[4] =~ s/\ //g;
		if($recibo_detalle{$k}[4] ne ""){
			my @pers = split(/\~/,$recibo_detalle{$k}[4]);
			for (my $i=0;$i<=$#pers;$i++){
				my @arr		= split(/\,/,$pers[$i]);
				my $trib	= substr($arr[2],0,8);
				$hash{$arr[0]}{$trib}{'DIM'} = $arr[1];
				$hash{$arr[0]}{$trib}{'TAR'} = $arr[2];				
				$hash{$arr[0]}{$trib}{'VAL'} = $arr[3];
				$hash{$arr[0]}{$trib}{'FIE'} = $arr[4];
				$hash{$arr[0]}{$trib}{'INT'} = $arr[5];
				$hash{$arr[0]}{$trib}{'MUL'} = $arr[6];
			}
		}
	}
	return %hash;
}
sub insert_recibo_pago {
    my $total   = 0;
    my $clase   = "";
	if ($gid eq "INM") {$clase = "inmueble"}
	if ($gid eq "EMP") {$clase = "empresa"}    
    foreach my $k (sort keys %recibo_periodos){
		foreach my $kk (sort keys %{$recibo_periodos{$k}}){
			my $sql				= "";
			my $c16_tarifa_id	= $recibo_periodos{$k}{$kk}{'TAR'};
			my $dias_mora		= $recibo_periodos{$k}{$kk}{'DIM'};
			my $d82_valor		= $recibo_periodos{$k}{$kk}{'VAL'};
			my $d82_fiesta		= $recibo_periodos{$k}{$kk}{'FIE'};
			my $d82_interes		= $recibo_periodos{$k}{$kk}{'INT'};
			my $d82_multa		= $recibo_periodos{$k}{$kk}{'MUL'};
			
			if ($d82_valor>0) {
				$sql  = "insert into sdd_".$clase."_abonos
						(i8_".$clase."_id,c8_tributo_id,c16_tarifa_id,i8_periodo,dt_abono,d82_abono,c3_tipo_abono_id,c16_recibo_id,
						c2_tipo_recibo_id,v64_abono_agencia,v64_abono_sucursal,c1_saldo,c1_balance_type,txt_comentario,i8_user_id,i8_emisor_id,i8_cajero_id,ts_in)
                        values('$eid','$kk','$c16_tarifa_id','$k','$dt_emision',$d82_valor,'VAL','$rid','IS','AMA','CENTRAL','N','A','AbonadoTesoreria','$uid','$emi_id','$caj_id',now())
					  ";
			    #print "$sql <br>";				
				if ( $dbh->Sql($sql) ) {SQL_fail($sql,$dbh,'insert')}
            }
			if ($d82_fiesta>0) {
				$sql = "insert into sdd_".$clase."_abonos
						(i8_".$clase."_id,c8_tributo_id,c16_tarifa_id,i8_periodo,dt_abono,d82_abono,c3_tipo_abono_id,c16_recibo_id,
						c2_tipo_recibo_id,v64_abono_agencia,v64_abono_sucursal,c1_saldo,c1_balance_type,txt_comentario,i8_user_id,i8_emisor_id,i8_cajero_id,ts_in)
                        values('$eid','$kk','$c16_tarifa_id','$k','$dt_emision',$d82_fiesta,'FIE','$rid','IS','AMA','CENTRAL','N','A','AbonadoTesoreria','$uid','$emi_id','$caj_id',now())
					  ";
			    #print "$sql <br>";				
				if ( $dbh->Sql($sql) ) {SQL_fail($sql,$dbh,'insert')}
			}
			if ($d82_interes>0) {
				$sql = "insert into sdd_".$clase."_abonos
						(i8_".$clase."_id,c8_tributo_id,c16_tarifa_id,i8_periodo,dt_abono,d82_abono,c3_tipo_abono_id,c16_recibo_id,
						c2_tipo_recibo_id,v64_abono_agencia,v64_abono_sucursal,c1_saldo,c1_balance_type,txt_comentario,i8_user_id,i8_emisor_id,i8_cajero_id,ts_in)
                        values('$eid','$kk','$c16_tarifa_id','$k','$dt_emision',$d82_interes,'INT','$rid','IS','AMA','CENTRAL','N','A','AbonadoTesoreria','$uid','$emi_id','$caj_id',now())
						  ";
			    #print "$sql <br>";				
				if ( $dbh->Sql($sql) ) {SQL_fail($sql,$dbh,'insert')}
			}
			if ($d82_multa>0) {
				$sql = "insert into sdd_".$clase."_abonos
						(i8_".$clase."_id,c8_tributo_id,c16_tarifa_id,i8_periodo,dt_abono,d82_abono,c3_tipo_abono_id,c16_recibo_id,
						c2_tipo_recibo_id,v64_abono_agencia,v64_abono_sucursal,c1_saldo,c1_balance_type,txt_comentario,i8_user_id,i8_emisor_id,i8_cajero_id,ts_in)
				  values('$eid','$kk','$c16_tarifa_id','$k','$dt_emision',$d82_interes,'MUL','$rid','IS','AMA','CENTRAL','N','A','AbonadoTesoreria','$uid','$emi_id','$caj_id',now())
					  ";
			    #print "$sql <br>";				
				if ( $dbh->Sql($sql) ) {SQL_fail($sql,$dbh,'insert')}
			}
			if ($dias_mora>0) {
				$sql = "insert into sdd_".$clase."_abonos
						(i8_".$clase."_id,c8_tributo_id,c16_tarifa_id,i8_periodo,dt_abono,d82_abono,c3_tipo_abono_id,c16_recibo_id,
						c2_tipo_recibo_id,v64_abono_agencia,v64_abono_sucursal,c1_saldo,c1_balance_type,txt_comentario,i8_user_id,i8_emisor_id,i8_cajero_id,ts_in)
				  values('$eid','$kk','$c16_tarifa_id','$k','$dt_emision',$dias_mora,'DIM','$rid','IS','AMA','CENTRAL','N','A','AbonadoTesoreria','$uid','$emi_id','$caj_id',now())
					  ";
			    #print "$sql <br>";				
				if ( $dbh->Sql($sql) ) {SQL_fail($sql,$dbh,'insert')}
			}            
		}
	}
}
sub construct_page {
	open (DATA, "$PATH$file");
	while ($line = <DATA>) {	
		$line =~ s/\{lan}/$lan/g;
		$line =~ s/\{appid}/$appid/g;
		$line =~ s/\{gid}/$gid/g;
		$line =~ s/\{eid}/$eid/g;
		$line =~ s/\{rid}/$rid/g;		 
		print "$line";
	}
}
#-------------------------------------------------------------------------
#AUXILIAR-SUBROUTINES
sub SQL_fail {
    my ($query,$dbh,$section)= @_;
    print "SQL failed in Section $section<br>";
    print "Error: ".$dbh->Error()."\n<br>";
    print "Query: ".$query."<br>";    
    $dbh->Close();
    exit;
}
sub connect_fail {
    my ($DSN)=@_;
    print "Error connecting to $DSN<br>";
    print "Error:".Win32::ODBC::Error()."<br>";
    exit;
}
sub round {
    my ($n, $places) = @_;
    my $abs = abs $n;
    my $val = substr($abs + ('0.' . '0' x $places . '5'),0,length(int($abs)) +(($places > 0) ? $places + 1 : 0));
    ($n < 0) ? "-" . $val : $val;
}
#-------------------------------------------------------------------------