#!/usr/bin/perl

BEGIN { use lib '/usr/home/cfg' ; require push_inc ; }
    
use CGI qw( :standard );
use CGI::Carp qw(fatalsToBrowser);
use LWP::Simple qw($ua get);
use Date::Calc qw(:all);
use MIME::Lite;
use Mail::Sendmail;
use Time::Piece ; 

require cfg ;

print header;   # CGI.pm method

#-------------------------------------------------------------------------------

my @ARGV                = split(/\&/, $ENV{'QUERY_STRING'});
my $type                = $ARGV[0] ;

our ($q)                = CGI -> new() ;
my $iaction             = $q -> param('iaction')  ;
my $iattachdoc          = $q -> param('iattachdoc')   ;

# our $debug = 1 ;
# our $testing = 1 ;

#------------------------------------------------------------------------------------------

&today ;

# my $string = qq~6565,2,328.00~ ; 

if ($iaction eq '') {
	
    &screen1 ;
	
} elsif ($iaction eq 'upload') {
	
	&db_open_ro ;
		our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
			&read_import ;
			&read_db ;
			&process ;
			&screen3 ;
		$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
	&db_close_conn ;
	
} elsif ($iaction eq 'save') {
	 
	&common_min_load_params ;
	&db_open_upd ;
		our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
			&read_read_import_lines ;
			&update ;
		$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
	&db_close_conn ;
	&screen2 ; 
}

exit;

#------------------------------------------------------------------------------------------

sub read_read_import_lines {
	
	our $max_unmatched_id = 0 ; 
	
	my $upload_filehandle = $q->upload('iattachdoc') ;
	
} #------------------------------------------------------------------------------------------
 
sub update {
	
	&db_min_ro('logistics_costs','event_nr,amounts,file_name_ids,cost_type',"",'','') ;
	
	&db_min_ro('logistics_costs_tables',"1,MAX(id)+1 AS 'max_id'","",'','') ;
	$db{logistics_costs_tables}{1}{max_id} = 1 unless $db{logistics_costs_tables}{1}{max_id} ;
	
	my %ii = %i ; my $updated_logistics_costs_tables = 0 ; my $file_id = 0 ; my %cost_types = () ; my %event_has_diff_cost_types = () ; my %prev_cost_type = () ; 
	
	foreach (keys %ii) {
		if ($_ =~ /costtype_/) {
			my ($NA,$event_id,$amnt_cnt) = split(/\_/,$_) ;
			$event_id = ($event_id =~ /\d+/) ? $event_id : -1 ;
			$cost_types{$event_id}{$amnt_cnt} = $ii{$_} ;
			if ($prev_cost_type{$event_id} && $prev_cost_type{$event_id} ne $ii{$_}) {
				$event_has_diff_cost_types{$event_id} = 1 ;
			}
			$prev_cost_type{$event_id} = $ii{$_} ; 
		}
	}

	foreach (keys %ii) {
		if ($_ =~ /breakdownamnts_/) {
			unless ($updated_logistics_costs_tables) {
				$updated_logistics_costs_tables = 1 ;
				%i = () ; 
				$i{id}  = $db{logistics_costs_tables}{1}{max_id} ;
				$file_id = $i{id}  ;
				$i{file_name}  = $ii{uploaded_file_name} ;
				$i{file_total} = $ii{uploaded_file_total} ; 
				$i{file_total} = sprintf("%.0f",$i{file_total}) ; 
				$i{file_nr_of_unique_events} = $ii{file_nr_of_unique_events} ; 
				$i{file_nr_of_rows} = $ii{file_nr_of_rows} ; 
				$i{date_uploaded} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
				$i{uploaded_by} = $userid ;
				&db_min_insert('logistics_costs_tables') ; 

			}
			
			my ($NA,$event_id) = split(/\_/,$_) ;
 
			%i = () ; 
 
			$i{event_nr} = ($event_id =~ /\d+/) ? $event_id : -1 ;
			
			$i{cost_type} = ($db{logistics_costs}{$i{event_nr}}{cost_type}) ? "$db{logistics_costs}{$i{event_nr}}{cost_type}::" : "" ;
			
			my $added_to_cost_type = 0 ; 
			
			foreach my $amnt_cnt (sort {$a <=> $b} keys %{$cost_types{$i{event_nr}}}) {
				$added_to_cost_type = 1 ;
				$i{cost_type} .= qq~$cost_types{$i{event_nr}}{$amnt_cnt};;~ ;
				last unless $event_has_diff_cost_types{$i{event_nr}} ;
			}
			
			$i{cost_type} = substr($i{cost_type},0,-2) if $added_to_cost_type ;
			
			# $i{cost_type} 		= ($db{logistics_costs}{$i{event_nr}}{cost_type}   	) ? "$db{logistics_costs}{$i{event_nr}}{cost_type}::" . $ii{"costtype_$event_id"}	: $ii{"costtype_$event_id"}  ;
			$i{file_name_ids} 	= ($db{logistics_costs}{$i{event_nr}}{file_name_ids}) ? "$db{logistics_costs}{$i{event_nr}}{file_name_ids}:$file_id"	: "$file_id" ; 
			$i{amounts}	 		= ($db{logistics_costs}{$i{event_nr}}{amounts} 		) ? "$db{logistics_costs}{$i{event_nr}}{amounts}:$ii{$_}"			: "$ii{$_}" ;  ;
			
			$i{amounts} =~ s/\,//g ; 
			$i{amounts} =~ s/\.00//g ; 
			
			if ($i{event_nr} && $db{logistics_costs}{$i{event_nr}}{event_nr}) {
				$ignore{event_nr} = 1 ;
				&db_min_upd('logistics_costs',"event_nr='$i{event_nr}'") ; 
			} else {
				&db_min_ro('logistics_costs',"1,MAX(id)+1 AS 'max_id'","",'','') ;
				$db{logistics_costs}{1}{max_id} = 1 unless $db{logistics_costs}{1}{max_id} ;		
				$i{id} = $db{logistics_costs}{1}{max_id} ;
				&db_min_insert('logistics_costs') ; 
			}
		}
	}
	
} #------------------------------------------------------------------------------------------
 
