#!/perl/bin/perl.exe
$|=1;
#--------------------------------------------------------------------------------
#--------------------------------------------------------------------------------
# Information Software SA
# Date In: 2012-12-09
# Updates: 2012-12-09
# Author:Rodolfo Machon
# File Name: mora_cartera_notificador_guardar.pl
#------------------------------------------------------------------------- 
#-------------------------------------------------------------------------
# PERL MODULES
use CGI;
use Win32::ODBC;
#------------------------------------------------------------------------- 
#-------------------------------------------------------------------------
# HTML PRINTING ACTIVATION
print "Content-type: text/html\n\n";
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
#GET PARAMETERS
$cgiparms      = new CGI;
$lan	       = $cgiparms->param('lan');
$appid	       = $cgiparms->param('appid');
$clase 	       = $cgiparms->param('clase');
$str	       = $cgiparms->param('str_expedientes');
$str1	       = $cgiparms->param('str_expedientes1');
$c2_zona_id    = $cgiparms->param('c2_zona_id');
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# CHECK PARAMETERS
if ($lan eq ""){print "Your are not passing LAN parameter<br>";}
if ($appid eq ""){print "Your are not passing APPID parameter<br>";}
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# GLBAL VARIABLES
$PATH	="../libraries/html/";
$file 	= "msg_processing.html";
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# GET CLASE SCHEMA AND VARIABLES
if (!($dbh  = new Win32::ODBC($appid))){connect_fail($appid)}
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# PROGRAM DESCRIPTION
# PROCUREMENT
$today		= get_fecha();
($uid,$uf,$ul)  = get_user();
%sectores       = get_sectores();
%notificador 	= get_notificador();
# INTEGRATION
delete_notificadores();
if($str ne ""){insert_notificadores();}
# PRESENTATION
construct_page();
exit;
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
#SUB-ROUTINES -> LEVEL 1
sub get_fecha {
	my $fec     = "";
	my $query   = "SELECT DATE_FORMAT(CURDATE(),'%Y-%m-%d')";
	if ( $dbh->Sql($query) ){SQL_fail($query,$dbh,'get_fecha')}
	if ($dbh-> FetchRow()){
		my @row = $dbh->Data();
		$fec = $row[0];
	}	
	return $fec;	
}
sub get_user {
	my $uid   = "";
	my $uf   = "";
	my $ul   = "";	
        my $user  = $ENV{"REMOTE_USER"};
	my $query = "SELECT a.i8_user_id,a.`v32_fname`,a.`v32_lname` FROM sdm_users a where a.`v16_login`='$user'";
	if ( $dbh->Sql($query) ){SQL_fail($query,$dbh,'sub get_user')};
	while($dbh->FetchRow()){
		my @row = $dbh->Data();
		$uid = $row[0];
		$uf  = $row[1];
		$ul  = $row[2];
	}
	return $uid,$uf,$ul;
}
sub get_sectores {
	my $mystr  = "";
	my %hash   = ();
	if($str eq ""){$mystr = $str1}else{$mystr = $str}
	my @expedientes = split(/\~/,$mystr);
	for($i=0;$i<=$#expedientes;$i++) {
		my @exp = split(/\|/,$expedientes[$i]);
		$hash{$exp[0]} = $exp[1];
		#print $hash{$exp[0]}."<br>";
	}
	return %hash;
}
sub get_notificador {
	my %hash = ();	
	my $str  = "";
        foreach my $k (sort keys %sectores){$str .= $sectores{$k}.",";}
	$str = substr($str,0,length($str)-1);
	my $query = "SELECT a.i8_user_id,a.v32_fname,a.v32_lname
		     FROM sdm_users a
		     WHERE a.i8_user_id IN ($str)
		     ORDER BY a.i8_user_id";
	if ( $dbh->Sql($query) ){SQL_fail($query,$dbh,'sub get_notificador')};
	while($dbh->FetchRow()){
	    my @row = $dbh->Data();
	    $hash{$row[0]} = [@row];
	}
	return %hash;
}
sub delete_notificadores {
	foreach my $k (sort keys %sectores){
		my $query = "DELETE FROM sdd_sector_notificador WHERE c11_sector_id='".$k."'  and i8_notificador_id='".$sectores{$k}."'";
		#print "$query<br>\n";
		if ( $dbh->Sql($query) ){SQL_fail($query,$dbh,'sub delete_notificadores')}
	}
}
sub insert_notificadores {
	foreach my $k (sort keys %sectores){
		my $gid = $notificador{$sectores{$k}}[0];
		my $gf  = $notificador{$sectores{$k}}[1];
		my $gl  = $notificador{$sectores{$k}}[2];		
		my $query = "INSERT INTO sdd_sector_notificador
			     (c11_sector_id,c2_tipo_notificador_id,i8_notificador_id,v64_nombres_notificador,v64_apellidos_notificador,
			     c8_estado,dt_activacion,i8_asignador_id,v64_nombres_asignador,v64_apellidos_asignador,ts_in)
			     VALUES ('$k','IN','$gid','$gf','$gl','ACTIVO','$today','$uid','$uf','$ul',now())";
		if ( $dbh->Sql($query) ){SQL_fail($query,$dbh,'sub insert_notificador')}
	}
}
sub update_notificadores {
	my %hash = ();
	my @expedientes = split(/\~/,$str1);
	for($i=0;$i<=$#expedientes;$i++) {
		my @exp = split(/\|/,$expedientes[$i]);
		$hash{$exp[0]} = $exp[1];
	}
	foreach my $k (sort keys %hash){
		my $query = "UPDATE sdd_sector_notificador SET c8_estado='INACTIVO',dt_inactivacion='$today' WHERE c11_sector_id='".$k."' and i8_notificador_id='".$hash{$k}."'";
		if ( $dbh->Sql($query) ){SQL_fail($query,$dbh,'sub update_notificadores')}
	}
}
sub construct_page {
    $data= "mora_notificaciones_p.pl?lan=$lan&appid=$appid&clase=$clase&c2_zona_id=$c2_zona_id";
    open (DATA, "$PATH$file");
    while ($line = <DATA>) {
	    $line =~ s/{CGI}/$data/g;
	    $line =~ s/{message}/Procesando Por Favor Espere.../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 convertir_tildes{
      my ($str) = @_;
      $str =~ s/\Ã±/ñ/g;
      $str =~ s/\Ã/Ñ/g;
      $str =~ s/\Ã¡/á/g;
      $str =~ s/\Ã©/é/g;
      $str =~ s/\Ã­/í/g;
      $str =~ s/\Ã³/ó/g;
      $str =~ s/\Ãº/ú/g;
      return $str;
}
#-------------------------------------------------------------------------