#!/usr/bin/perl

BEGIN { use lib '/usr/home/cfg' ; require push_inc ; }
    
require cfg ;

print "Content-type: text/html\n\n";

# unless ($useropts{it}{$username}) { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; }

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

use CGI::Carp qw(fatalsToBrowser);
use CGI;
use Mail::Sendmail;
use Fcntl qw(:flock);
use File::Copy;
use File::Basename;
use Date::Calc qw(:all);
use Excel::Writer::XLSX;

use Time::Piece;
use Time::Seconds;

# my $start_time_str = "09:30:00" ;
# my $end_time_str   = "17:45:00" ;

# Create Time::Piece objects for start and end times
# my $start_time = Time::Piece->strptime($start_time_str, "%H:%M:%S");
# my $end_time   = Time::Piece->strptime($end_time_str, "%H:%M:%S");

# Calculate the difference in seconds and convert to hours
# my $time_diff_in_hours = (Time::Piece->strptime($end_time_str,"%H:%M:%S") - Time::Piece->strptime($start_time_str,"%H:%M:%S")) / ONE_HOUR;

&today;

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

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

our ($q)                 = CGI -> new() ;
our $iaction             = $q -> param('iaction')                || $action ;
our $isaved              = $q -> param('isaved')                 || '' ;

our $open_new_tab = qq~target="_blank"~ ;

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

#-------- page opts --------------------------------------------------------------------------------------------------------------------------------------------------

&page_opts ;

#---------------------------------------------------------------------------------------------------------------------------------------------------------------------
	
our $srchscr = 1 ;

&db_open_ro ;
    our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
		&report_screen if $iaction eq '' ; 
	$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
&db_close_conn ;



if ($iaction eq 'report') {
	&common_min_load_params ;
	&db_open_ro ;
		our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
		&report_ifields ;
		&list_screen ; 
		$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
	&db_close_conn ;			
	&screen3 ;
}

if ($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
			&update ;
		$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
	&db_close_conn ;
	exit if $username eq 'rory' && $testing ;
	&screen4 ;
}

# &common_min_action;

exit;

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

sub update {
	
	&db_min_ro('logistics_costs','event_nr,file_name_ids,cost_type',"",'','') ;

	my %ii = %i ; my %cost_types = () ; 

	foreach (keys %ii) {
		if ($_ =~ /costtype_/) {
			my ($NA,$event_id,$file_id,$amnt_cnt) = split(/\_/,$_) ;
			$cost_types{$event_id}{$file_id}{$amnt_cnt} = 1 ;
			next if $event_and_file_has_diff_cost_types{$event_id}{$file_id} ;
			if ($prev_cost_type{$event_id}{$file_id} && $prev_cost_type{$event_id}{$file_id} ne $ii{$_}) {
				$event_and_file_has_diff_cost_types{$event_id}{$file_id} = 1 ;
			}
			$prev_cost_type{$event_id}{$file_id} = $ii{$_} ; 
		}
	}
	
	my %seen_event = () ; 
	
	foreach (keys %ii) {
		if ($_ =~ /costtype_/) {
			my ($NA,$event_id,$file_id1,$amnt_cnt1) = split(/\_/,$_) ;
	
			next if $seen_event{$event_id} ;
			$seen_event{$event_id} = 1 ;
			
			%i = () ;  
			my $saved_event_id = ($event_id =~ /\d+/) ? $event_id : -1 ;
			my @saved_files = split(/\:/,$db{logistics_costs}{$saved_event_id}{file_name_ids}) ;
			my $used_file = 0 ; 

			foreach my $file_id (@saved_files) {
				my $used_amnt = 0 ; $used_file = 1 ; 
				if ($event_and_file_has_diff_cost_types{$event_id}{$file_id}) {
					foreach my $amnt_cnt (sort {$a <=> $b} %{$cost_types{$event_id}{$file_id}}) {
						my $field_name = "costtype_$event_id\_$file_id\_$amnt_cnt" ;
						$i{cost_type} .= qq~$ii{$field_name};;~ ;
						$used_amnt = 1 ;
					}
					$i{cost_type} = substr($i{cost_type},0,-2) if $used_amnt ; 
					$i{cost_type} .= qq~::~ ;					
				} else {
					$i{cost_type} .= qq~$ii{$_}::~ ; 
				}
			} 
			$i{cost_type} = substr($i{cost_type},0,-2) if $used_file ; 
			$ignore{cost_type} = 1 if $i{cost_type} eq $db{logistics_costs}{$event_id}{cost_type} ;
			&db_min_upd("logistics_costs","event_nr='$event_id'") ; 
		}
	}

	%i = %ii ;
	
	# exit ;
	
} #------------------------------------------------------------------------------------------