sub read_import {
 
	$print_box_content_rows .= &common_min_forms_start('import-logistics-costs') ;
 
	my $upload_filehandle = $q->upload('iattachdoc') ;
		
	unless ($upload_filehandle) {
		$warning = "PLEASE UPLOAD A CSV FILE!!!" ;
		&common_min_alert_type ;
		&screen1 ;
	}

	our %totals = () ; my $line_cnt = 0 ; my %event_cnt = () ;
	
	if ($upload_filehandle !~ /.csv/) {
		$error = "PLEASE UPLOAD A CSV TYPE FILE!!!" ;
		&common_min_alert_type ;
		&screen1 ;
	} 
	
	my $file_total_amnt = 0 ; my $file_nr_of_rows = 0 ;

	if ($type eq 'csv') {

		while ( <$upload_filehandle> ) {
		# foreach (@imported_file_data) {
			
			next if $_ !~ /\d+/ ;
			
			$file_nr_of_rows++ ;
			
			chomp $_;
			
			$_ =~ s/\R\z// ; # Removes any line-ending character (\n, \r\n, or \r)
			$_ =~ s/\"//g ; 
			# $_ =~ s/\,//g ; 
			# $_ =~ s/\s+$//g;
			$_ =~ s/ //g ; 
			$_ =~ s/^,|(?<=\W),(?=\w)//g;	
			$_ =~ s/^(\d+),(\d+),(\d+\.\d+)/$1,$2$3/g; 					## REWRITE 1,1,000.11 AS 1,1000.11
			$_ =~ s/^(\d+),(\d+),(\d+),(\d+\.\d+)/$1,$2$3$4/g;			## REWRITE 1,1,000,000.11 AS 1,1000000.11
			$_ =~ s/^(\d+),(\d+),(\d+),(\d+),(\d+\.\d+)/$1,$2$3$4$5/g;	## REWRITE 1,1,000,000,000.11 AS 1,1000000000.11
			$_ =~ s/^([^,]+),(\d+),(\d+\.\d+)/$1,$2$3/;					## REWRITE OTHER,1,000.11 AS OTHER,1000.11
			$_ =~ s/^([^,]+),(\d+),(\d+),(\d+\.\d+)/$1,$2$3$4/;			## REWRITE OTHER,1,000,000.11 AS OTHER,1000000.11
			$_ =~ s/^([^,]+),(\d+),(\d+),(\d+),(\d+\.\d+)/$1,$2$3$4$5/;	## REWRITE OTHER,1,000,000,000.11 AS OTHER,1000000000.11

			my ($event_id,$total) = split(/\,/,$_) ;
			$event_cnt{$event_id} += 1 ;
			$totals{$event_id} += $total ;
			$file_total_amnt += $total ;
			
			$total = &common_commify(sprintf("%.02f",$total)) ; 
			$totals{breakdown}{$event_id} .= qq~$total;~ ;
			$totals{seperate}{$event_id}{$event_cnt{$event_id}} = $total  ;
			
			
			
		}
	}
	
	$file_total_amnt = sprintf("%.0f",$file_total_amnt) ; 
	 
	our @sql_col_display = ("event_nr","cost_type","logistics_totals") ;
	
	my $file_total = 0 ; my $file_nr_of_unique_events = 0 ; 
		
	&db_min_ro('event_quotes','id,quote_completed,quote_accepted,fixed_system_overall_status,event_system_id_multiple,quote_rejected,quote_cancelled,quote_created,quote_pending,sss_quote_nr',"",'','') ;
	
	&db_min_ro('event_systems',"*",'','','') ; 	
	
	my %seen_event = () ; 
	
	foreach my $event_id (sort {$a <=> $b} keys %totals) {
		
		next if $event_id eq 'breakdown' ;
		
		my $amnt_cnt = 0 ; 
		
		foreach my $sep_amnt (split(/\;/,$totals{breakdown}{$event_id})) {
		
			$print_tbody .= qq~<tr>~ ;
			
			$amnt_cnt++ ;
			
			foreach (@sql_col_display) {
				my $val = '' ;
				my $class = qq~class="dt-center"~ ;
				if ($_ eq 'event_nr') {
					$val = ($event_id eq 'IBT') ? &common_min_get_event_quote_button("N/A") : &common_min_get_event_quote_button($event_id) ;
					$file_nr_of_unique_events++ unless $seen_event{$event_id} ;
				} elsif ($_ eq 'cost_type') {
					$val = ($event_id eq 'IBT') ? $event_id : "" ;
					$val = ($val) ? &common_min_table_input("costtype_$event_id\_$amnt_cnt",$val) : "" ;
				} elsif ($_ eq 'logistics_totals') {
					chop $totals{breakdown}{$event_id} if $totals{breakdown}{$event_id} ;
					
					# my $seperate_amnts_tooltip 	= ($totals{breakdown}{$event_id} =~ /:/) ? $totals{breakdown}{$event_id} : qq~~ ; 
					# $seperate_amnts_tooltip 	=~ s/\:/\<br>/g ; 
					# $seperate_amnts_tooltip 	= qq~title data-toggle="tooltip" data-placement="right" data-original-title="Seperate Amounts :<br>$seperate_amnts_tooltip"~ if $seperate_amnts_tooltip ;
					
					my $breakdownamnts = ($seen_event{$event_id}) ?  qq~~ : qq~<input style="display:none;" name="breakdownamnts_$event_id" value="$totals{breakdown}{$event_id}">~ ;
					# <input style="display:none;" name="total_$event_id" value="$totals{$event_id}">
					
					# $totals{seperate}{$event_id}{$event_cnt{$event_id}}
					
					# $totals{seperate}{$event_id}{$amnt_cnt} = &common_commify(sprintf("%.02f",$totals{seperate}{$event_id}{$amnt_cnt})) ; 
	
					$val = qq~$breakdownamnts~ . qq~<span $seperate_amnts_tooltip>~ . $totals{seperate}{$event_id}{$amnt_cnt} . qq~</span>~ ; 
		
					$file_total += $totals{$event_id} unless $seen_event{$event_id} ;
				}
				# style="display:none;
				
				$print_tbody .= qq~<td $class>$val</td>~ ;	
			}
			$print_tbody .= qq~</tr>~ ;	
			
			$seen_event{$event_id} = 1 ;
			
		}
		
	}

	&db_min_ro('logistics_costs_tables',"1,id","`file_total`='$file_total_amnt' AND `file_nr_of_unique_events`='$file_nr_of_unique_events' AND `file_nr_of_rows`='$file_nr_of_rows'",'','') ;
	
	if ($db{logistics_costs_tables}{1}{id}) {
		$warning = "THE FILE UPLOADED HAVE ALREADY BEEN SAVED!!!" ;
		&common_min_alert_type ;
		# &screen1 ;
		# $print_box_content_rows .= qq~<input style="display:none;" name="file_exists" value="1">~ ; 
	}
	
	$file_total = sprintf("%.02f",$file_total) ; 
	
	$print_box_content_rows .= qq~<input style="display:none;" name="uploaded_file_name" value="$upload_filehandle">~ ; 
	$print_box_content_rows .= qq~<input style="display:none;" name="uploaded_file_total" value="$file_total">~ ; 
	$print_box_content_rows .= qq~<input style="display:none;" name="file_nr_of_unique_events" value="$file_nr_of_unique_events">~ ; 
	$print_box_content_rows .= qq~<input style="display:none;" name="file_nr_of_rows" value="$file_nr_of_rows">~ ; 
	
		# $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
	# &db_close_conn ;
		
} #------------------------------------------------------------------------------------------

