#!/perl/bin/perl.exe
$|=1;
#--------------------------------------------------------------------------------
#--------------------------------------------------------------------------------
# Information Software SA
# Date In: 2013-01-09
# Updates: 2013-01-09
# Author:Rodolfo Machon
# File Name: administrativos_sector_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');
$boton    	= $cgiparms->param('boton');
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# 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."_administrativos_sector_p.html";
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# PROGRAM DESCRIPTION
# PROCUREMENT
($amis,$admi,$judi)	    = get_tipo_notificaciones();
%expedientes_notificaciones = get_expedientes_notificaciones();
if (keys %expedientes_notificaciones) {
	%expedientes  	       = get_expedientes();
	%expedientes_direccion = get_expedientes_direccion();
	# INTEGRATION
	%sector_notificaciones = get_sector_notificaciones();
	# PRESENTATION
	$table 		   = construct_table();
}
construct_page();
exit;
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
#SUB-ROUTINES -> LEVEL 1
sub get_tipo_notificaciones {
    my $ami   = "";
    my $adm   = "";
    my $jud   = "";
    my %hash  = ();
    my $sql = "SELECT a.i2_tipo_notificacion_id,
			a.v64_tipo_notificacion
		 FROM sdm_tipo_notificaciones a
		 WHERE a.c2_tipo_proceso_id='CD'
		 ";
	my $sth = $dbh->prepare($sql);
	$sth->execute or die SQL_fail($sql,$dbh,'sub get_sector');
	while (my @row = $sth->fetchrow_array) {
		if($row[0]>0 && $row[0]<20){$ami .= "<li>".$row[0].". ".$row[1]."<li>";}
		if($row[0]>=20 && $row[0]<30){$adm .= "<li>".$row[0].". ".$row[1]."<li>";}
		if($row[0]>=30 && $row[0]<40){$jud .= "<li>".$row[0].". ".$row[1]."<li>";}
    }
    $ami = "<ul>".$ami."</ul>";
    $adm = "<ul>".$adm."</ul>";
    $jud = "<ul>".$jud."</ul>";
    return $ami,$adm,$jud;
}
sub get_expedientes_notificaciones {
    my %hash  = ();
    my $table = "";
    if($clase eq "inmueble"){$table = "sdm_".$clase."s"}
    if($clase eq "empresa"){$table = "sdd_".$clase."_ubicacion"}
    my $sql = "SELECT a.i8_".$clase."_id,
			SUM(IF(a.i2_tipo_notificacion_id='20',1,0)),
			SUM(IF(a.i2_tipo_notificacion_id='21',1,0)),
			SUM(IF(a.i2_tipo_notificacion_id='22',1,0))
		 FROM `sdd_".$clase."_administrativo` a
		 LEFT JOIN $table b ON a.i8_".$clase."_id=b.i8_".$clase."_id
		 INNER JOIN sdd_".$clase."_procesos c ON a.i8_".$clase."_id=c.i8_".$clase."_id
		 WHERE b.c11_sector_id='$c11_sector_id' and c.c8_estado='ABIERTO'
		 GROUP BY a.i8_".$clase."_id
		 ORDER BY a.i8_".$clase."_id";
	my $sth = $dbh->prepare($sql);
	$sth->execute or die SQL_fail($sql,$dbh,'sub get_sector');
	while (my @row = $sth->fetchrow_array) {
		$hash{$row[0]} = [@row];
    }
    return %hash;
}
sub get_expedientes {
    my $str   = ();
    my %hash  = ();
    my $sql = "";
    foreach my $k (sort keys %expedientes_notificaciones){$str .= "'".$k."',"}
    $str = substr($str,0,length($str)-1);    
    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.i8_".$clase."_id IN ($str)
		  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  a.i8_".$clase."_id IN ($str)
		  GROUP BY a.i8_".$clase."_id";
    }
	my $sth = $dbh->prepare($sql);
	$sth->execute or die SQL_fail($sql,$dbh,'sub get_sector');
	while (my @row = $sth->fetchrow_array) {
		$hash{$row[0]} = [@row];
    }
    return %hash;
}
sub get_expedientes_direccion {
    my $str   = ();
    my %hash  = ();
    my $tabla = "";
    foreach my $k (sort keys %expedientes_notificaciones){$str .= "'".$k."',"}
    $str = substr($str,0,length($str)-1);    
    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.i8_".$clase."_id IN ($str)
		 ORDER BY a.i8_".$clase."_id";
	my $sth = $dbh->prepare($sql);
	$sth->execute or die SQL_fail($sql,$dbh,'sub get_sector');
	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;
    }
    print "";
    return %hash;
}
sub get_sector_notificaciones {
    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}{'20'} 	= $expedientes_notificaciones{$k}[10];
		$hash{$k}{'21'} 	= $expedientes_notificaciones{$k}[11];
		$hash{$k}{'22'} 	= $expedientes_notificaciones{$k}[12];
    }
    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>No.</td><td>EXPEDIENTE</td><td>APELLIDOS</td><td>NOMBRES</td><td>DIRECCION</td><td>20</td><td>21</td><td>22</td><td>ENVIAR A COBRO JUDICIAL</td></tr></thead>";
    my $tfoot   = "<tfoot><tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>TOTAL</td><td>{t_20}</td><td>{t_21}</td><td>{t_22}</td><td>&nbsp;</td></tr></tfoot>";
    foreach my $k (sort keys %sector_notificaciones){
	my $row   = "<td>$count</td>
		     <td>".$k."</td>
		     <td>".$sector_notificaciones{$k}{'apellidos'}."</td>
		     <td>".$sector_notificaciones{$k}{'nombres'}."</td>
		     <td>".$sector_notificaciones{$k}{'direccion'}."</td>
		     <td>".$sector_notificaciones{$k}{'20'}."</td>
		     <td>".$sector_notificaciones{$k}{'21'}."</td>
		     <td>".$sector_notificaciones{$k}{'22'}."</td>
		     ";
	if($boton eq "ACTIVO"){$row .= "<td><input type=button value=\" EXPEDIENTE COMPLETO \" onclick=\"ProcesoCerrar('".$k."','CD')\"></td>"}else{$row .= "<td>&nbsp;</td>"}
	$rowset  	.= "<tr>".$row."</tr>";
	$t_20   	+= $sector_notificaciones{$k}{'20'};
	$t_21     	+= $sector_notificaciones{$k}{'21'};
	$t_22   	+= $sector_notificaciones{$k}{'22'};
	$count++;	
    }
    $tfoot     =~ s/\{t_20}/$t_20/g;
    $tfoot     =~ s/\{t_21}/$t_21/g;
    $tfoot     =~ s/\{t_22}/$t_22/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/\{clase}/$clase/g;         
        $line =~ s/\{table}/$table/g;
        $line =~ s/\{amistoso}/$amis/g;
        $line =~ s/\{administrativo}/$admi/g;
        $line =~ s/\{judicial}/$judi/g;
        $line =~ s/\{c11_sector_id}/$c11_sector_id/g;
        $line =~ s/\{v64_sector}/$v64_sector/g;
        $line =~ s/\{boton}/$boton/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;
}
#-------------------------------------------------------------------------