sub report_ifields {

	if ($i{event_id} && $i{event_id} ne 'all' && $i{event_id} ne 'na_event' && $i{event_id} ne 'N/A') {
		push @report_sql_2, "(id = '$i{event_id}')" ;
		&db_min_ro('event_quotes','1,ref',"`id`='$i{event_id}'",'','') ; 
	}
	
	if ($db{event_quotes}{1}{ref}) {
		push @report_results, "(EVENT QUOTE = '$db{event_quotes}{1}{ref}')" ;
		push @report_sql, "(event_nr = '$i{event_id}')" ;
	} elsif ($i{event_id} eq 'N/A') {
		push @report_results, "EVENT NAME UNKNOWN" ;
		push @report_sql, "(event_nr = '-1')" ;
		push @report_sql_2, "(id = '-1')" ;
	} elsif ($i{event_id} && $i{event_id} eq 'all') {
		push @report_results, "ALL EVENTS" ;
		
	} else {
		push @report_sql, "(event_nr = '$i{event_id}')" ;
		push @report_results, "(EVENT NR = '$i{event_id}')" ;
	}
	
	if ($i{cost_type}) {
		push @report_results, "(COST TYPE LIKE '$i{cost_type}')" ;
		push @report_sql, "(cost_type LIKE '%$i{cost_type}%')" ;
	}

	$report_results_msg = uc join(', ',@report_results) ;

	if (not $report_results_msg) { 
		# $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); 
		# &report_screen ; 
	} else { 
		$isaved = qq(SELECT WHERE $report_results_msg) ; 
	}
 
} #------------------------------------------------------------------------------------------

sub list_screen {

	$print_box_content_rows .= &common_min_forms_start('logistics-costs') ;

	my $srch_where_sql = join(' AND ', @report_sql) ;
	my $srch_where_sql_2 = join(' AND ', @report_sql_2) ;
	
	&load_list_vars("$srch_where_sql","$srch_where_sql_2") ;
	
	our @sql_col_display = ("event_nr","cost_type","amounts","uploaded_from") ;

	foreach my $event_id (sort {$a <=> $b} keys %{$db{$table}}) {
	
		# my $event_id = $db{$table}{$id}{event_nr} ;
		
		# $db{$table}{na}{file_name_ids} = $db{$table}{$event_id}{file_name_ids} if $event_id < 0 ;
		
		next if $event_id eq 'breakdown' ;
		
		if ($db{$table}{$event_id}{file_name_ids}) {
			
			my @all_amounts_per_file_uploaded = split(/\:/,$db{$table}{$event_id}{amounts}) ; 
			my @files_uploaded = split(/\:/,$db{$table}{$event_id}{file_name_ids}) ; 
			my @all_cost_type = split(/\::/,$db{$table}{$event_id}{cost_type}) ; 
			my $file_cnt = 0 ; 
			
			$event_id = "na" if $event_id < 0 ;
			
			foreach my $file_id (@files_uploaded) { 
				
				
				my @amounts_per_file_uploaded = split(/\;/,$all_amounts_per_file_uploaded[$file_cnt]) ; 
				
				if ($all_amounts_per_file_uploaded[$file_cnt] =~ /;/ && $all_cost_type[$file_cnt] && $all_cost_type[$file_cnt] !~ /;/) {
					my $abc = $all_cost_type[$file_cnt] ;
					foreach (@amounts_per_file_uploaded) {
						$all_cost_type[$file_cnt] .= qq~;;$abc~ ;
					}
				}
				my @files_cost_type = split(/\;;/,$all_cost_type[$file_cnt]) ; 
				
				my $amnt_cnt = 0 ; 

				foreach my $sep_amnt (@amounts_per_file_uploaded) {
					
					$amnt_cnt++ ;
					$print_tbody .= qq~<tr>~ ; 
		
					foreach my $col (@sql_col_display) {
						my $val = '' ;
						my $class = qq~class="dt-center"~ ;
						if ($col eq 'event_nr') {
							$val = ($event_id eq 'na') ? qq~<span style="display:none;">NA</span>~ . &common_min_get_event_quote_button("N/A") : qq~<span style="display:none;">$event_id</span>~ . &common_min_get_event_quote_button($event_id) ;
						} elsif ($col eq 'cost_type') {
							$val = $files_cost_type[$amnt_cnt-1] ;
							$val = ($val) ? &common_min_table_input("costtype_$event_id\_$file_id\_$amnt_cnt",$val) : "Logistics Costs" ;
						} elsif ($col eq 'amounts') { 
							$val = &common_commify(sprintf("%.02f",$sep_amnt)) ; 
						} elsif ($col eq 'uploaded_from') { 
							$val = $db{logistics_costs_tables}{$file_id}{file_name} ;
						}
						$print_tbody .= qq~<td $class>$val</td>~ ;	
					}
					$print_tbody .= qq~</tr>~ ;	
				}
				$file_cnt++ ;
			}
		}
		
		if ($db{event_quotes_min}{$event_id}{cost_types}) {
			
			my $cost_cnt = 0 ; 
			my @amounts_per_cost = split(/\;/,$db{event_quotes_min}{$event_id}{amounts}) ; 
			my @qtys_per_cost = split(/\;/,$db{event_quotes_min}{$event_id}{qtys}) ; 
			my @cost_type_ids = split(/\;/,$db{event_quotes_min}{$event_id}{cost_types}) ; 
	 
			foreach my $cost_type_id (@cost_type_ids) {
				$cost_cnt++ ;
				next if !$cost_type_id || !$db{event_cost_items}{$cost_type_id}{name} ;
				$print_tbody .= qq~<tr>~ ; 
				foreach my $col (@sql_col_display) {
					my $val = '' ;
					my $class = qq~class="dt-center"~ ;
					if ($col eq 'event_nr') {
						$val = qq~<span style="display:none;">$event_id</span>~ . &common_min_get_event_quote_button($event_id) ;
					} elsif ($col eq 'cost_type') {
						$val = $db{event_cost_items}{$cost_type_id}{name} ;
					} elsif ($col eq 'amounts') {
						$amounts_per_cost[$cost_cnt-1] = 0 if $amounts_per_cost[$cost_cnt-1] !~ /\d+/ ;
						$val = &common_commify(sprintf("%.02f",$qtys_per_cost[$cost_cnt-1]*$amounts_per_cost[$cost_cnt-1])) ; 
					} elsif ($col eq 'uploaded_from') { 
						$val = "" ;
					}
					$print_tbody .= qq~<td $class>$val</td>~ ;	
				}
				$print_tbody .= qq~</tr>~ ;	
			}
		}
	}
	
} #------------------------------------------------------------------------------------------

