#!/perl/bin/perl.exe
$|=1;
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# Author:Rodolfo Machon
# Company:WebSoft, SA de CV 
# Nombre del archivo: mandamiento.ref.save.pl
# Created: 2017-04-03
# Updates: 2017-04-03
# Copyright - All Rights Reserved
#------------------------------------------------------------------------- 
#-------------------------------------------------------------------------
# PERL MODULES
use CGI;
use DBI;
use XML::Simple;
use Data::Dumper;
use Date::Calc qw(Add_Delta_YMD);
use CGI::Carp qw(fatalsToBrowser);
binmode STDOUT, ":encoding(utf8)";
#------------------------------------------------------------------------- 
#-------------------------------------------------------------------------
# HTML PRINTING ACTIVATION
print "Content-type: text/html; charset=utf-8\n\n";
#------------------------------------------------------------------------- 
#-------------------------------------------------------------------------
#GET PARAMETERS
$form	 				= new CGI;
$v128_contribuyente		= $form->param('v128_contribuyente');
$c16_tarifa_id			= $form->param('c16_tarifa_id');
$dt_emision				= $form->param('dt_emision');
$i2_cajero_id			= $form->param('i2_cajero_id');
$i8_emisor_id			= $form->param('i8_emisor_id');
$i4_cantidad			= $form->param('i4_cantidad');
$txt_concepto			= $form->param('txt_concepto');
$i2_tipo_departamento_id= $form->param('i2_tipo_departamento_id');
$fiestas				= $form->param('fiestas');
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# GET CLASE SCHEMA AND VARIABLES
get_app_data();
#--------------------------------------------------------------------------------
#--------------------------------------------------------------------------------
#GENERAL VARIABLES

#--------------------------------------------------------------------------------
#--------------------------------------------------------------------------------
# OPEN DATABASE CONNECTIONS - ODBCs
$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;
$dbh1 	= DBI->connect("dbi:ODBC:$appid",'','',{PrintError => 1, RaiseError => 1});
if (!$dbh1) {print "error: connection: $DBI::err\n$DBI::errstr\n$DBI::state\n";}
$dbh1->{LongReadLen} = 512 * 1024;
#--------------------------------------------------------------------------------
#--------------------------------------------------------------------------------
#Main Program
$mid = insert_mandamiento();
insert_mandamiento_detalle();
print "$mid";
exit;
#--------------------------------------------------------------------------------
#--------------------------------------------------------------------------------
# SUB-ROUTINES
sub insert_mandamiento{
	my $str						= 0;
	my $c2_tipo_mandamiento_id	= "RE";
	my $i8_contribuyente_id	  	= 99999999;
	my $i2_tipo_pago_id	  		= 1;
	my $c4_status_mandamiento_id= "OPEN";
	my $d82_tarifa 				= 0;
	my $c3_tipo_generador_id    = "REF";
	my $sql = " insert into sdm_mandamientos
				(i8_contribuyente_id,i2_tipo_pago_id,i2_tipo_departamento_id,c3_tipo_generador_id,
				c2_tipo_mandamiento_id,v128_contribuyente,dt_emision,dt_vencimiento,txt_concepto,
				c4_status_mandamiento_id,i2_cajero_id,i8_emisor_id,ts_in,ts_update)
				values($i8_contribuyente_id,$i2_tipo_pago_id,$i2_tipo_departamento_id,'$c3_tipo_generador_id',
				   '$c2_tipo_mandamiento_id','$v128_contribuyente','$dt_emision','$dt_emision','$txt_concepto',
				   '$c4_status_mandamiento_id',$i2_cajero_id,$i8_emisor_id,now(),now())";	
	#print "$sql<br>";
    $dbh->do($sql);
	$sql = "SELECT LAST_INSERT_ID()";
	my $sth = $dbh->prepare($sql);
	$sth->execute or die SQL_fail($sql,$dbh,'sub insert_mandamiento');
	if (my @row = $sth->fetchrow_array) {
		$str=$row[0];
	}
	return $str;
}
sub insert_mandamiento_detalle {
	my $trfs  = ""; 
	my @tarfs = split(/\,/,$c16_tarifa_id);
	for (my $i=0;$i<=$#tarfs;$i++){$trfs .= "'".$tarfs[$i]."',";}
	$trfs = substr($trfs,0,length($trfs)-1);
	my $sql	  = "select c16_tarifa_id,v128_tarifa,d82_tarifa from sdm_tarifas where c16_tarifa_id IN ($trfs) order by dt_desde desc";
	#print "$sql<br>";	
	my $sth = $dbh->prepare($sql);
	$sth->execute or die SQL_fail($sql,$dbh,'sub insert_mandamiento');
	while (my @row = $sth->fetchrow_array) {
		my $c16_tarifa				= $row[0];
		my $v128_tarifa				= $row[1];
		my $d82_tarifa 				= $row[2];
		my $c16_tarifa_id_fiestas	= "ACINMFIENNAMC001";
		my $d82_fiestas 			= round(($d82_tarifa*0.05),2);
		my $d82_fiestas 			= round(($d82_fiestas*$i4_cantidad),2);

		if ($mid>0){
			my $sql1="insert into sdd_mandamientos (i8_mandamiento_id,c16_tarifa_id,v128_tarifa,d82_cantidad,d82_tarifa)
			values($mid,'$c16_tarifa','$v128_tarifa','$i4_cantidad',$d82_tarifa)";
			#print "$sql1<br>";
			$dbh1->do($sql1);
			if ($fiestas eq "SI"){
				my $sql2 ="insert into sdd_mandamientos (i8_mandamiento_id,c16_tarifa_id,v128_tarifa,d82_cantidad,d82_tarifa)
						  values($mid,'$c16_tarifa_id_fiestas','FIESTAS',1,'$d82_fiestas')";
				#print "$sql2<br>";
				$dbh1->do($sql2);
			}
		}
	}
}
#------------------------------------------------------
#AUXILIAR SUB-ROUTINES
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};
    $country    = $data->{portal}->{country};
}
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;
}
sub SQLfail{
	my ($db_conn_name,$query,$section)=@_;
	print "SQL failed<BR>";
	print "$query<br>";
	print "Section=$section<br>";
	print "Error: " . $db_conn_name->Error() . "\n";
	exit;
}