sub read_db {
	
} #------------------------------------------------------------------------------------------

sub process {

} #------------------------------------------------------------------------------------------

sub screen1 {

	&common_min_dialog ;

	$print_box_content_rows .= qq~<div class="col-md-6"><div class="form-group"></div></div>~;
	  
	# my $date_inputs = &common_min_form_datepicker() ; 
	  
	print <<ENDOFTEXT;
	$dialog{'common'}{'head'}
		
	<div id="content" class="col-lg-12 col-sm-12">
		<!-- content starts --> 
		
		$alert
		
		<div class="row">
			<div class="box col-md-12">
				<form role="form" name="form_import" id="import-form" action="?$type" method="post" enctype="multipart/form-data">
				<div class='row'>
					<div class='col-md-9'>
						<div class='control-group'>
							<div class='controls'> 
								<label for="imageInputFile">Import CSV</label>
								<input type="file" id="imageInputFile" name='iattachdoc' tabindex='1'>
								<p class="help-block">Upload file from PC.</p>
							</div>
						</div>
					</div>
				</div>
				<input type="hidden" name="iaction" id="action" value="upload">
				<div class="row"><div class="col-md-12">&nbsp;</div></div>
				<div class="row">
					<div class="col-md-12">	
						<button type="button" class="btn btn-primary" id="importbutt">Upload</button>&nbsp;
						<button type="button" class="btn btn-default" onclick="parent.BootstrapDialog.closeAll();">Close</button>
					</div>
				</div>
				<div class="row"><div class="col-md-12">&nbsp;</div></div>
				</form>
			</div>
		</div>
	</div> 
	</div><!--/fluid-row-->   
	</div><!--/.fluid-container-->

	<!-- external javascript -->

	<style>body { font-size: 14px; }.control-label { font-size: 14px; }</style>
	<script src="$useropts{'js'}/jquery.form-validator.min.js"></script>

	$dialog{'common'}{'js'}

	<script>

	\$.validate();

	\$("#importbutt").click(function() {    
		\$('#action').val('upload');
		\$('#import-form').submit();
	});

	</script>
	</body>
	</html>
ENDOFTEXT
#         

exit ;

} #------------------------------------------------------------------------------------------