sub load_list_vars {
	
	my ($where,$where_2) = @_ ;
	
	&db_min_ro($table,"event_nr,file_name_ids,cost_type,amounts","$where",'','') ; 
	
	our %totals = () ;
	
	foreach my $event_id (keys %{$db{$table}}) {
		# my $event_id = $db{$table}{$id}{event_nr} ;
		my @files_uploaded = split(/\;/,$db{$table}{$id}{file_name_ids}) ; 
		my $files_cnt = 0 ; 
		foreach my $part1 (split(/\:/,$db{$table}{$id}{amounts})) {
			foreach my $part2 (split(/\;/,$part1)) {
				$totals{$event_id}{$files_uploaded[$files_cnt]} += $part2 ;
				$totals{breakdown}{$event_id}{$files_uploaded[$files_cnt]} .= qq~$part2;~ ;
			}
			$files_cnt++ ;			
		}
	}
	
	&db_min_ro('logistics_costs_tables',"id,file_name",'','','') ; 
	
	&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',"*",'','','') ; 	
	
	&get_events_with_other_costs($where_2) ;
	
} #------------------------------------------------------------------------------------------

sub get_events_with_other_costs {
	
	my ($where) = @_ ; 
	
	&db_min_ro('event_quotes_min',"id,item_costing_event AS 'cost_types',qty_costing_event AS 'qtys',usd_amnt_costing_event AS 'amounts'","$where",'','') ; 
	
	&db_min_ro('event_cost_items','id,name',"id != '14' AND name NOT LIKE '%Mobile%%System%' AND name NOT LIKE '%Fixed%%System%' AND name NOT LIKE '%Mobile%%Operation%' AND name NOT LIKE '%Fixed%%Operation%' AND name NOT LIKE '%Cricket%%Operation%'",'','') ; 
	
	foreach my $event_id (keys %{$db{event_quotes_min}}) {
		foreach (split(/\;/,$db{event_quotes_min}{$event_id}{cost_types})) {
			next unless $_ ;
			if ($db{event_cost_items}{$_}{name} && !$db{logistics_costs}{$event_id}{event_nr}) {
				$db{logistics_costs}{$event_id}{event_nr} = $event_id ;
			}
		}
	}

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

sub set_tick {
	
	my ($color,$tooltip) = @_ ;
		
	$tick{green}  = qq~<span style="display:none;">2</span><span class="label label-success"><i $tooltip class="glyphicon glyphicon-ok"></i></span>~ ;
	$tick{orange} = qq~<span style="display:none;">1</span><span class="label label-warning"><i $tooltip class="glyphicon glyphicon-ok"></i></span>~ ;
	$tick{red}    = qq~<span style="display:none;">0</span><span class="label label-danger"><i $tooltip class="glyphicon glyphicon-ok"></i></span>~ ;

	return ($tick{$color}) ;
			
} #------------------------------------------------------------------------------------------

sub set_cross {
	
	my ($color,$tooltip) = @_ ;
		
	$tick{green}  = qq~<span style="display:none;">2</span><span class="label label-success"><i $tooltip class="glyphicon glyphicon-remove"></i></span>~ ;
	$tick{orange} = qq~<span style="display:none;">1</span><span class="label label-warning"><i $tooltip class="glyphicon glyphicon-remove"></i></span>~ ;
	$tick{red}    = qq~<span style="display:none;">0</span><span class="label label-danger"><i $tooltip class="glyphicon glyphicon-remove"></i></span>~ ;

	return ($tick{$color}) ;
			
} #------------------------------------------------------------------------------------------

sub thead {
	
	&common_min_thead ;
	
} #-------------------------------------------------------------------------------

sub page_opts {

	our $glyphicon = 'list' ;
	our $lcpage    = 'logistics-costs-report' ;

	&common_page_name ;
	   
	our $table     = 'logistics_costs' ;
	$page_title    = 'Logistics Costs' ;
 
	$box_icon .= qq~
		<div class="box-icon">
			<a class="btn btn-primary btn-round" href="javascript:importDoc('csv');" style="padding-top:1px;" data-toggle="tooltip" data-placement="left" data-original-title="Import CSV">
				<i class="glyphicon glyphicon-upload icon-white"></i>
			</a>
		</div>
	~ ;
 
	$trigger_jquery_raw .= qq~
		function importDoc(t,b) {    
			dlgMdl("$useropts{'scripts'}/dialog/import_logistics_costs.pl?"+t+"&"+b,"Import CSV",'','max-dialog') ;
		}		
	~;

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

sub report_screen {

	our $lcol = 1 ;
	our $fcol = 3 ;

	$print_box_content_rows .= &common_min_forms_start('report') ;

	&db_min_ro("event_quotes","id,ref",'','','') ; 
	&db_min_ro("logistics_costs","DISTINCT event_nr",'','','') ; 
	
	# $db{logistics_costs}{"N/A"}{event_nr} = "N/A" ;
	
	my $event_na_exists = 0 ; my $events_exists = 0 ; my %selected = () ;
	
	&get_events_with_other_costs ;
	
	if ($i{event_id}) {
		$selected{$i{event_id}} = "SELECTED" ;
	} else {
		$selected{all} = "SELECTED" ;
	}
 
	# foreach (sort {$db{event_quotes}{$a}{ref} cmp $db{event_quotes}{$b}{ref}} keys %{$db{logistics_costs}}) {
	foreach (sort {$b <=> $a} keys %{$db{logistics_costs}}) {
		# $_ = "N/A" if $_ < 0 ;
		$_ = "N/A" if $_ < 0 ;
		$opts{event_id} .= qq~<option value="$_" $selected{$_}>[$_] $db{event_quotes}{$db{logistics_costs}{$_}{event_nr}}{ref}</option>~ if $_ ; 
		$event_na_exists = 1 unless $_ ;
		$events_exists++ ;
	}
	
	$opts{event_id} = qq~<option value="all" $selected{all}>All</option>~ . $opts{event_id} if $events_exists > 1 ;
	$opts{event_id} = qq~<option value="na_event" $selected{na_event}>Event Unknown</option>~ . $opts{event_id} if $event_na_exists ;
	
	$print_box_content_rows  .= &common_min_form_select('event_id','') ; 
	$print_box_content_rows  .= &common_min_form_input('cost_type') ; 
	
	$print_box_content_rows  .= &common_min_forms_end('','','report') ;

	&common_min_search_screen ;

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

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_table('id',$page,'list') ;

our $savjqy = 1 ;

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

$extra_form_fields .= qq~
	<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}">
~ ;

$trigger_jquery_raw .= qq~

	\$("#savebutt").click( function () {
		console.log("Hello World") ; 
		\$("#logistics-costs-form").submit() ;
	}) ;

~ ;

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

require _blank ;

exit ;

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

sub screen4 {
	
&common_min_alert_type ;

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>

\$(document).ready(function(){ \$('#$lcpage-form').submit(); })

</script>
</body>

<form role="form" id="$lcpage-form" method="post" action="">
	<input type="hidden" name="iaction"          value="report">
	<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}">
	<input type="hidden" name="isaved"           value="$success">
</form>
 
</html>
ENDOFTEXT
#

exit ;

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

use common ;
use report ;
use xlsxcreator ;
use today ;

1;