#!/perl/bin/perl.exe
$|=1;
#--------------------------------------------------------------------------------
#--------------------------------------------------------------------------------
# Information Software SA
# Date In: 2012-12-08
# Updates: 2012-12-08
# Author:Rodolfo Machon
# File Name: mora_cartera_sector_expedientes_p.pl
#------------------------------------------------------------------------- 
#-------------------------------------------------------------------------
# PERL MODULES
use CGI;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
use DBI;
use XML::Simple;
binmode STDOUT, ":encoding(utf8)";
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
# HTML PRINTING ACTIVATION
print "Content-type: text/html; charset=utf-8\n\n";
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
#GET PARAMETERS
$cgiparms      = new CGI;
$clase 	       = $cgiparms->param('clase');
$c11_sector_id = $cgiparms->param('c11_sector_id');
$v64_sector    = $cgiparms->param('v64_sector');
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# CHECK PARAMETERS
if ($clase eq ""){print "Your are not passing CLASE parameter<br>";}
if ($c11_sector_id eq ""){print "Your are not passing SECTOR parameter<br>";}
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
# OPEN DATABASE CONNECTIONS - ODBCs
get_app_data();
open_database_connections();
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# GLBAL VARIABLES
$PATH 		= "../".$lan."/";
$file       	= $lan."_mora_cartera_sector_expedientes_p.html";
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# PROGRAM DESCRIPTION
# PROCUREMENT
%expedientes  	       = get_expedientes();
%expedientes_direccion = get_expedientes_direccion();
%expedientes_mora      = get_expedientes_mora();
%expedientes_gestor    = get_expedientes_gestor();
# INTEGRATION
%expedientes_direccion_mora = get_expedientes_direccion_mora();
# PRESENTATION
$table 		   = construct_table();
construct_page();
exit;
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
#SUB-ROUTINES -> LEVEL 1
sub get_expedientes {
    my %hash  = ();
    my $sql = "";
    if($clase eq "inmueble"){
	$sql = "SELECT a.i8_".$clase."_id,c.v64_apellidos,c.v64_nombres
		  FROM sdm_".$clase."s a
		  LEFT JOIN sdd_".$clase."_contribuyentes b ON a.i8_".$clase."_id=b.i8_".$clase."_id
		  LEFT JOIN sdm_contribuyentes c ON b.i8_contribuyente_id=c.i8_contribuyente_id
		  WHERE a.c16_estado='ACEPTADO' AND a.c11_sector_id='$c11_sector_id'
		  GROUP BY a.i8_".$clase."_id";
    }
    if($clase eq "empresa"){
	$sql = "SELECT  a.i8_".$clase."_id,c.v64_apellidos,c.v64_nombres
		  FROM sdm_".$clase."s a
		  LEFT JOIN sdd_".$clase."_ubicacion b ON a.i8_".$clase."_id=b.i8_".$clase."_id
		  LEFT JOIN sdd_".$clase."_contribuyentess c ON a.i8_".$clase."_id=c.i8_".$clase."_id
		  LEFT JOIN sdm_contribuyentes d ON c.i8_contribuyente_id=d.i8_i8_contribuyente_id
		  WHERE a.c16_estado='ACEPTADO' AND b.c11_sector_id='$c11_sector_id'
		  GROUP BY a.i8_".$clase."_id";
    }
	my $sth = $dbh->prepare($sql);
	$sth->execute or die SQL_fail($sql,$dbh,'sub get_');
	while (my @row = $sth->fetchrow_array) {
        $hash{$row[0]} = [@row];
    }
    return %hash;
}
sub get_expedientes_direccion {
    my %hash  = ();
    my $tabla = "";
    if($clase eq "inmueble"){$tabla = "sdm_inmuebles"}
    if($clase eq "empresa"){$tabla = "sdd_empresa_ubicacion"}
    my $sql = "SELECT a.i8_".$clase."_id,
			b.v64_barrio,
			c.v64_poligono,
			d.v64_block,
			e.v64_calle,
			f.v64_avenida,
			g.v64_pasaje,
			h.v64_senda,
			a.c4_casa,
			i.v64_sector,
			j.v64_tipo_sector			
		 FROM ".$tabla." a
		 LEFT JOIN sdd_sector_barrios b ON a.c11_sector_id=b.c11_sector_id and a.c2_barrio_id=b.c2_barrio_id
		 LEFT JOIN sdd_sector_poligonos c ON a.c11_sector_id=c.c11_sector_id and a.c2_poligono_id=c.c2_poligono_id
		 LEFT JOIN sdd_sector_blocks d ON a.c11_sector_id=d.c11_sector_id and a.c2_block_id=d.c2_block_id
		 LEFT JOIN sdd_sector_calles e ON a.c11_sector_id=e.c11_sector_id and a.c4_calle_id=e.c4_calle_id
		 LEFT JOIN sdd_sector_avenidas f ON a.c11_sector_id=f.c11_sector_id and a.c4_avenida_id=f.c4_avenida_id
		 LEFT JOIN sdd_sector_pasajes g ON  a.c11_sector_id=g.c11_sector_id and a.c2_pasaje_id=g.c2_pasaje_id
		 LEFT JOIN sdd_sector_sendas h ON  a.c11_sector_id=h.c11_sector_id and a.c2_senda_id=h.c2_senda_id
		 LEFT JOIN sdm_sectores i ON a.c11_sector_id=i.c11_sector_id
		 LEFT JOIN sdm_tipo_sectores j ON a.i2_tipo_sector_id=j.i2_tipo_sector_id
		 WHERE a.c11_sector_id='$c11_sector_id'
		 ORDER BY a.i8_".$clase."_id";
	my $sth = $dbh->prepare($sql);
	$sth->execute or die SQL_fail($sql,$dbh,'sub get_');
	while (my @row = $sth->fetchrow_array) {
        my $dir   = "";
        if($row[1] ne ""){$dir .= "Barrio ".$row[1].","}
        if($row[2] ne ""){$dir .= "Poligono ".$row[2].","}
        if($row[3] ne ""){$dir .= "Block ".$row[3].","}
        if($row[4] ne ""){$dir .= "Calle ".$row[4].","}
        if($row[5] ne ""){$dir .= "Avenidad ".$row[5].","}
        if($row[6] ne ""){$dir .= "Pasaje ".$row[6].","}
        if($row[7] ne ""){$dir .= "Senda ".$row[7].","}
        if($row[8] ne ""){$dir .= "# ".$row[8].","}	
        $dir = $row[10]." ".$row[9].", ".$dir;
        $dir = substr($dir,0,length($dir)-1);
        $hash{$row[0]} = $dir;
    }
    return %hash;
}
sub get_expedientes_mora {
    my %hash  = ();
    if($clase eq "inmueble"){
        $sql = "SELECT a.i8_".$clase."_id,(sum(a.d82_val)+sum(a.d82_fie)+sum(a.d82_int)+sum(a.d82_mul))
		  FROM sdd_".$clase."_estados_mensuales a
		  INNER JOIN sdm_".$clase."s  b	on a.i8_".$clase."_id=b.i8_".$clase."_id
		  WHERE b.c11_sector_id='$c11_sector_id' and a.i4_dias_mora>0
		  GROUP BY a.i8_".$clase."_id";
    }
    if($clase eq "empresa"){
        $sql = "SELECT  a.i8_".$clase."_id,(sum(a.d82_val)+sum(a.d82_fie)+sum(a.d82_int)+sum(a.d82_mul))
		  FROM sdd_".$clase."_estados_mensuales a
		  INNER JOIN sdm_".$clase."s  b	ON a.i8_".$clase."_id=b.i8_".$clase."_id
		  INNER JOIN sdd_".$clase."_ubicacion c ON a.i8_".$clase."_id=c.i8_".$clase."_id
		  WHERE c.c11_sector_id='$c11_sector_id' and a.i4_dias_mora>0	
		  GROUP BY a.i8_".$clase."_id";
    }
	my $sth = $dbh->prepare($sql);
	$sth->execute or die SQL_fail($sql,$dbh,'sub get_');
	while (my @row = $sth->fetchrow_array) {
        $hash{$row[0]} = [@row];
    }
    return %hash;
}
sub get_expedientes_gestor {
    my %hash  = ();
    my $sql = "";
    if($clase eq "inmueble"){
	$sql = "SELECT a.i8_".$clase."_id,b.i8_gestor_id,b.v64_apellidos_gestor,b.v64_nombres_gestor
		  FROM sdm_".$clase."s a
		  LEFT JOIN sdd_".$clase."_gestores b ON a.i8_".$clase."_id=b.i8_".$clase."_id
		  WHERE a.c16_estado='ACEPTADO' AND a.c11_sector_id='$c11_sector_id' and b.c8_estado='ACTIVO'
		  ORDER BY a.i8_".$clase."_id";
    }
    if($clase eq "empresa"){
	$sql = "SELECT a.i8_".$clase."_id,b.i8_gestor_id,b.v64_apellidos_gestor,b.v64_nombres_gestor
		  FROM sdm_".$clase."s a
		  LEFT JOIN sdd_".$clase."_ubicacion b ON a.i8_".$clase."_id=b.i8_".$clase."_id
		  LEFT JOIN sdd_".$clase."_gestores c ON a.i8_".$clase."_id=c.i8_".$clase."_id
		  WHERE a.c16_estado='ACEPTADO' AND b.c11_sector_id='$c11_sector_id' and b.c8_estado='ACTIVO'
		  ORDER BY a.i8_".$clase."_id";
    }
	my $sth = $dbh->prepare($sql);
	$sth->execute or die SQL_fail($sql,$dbh,'sub get_');
	while (my @row = $sth->fetchrow_array) {
        $hash{$row[0]} = [@row];
    }
    return %hash;
}
sub get_expedientes_direccion_mora {
    my %hash  = ();
    foreach my $k (sort keys %expedientes){
        $hash{$k}{'apellidos'}  = $expedientes{$k}[1];
        $hash{$k}{'nombres'}	= $expedientes{$k}[2];	
        $hash{$k}{'direccion'}	= $expedientes_direccion{$k};
        $hash{$k}{'valor'}	= $expedientes_mora{$k}[1];
        $hash{$k}{'fiesta'}	= $expedientes_mora{$k}[2];
        $hash{$k}{'interes'}	= $expedientes_mora{$k}[3];
        $hash{$k}{'multa'}	= $expedientes_mora{$k}[4];
        $hash{$k}{'gestor_id'}	= $expedientes_gestor{$k}[1];
        $hash{$k}{'gestor'}	= $expedientes_gestor{$k}[2].", ".$expedientes_gestor{$k}[3];
    }
    return %hash;
}
sub construct_table {
    my $count   = 1;
    my $table   = "";
    my %tar_cue = ();    
    my %thead_h = ();
    my %tfoot_h = ();    
    my $thead_s = "";
    my $tfoot_s = "";    
    my $rowset  = "";
    my $thead   = "<thead><tr><td><input type=checkbox name=chk onClick=MarkAll()>No.</td><td>ID</td><td>APELLIDOS</td><td>NOMBRES</td><td>DIRECCION</td><td>VALOR</td><td>FIESTA</td><td>INTERES</td><td>MULTA</td><td>GESTOR ID</td><td>GESTOR NOMBRE</td></tr></thead>";
    my $tfoot   = "<tfoot><tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>TOTAL</td><td>{t_valor}</td><td>{t_fiesta}</td><td>{t_interes}</td><td>{t_multa}</td><td>&nbsp;</td></tr></tfoot>";    
    foreach my $k (sort keys %expedientes_direccion_mora){
	my $row   = "<td><input type=checkbox name=chk_$count>$count</td>
		     <td>".$k."</td>
		     <td>".$expedientes_direccion_mora{$k}{'apellidos'}."</td>
		     <td>".$expedientes_direccion_mora{$k}{'nombres'}."</td>
		     <td>".$expedientes_direccion_mora{$k}{'direccion'}."</td>
		     <td>".$expedientes_direccion_mora{$k}{'valor'}."</td>
		     <td>".$expedientes_direccion_mora{$k}{'fiesta'}."</td>
		     <td>".$expedientes_direccion_mora{$k}{'interes'}."</td>
		     <td>".$expedientes_direccion_mora{$k}{'multa'}."</td>
		     <td>".$expedientes_direccion_mora{$k}{'gestor_id'}."</td>
		     <td>".$expedientes_direccion_mora{$k}{'gestor'}."</td>";
	$rowset    .= "<tr>".$row."</tr>";
	$t_valor   += $sector_expendientes_mora{$k}{'valor'};
	$t_fiesta  += $sector_expendientes_mora{$k}{'fiesta'};
	$t_interes += $sector_expendientes_mora{$k}{'interes'};
	$t_multa   += $sector_expendientes_mora{$k}{'multa'};
	$count++;	
    }
    $t_valor   = sprintf("%.2f",$t_valor);
    $t_fiesta  = sprintf("%.2f",$t_fiesta);
    $t_interes = sprintf("%.2f",$t_interes);
    $t_interes = sprintf("%.2f",$t_interes);
    $tfoot     =~ s/\{t_valor}/$$t_valor/g;
    $tfoot     =~ s/\{t_fiesta}/$t_fiesta/g;
    $tfoot     =~ s/\{t_interes}/$t_interes/g;
    $tfoot     =~ s/\{t_multa}/$t_multa/g;		
    $rowset    = "<tbody>".$rowset."</tbody>";
    $table     = "<table id=grid>".$thead.$rowset.$tfoot."</table>";
    return $table;
}
sub construct_page {
    open (DATA, "$PATH$file");
    while ($line = <DATA>) {	
        $line =~ s/\{clase}/$clase/g;
        $line =~ s/\{city}/$city/g;
        $line =~ s/\{state}/$state/g;           
        $line =~ s/\{table}/$table/g;
        $line =~ s/\{c11_sector_id}/$c11_sector_id/g;
        $line =~ s/\{v64_sector}/$v64_sector/g;
        print "$line";
    }
}
#-------------------------------------------------------------------------
#AUXILIAR-SUBROUTINES
sub numeros {$a<=>$b}
sub get_app_data {
    my $schema  = "app.data.xml";
    my $xml     = new XML::Simple;
    my $data    = $xml->XMLin("../xml/".$schema);
    $appid	  = $data->{portal}->{app};
    $lan	  = $data->{portal}->{lang};
	$city	    = $data->{portal}->{city};
	$state      = $data->{portal}->{state};	
}
sub open_database_connections {
	$dbh 	= DBI->connect("dbi:ODBC:$appid",'','',{PrintError => 1, RaiseError => 1});
	if (!$dbh) {print "error: connection: $DBI::err\n$DBI::errstr\n$DBI::state\n";}
	$dbh->{LongReadLen} = 512 * 1024;	
}
sub SQL_fail {
    my ($query,$dbh,$section)= @_;
    print "SQL failed in Section $section<br>";
    print "Query: ".$query."<br>";    
    exit;
}
#-------------------------------------------------------------------------