sub screen2 {

	# <div class="alert alert-success" id="alertmsg" role="alert"></div>
	
	my $jquery = qq~parent.\$("#alertbar").html("<div class='alert alert-success' id='alertmsg' role='alert'><i class='glyphicon glyphicon-ok'></i> CSV SUCCESSFULLY IMPORTED</div>");
		parent.location.reload();
		parent.BootstrapDialog.closeAll() ;~ unless $debug ;
		 
	print <<ENDOFTEXT;
	<!DOCTYPE html>
	<html lang="en">
	<head>    
		<meta charset="utf-8">
		<title>$useropts{title}</title>
		<script src="$useropts{'bower_components'}/jquery/jquery.min.js"></script>   
	</head>
	<body>
	<script>

	\$(function () {
		$jquery
	});

	</script>
	</body>
	</html>
ENDOFTEXT
#

} #------------------------------------------------------------------------------------------

sub screen3 {

&thead;

if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; }

# my $page = "$lcpage\s" ;

my $page = "event-quotes" ;

if ($s{no}) { $page = $lcpage ; }

&common_min_thead ; 

# &common_min_table('id',$page,'list') ;

$print_box_content_rows .= qq~
	<table id="itv-table" class="table table-striped table-bordered bootstrap-datatable datatable responsive">    
		$print_thead
		<tbody>
			$print_tbody
		</tbody>
	</table>
~ ;

# &common_min_table_select_jquery("#itv-table td:nth-last-child(2),#itv-table td:nth-last-child(10)") ;

# our $savjqy = 1 ;

# &common_min_extra_crumb("manage-$lcpage\s","Manage $ucfirstpage\s") ;

# $extra_form_fields .= qq~<input type="file" id="imageInputFile" name='iattachdoc' tabindex='1'>~ ;

	# <input type="hidden" name="client_id"        value="$i{client_id}">
	# <input type="hidden" name="date_from"        value="$i{date_from}">
	# <input type="hidden" name="date_to"          value="$i{date_to}">
	# <input type="hidden" name="event_costing_id" value="$i{event_costing_id}">
	# <input type="hidden" name="event_quote_id"	 value="$i{event_quote_id}">
	# <input type="hidden" name="paid_status"      value="$i{paid_status}">
# ~ ;

our $savjqy = 1 ;

$trigger_jquery_raw .= qq~
	\$("#savebutt").click( function () {
		
		let file_uploaded = "$db{logistics_costs_tables}{1}{id}" ;
		
		if (file_uploaded) {
			BootstrapDialog.confirm({
				title: 'Confirm Upload',
				message: 'Are you sure you want to uplad this file that may have already been saved?',
				type: BootstrapDialog.TYPE_WARNING, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING
				callback: function(result) {            
					if (result) {
						console.log("import-logistics-costs-form") ; 
						\$("#import-logistics-costs-form").submit() ;					  
					}
				}
			});
		} else {
			\$("#import-logistics-costs-form").submit() ;
		}
	}) ;
~ ;

$print_box_content_rows .= &common_min_forms_end('','','save') ;

require _blank_4 ;

exit ;

} #------------------------------------------------------------------------------------------

use today ;
use common ; 
use production_time ;