#!/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 ; 

&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 $debug   = 1 ;
our $testing = 1 ;

# if ($username ne 'handre') {
	# print "<< MAINTENANCE IN PROGRESS >>" ; exit ; 	
# }

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

&page_opts ;

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

if ($iaction eq 'save') {  	
	&db_open_upd ;
		our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
		&common_min_load_params ;
		&report_ifields;
		&update ;
		# &list_screen ;    
		$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
	&db_close_conn ;
	exit if $username eq 'rory' && $testing ;
	# &screen3;
	&redirect_screen;
}		

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

exit;

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

sub update {
	
	foreach (keys %i) {
		local @abc = split("_",$_) ;	
		if (substr($_,0,19) eq 'calibration_status_') {
			$seen_event_id{$abc[-3]} = 1 ;
		}
	}
	
	local @event_ids = () ; 
	foreach (keys %seen_event_id) {
		push @event_ids , "`id` = '$_'" ; 
	}
	local $e_q_sql = join (" OR ",@event_ids) ;
	
	&db_min_ro($table,'id,event_system_id_multiple,date_from,date_to,calibrator_amounts_paid,calibrator_dates_paid',"$e_q_sql",'','') ; 

	my %ii = () ; my %iii = %i  ;
	foreach (keys %i) {
		local @a = split("_",$_) ;
		
		my $upd_field = "paid_$a[-3]\_$a[-2]\_$a[-1]"  ; 
		next unless $i{$upd_field} ;
		
		if (substr($_,0,12) eq 'date_payable') {
			$ii{$a[-3]}{$a[-2]}{$a[-1]}{date_payable} = $i{$_} ;
		} elsif (substr($_,0,13) eq 'amount_payble') {
			$ii{$a[-3]}{$a[-2]}{$a[-1]}{amount_payble} = $i{$_} ;
		}
	}

	my %iii = %i  ;
	
	my $amnts_field	= 'calibrator_amounts_paid' ;
	my $dates_field	= 'calibrator_dates_paid' ;
	
	foreach my $event_id (keys %ii) {
		
		%i  = () ;
		
		# &common_debug("1. +++ event_id[$event_id] date_from[$db{$table}{$event_id}{date_from}] date_to[$db{$table}{$event_id}{date_to}]  event_system_calibration_ids[$db{$table}{$event_id}{event_system_calibration_ids}] event_system_calibration_status[$db{$table}{$event_id}{event_system_calibration_status}] event_system_id_multiple[$db{$table}{$event_id}{event_system_id_multiple}]") ; 
 
		my @event_system_ids		= split(";",$db{$table}{$event_id}{event_system_id_multiple}) ;
		my @calibrator_amounts_paid	= split(";",$db{$table}{$event_id}{calibrator_amounts_paid}) ; 		
		my @calibrator_dates_paid	= split(";",$db{$table}{$event_id}{calibrator_dates_paid}) ; 
		
		my @ed_from = &common_split_sql_time($db{$table}{$event_id}{date_from}) ;
		my @ed_to   = &common_split_sql_time($db{$table}{$event_id}{date_to}) ; 
		
		&common_date_array("$ed_from[0]$ed_from[1]$ed_from[2]","$ed_to[0]$ed_to[1]$ed_to[2]") ;
		
		$sys_cnt = 0;
		foreach my $system_id (@event_system_ids) {
			# next unless $system_id ;
			my (@calibrator_amounts_paid_per_event_day) = split(/\-/,$calibrator_amounts_paid[$sys_cnt]);
			my $sys_day=0;
			foreach my $_date (@common_date_array) {
				$sys_day++;
				$i{$amnts_field} .= ($ii{$event_id}{$system_id}{$sys_day}{amount_payble}) ? "$ii{$event_id}{$system_id}{$sys_day}{amount_payble}-" : ($calibrator_amounts_paid_per_event_day[$sys_day-1]) ? "$calibrator_amounts_paid_per_event_day[$sys_day-1]-" : '-'  ;
			}
			chop $i{$amnts_field} if $i{$amnts_field} ; 
			$i{$amnts_field} .= ";" ;
			$sys_cnt++;
		}
		chop $i{$amnts_field} if $i{$amnts_field} ; 
		
		$sys_cnt = 0;
		foreach my $system_id (@event_system_ids) {
			# next unless $system_id ;
			my (@calibrator_dates_paid_per_event_day) = split(/\:/,$calibrator_dates_paid[$sys_cnt]);
			my $sys_day=0;
			foreach my $_date (@common_date_array) {
				$sys_day++;
				$i{$dates_field} .= ($ii{$event_id}{$system_id}{$sys_day}{date_payable}) ? "$ii{$event_id}{$system_id}{$sys_day}{date_payable}:" : ($calibrator_dates_paid_per_event_day[$sys_day-1]) ? "$calibrator_dates_paid_per_event_day[$sys_day-1]:" : ':'  ;
			}
			chop $i{$dates_field} if $i{$dates_field} ; 
			$i{$dates_field} .= ";" ;
			$sys_cnt++;
		}
		chop $i{$dates_field} if $i{$dates_field} ;
		
		$ignore{$amnts_field} = 1 if $i{$amnts_field} eq $db{$table}{$event_id}{calibrator_amounts_paid} ;
		$ignore{$dates_field} = 1 if $i{$dates_field} eq $db{$table}{$event_id}{calibrator_dates_paid} ;
		
		&db_min_upd($table,"`id`='$event_id'") ; 		
	}
			
	%i = %iii ;
	
} #------------------------------------------------------------------------------------------

sub report_ifields {
	
	&load_search_vars ;
		
	if ($i{date_from} and $i{date_to}) { # check dates
		my $date_from_check = $i{date_from} ;
		   $date_from_check =~ s/\-//g ;
		my $date_to_check = $i{date_to} ;
		   $date_to_check =~ s/\-//g ;
		if ($date_from_check > $date_to_check) { 
			$error = qq~'$i{date_from}' > '$i{date_to}'~ ; &report_screen ; 
		}
		# push @report_sql, "((`date_from` >= '$i{date_from} 00:00:00' AND `date_from` <= '$i{date_to} 23:59:59') OR (`date_to` <= '$i{date_to} 23:59:59' AND `date_to` >= '$i{date_from} 00:00:00'))" ;
		# push @report_sql, "(('$i{date_from} 23:59:59' >= `date_from` AND '$i{date_from} 00:00:00' <= `date_to`) OR ('$i{date_to} 23:59:59' >= `date_from` AND '$i{date_to} 00:00:00' <= `date_to`))" ;
		# push @report_sql, "((`date_from` >= '$i{date_from} 00:00:00' AND `date_from` <= '$i{date_to} 23:59:59') OR (`date_to` >= '$i{date_from} 00:00:00' AND `date_to` <= '$i{date_to} 23:59:59'))" ;
		my @srch_ed_from = &common_split_sql_time($i{date_from}) ;
		my @srch_ed_to   = &common_split_sql_time($i{date_to}) ; 
		
		&common_date_array("$srch_ed_from[0]$srch_ed_from[1]$srch_ed_from[2]","$srch_ed_to[0]$srch_ed_to[1]$srch_ed_to[2]") ;
		
		@report_sql_or = () ;	
		
		foreach my $_srch_date (@common_date_array) {
			my $srch_ccyy_mm_dd = substr($_srch_date,0,4) . '-' . substr($_srch_date,4,2) . '-' . substr($_srch_date,6,2) ;
			push @report_sql_or, "('$srch_ccyy_mm_dd 23:59:59' >= date_from AND '$srch_ccyy_mm_dd 00:00:00' <= date_to)"
		}
		
		my $sql_or = join(' OR ',@report_sql_or) ;
		push @report_sql, "($sql_or)" if $sql_or ; 
		
		# push @report_sql, "((`date_from` >= '$i{date_from} 00:00:00' AND `date_from` <= '$i{date_to} 23:59:59') OR (`date_to` >= '$i{date_from} 00:00:00' AND `date_to` <= '$i{date_to} 23:59:59'))" ;
		push @report_results, "(BETWEEN '$i{date_from}' AND '$i{date_to}')" ;
	} elsif (not $i{date_from}) {
		$error = qq~PLEASE ENTER A START DATE!~ ; 
		&report_screen; 
	} elsif (not $i{date_to}) {
		$error = qq~PLEASE ENTER AN END DATE!~ ; 
		&report_screen; 
	}
	
	if ($i{calibrator_id} and $i{calibrator_id} ne 'all') { 
		push @report_results,"`CALIBRATOR` = '$db{users}{1}{name}'" ;
		push @report_sql, "
			(
				`event_system_calibration_ids` LIKE '%;$i{calibrator_id};%' OR 
				`event_system_calibration_ids` LIKE '%;$i{calibrator_id}' OR 
				`event_system_calibration_ids` LIKE '$i{calibrator_id};%' OR 
				`event_system_calibration_ids` LIKE '%-$i{calibrator_id};%' OR 
				`event_system_calibration_ids` LIKE '%;$i{calibrator_id}-%' OR
				`event_system_calibration_ids` LIKE '%-$i{calibrator_id}-%' OR	
				`event_system_calibration_ids` LIKE '$i{calibrator_id}-%' OR		
				`event_system_calibration_ids` LIKE '%-$i{calibrator_id}'				
			)
		" ; 
	} elsif ($i{calibrator_id} and $i{calibrator_id} eq 'all') {
		push @report_results,"`CALIBRATORS` = 'ALL'" ;
	} 
	
	if ($i{event_quote_id}) {
		&db_min_ro('event_quotes','1,ref',"`id`='$i{event_quote_id}'",'','') ; 
		push @report_sql, "(e.id = '$i{event_quote_id}')" ;
		push @report_results,"EVENT QUOTE = $db{event_quotes}{1}{ref}" ;		
	}
	
	if ($i{paid_status} eq 'paid') {
		push @report_results,"CALIBRATORS ARE ALL PAID" ;
		# push @report_sql, 
	} elsif ($i{paid_status} eq 'outstanding') {
		push @report_results,"CALIBRATOR PAY OUTSTANDING" ;
		# push @report_sql, 
	}	
	# if ($i{calibration_status} and $i{calibration_status} ne 'all') {
		# push @report_results,"`STATUS` = '$db{calibration_status}{$i{calibration_status}}{status}'" ;
	# }
		
	$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) ; 
	}
	
	our $srch_where_sql = join(' AND ',@report_sql) ; 
 
} #------------------------------------------------------------------------------------------

sub load_search_vars {
	 
	if ($i{calibrator_id} and $i{calibrator_id} ne 'all') { 
		&db_min_ro('users','1,name',"`id` = '$i{calibrator_id}'",'','') ;
	}
	
	&db_min_ro('calibration_status','id,status',"",'','') ; #`status` LIKE '%done%'
	
	our $calibration_status = 1 ; 
	
} #------------------------------------------------------------------------------------------

sub list_screen {
	
	$print_box_content_rows .= &common_min_forms_start("$lcpage") ;
	
	&calibration_load_list_vars("$srch_where_sql",1) ;
 
	$box_icon .= qq~<div class="box-icon" title='Toggle all Paid' data-toggle="tooltip" data-placement="left"><a class="btn btn-default btn-round" href="javascript:selectAll();" style="padding-top:1px;"><i class="glyphicon glyphicon-usd icon-white"></i></a></div>~ ;
	

	# $fcol = 2 ; 
	
	# $print_box_content_rows .= qq~<div style = "display:none;">~ ; 
	# $print_box_content_rows .= &common_min_form_input_col("date_from",$i{date_from}) ; #date_from_i_field
	# $print_box_content_rows .= &common_min_form_input_col("date_to",$i{date_to}) ; #date_to_i_field
	# $print_box_content_rows .= &common_min_form_input_col("calibrator_id",$i{calibrator_id}) ;  #operator_id_i_field
	# # $print_box_content_rows .= &common_min_form_input_col("event_quote_id",$i{event_quote_id}) ;
	# $print_box_content_rows .= &common_min_form_input_col("calibration_status",$i{calibration_status}) ;
	# $print_box_content_rows .= qq~</div>~ ;
	
	$fcol = 12 ; 
	
	my $report = 1 ; 
	
	our $xlsxdir = "calibrator_payments" ; 
	
	our $xlsxreportname = "Calibrator_Payments" ; 
 
	my $date = &common_write_date_interval($i{date_from},$i{date_to}) ;
	
	our $xlsx_title_heading = "Calibrator Payments $date" ;
	
	our $calibration_report = 1 ;
	
	our $paid_fields = qq~~ ;
	
	&calibration_build_table_and_or_excel(1,1) ; 
	
	if ($found_after_date) {
		
		$trigger_jquery_raw .= qq~
			\$("#itv-table tr th:nth-last-child(3)").css("width", "12.5%") ;
			\$("#itv-table tr th:nth-last-child(2)").css("width", "12.5%") ;
		~ ;	

	} else {
		$trigger_jquery_raw .= qq~
			\$("#itv-table tr th:nth-last-child(3)").css("width", "7.5%") ;
			\$("#itv-table tr th:nth-last-child(2)").css("width", "7.5%") ;
		~ ;
	}
	
	chop $paid_fields if $paid_fields ;
	
	&common_debug("paid_fields : $paid_fields " ) ;
	
	$trigger_jquery_raw .= qq~
		
		function selectAll() {
				
			console.log("selectAll") ;  	
				
			let jsObject = {
				$paid_fields
			};

			for (let key in jsObject) {
				let parts = key.split("_") ;
				let event_id 	= parts[0] ;
				let sys_id 		= parts[1] ;
				let day_cnt 	= parts[2] ;
				
				console.log("key : "+key) ;
				
				// console.log("event_id : "+event_id+" , sys_id : "+sys_id+" , day_cnt : "+day_cnt) ; 
				
				\$(\$("#itv-table").dataTable().fnGetNodes()).find(\$("input[name='paid_"+event_id+"_"+sys_id+"_"+day_cnt+"']")).each(function () { 
					if(\$(this).is(':checked')) { 
						\$(this).prop('checked',false);
					} else {
						\$(this).prop('checked',true);
					}
				}) ;
			}
		}
	~; 

	$fnsortorder = 'asc' ;
	
	&common_min_extra_crumb("$lcpage","Search Screen") ;
 
	$trigger_jquery_raw .= qq~
		\$("#savebutt").click(function() {
			\$("#$lcpage-form").submit() ;
		}) ;
	~ ;
	
} #------------------------------------------------------------------------------------------

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    = 'calibrator-payments' ;

	&common_page_name ;
	   
	our $table     = 'event_quotes' ;
	$page_title    = 'Calibrator Payments' ;

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

sub report_screen {

	our $lcol = 3 ;
	our $fcol = 5 ;

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

	# my ($sql_next_day) = &common_add_delta_days(1) ;
	# my ($next_year,$next_month,$next_day) = split(/\-/,$sql_next_day) ;
	
	my $days_in_month = Days_in_Month($now_year,$now_mm) ;
	
	$print_box_content_rows .= &common_min_form_datepicker('date_from',"$now_year-$now_mm-01") ; #unless $i{date_from} ;  
	$print_box_content_rows .= &common_min_form_datepicker('date_to',"$now_year-$now_mm-$days_in_month") ;

	$selected{calibration_status}{all} = 'SELECTED' ;
	if ($i{calibration_status}) {
		$selected{calibration_status}{$i{calibration_status}} = 'SELECTED' ;
		$selected{calibration_status}{all} = '' ;
	} 
	
	# # &db_min_ro('calibration_status','id,status','','','') ;
	
	# # $opts{calibration_status} .= qq~<option value="-1" $selected{calibration_status}{-1}>None</option>~ ; 
	# foreach (keys %{$db{calibration_status}}) {
		# $opts{calibration_status} .= qq~<option value="$_" $selected{calibration_status}{$_} >$db{calibration_status}{$_}{status}</option>~ ; 
	# }
	# $opts{calibration_status} .= qq~<option value="all" $selected{calibration_status}{all} >All</option>~ ; 
	
	# $preferred_title{calibration_status} = "Status" ;
	
	$preferred_title{calibrator_id} = "Calibrator" ;
	
	# &db_min_ro('users',"id,name","`user_type` = 'support' OR `user_type` = 'casual_calibrator'",'','') ;
	&db_min_ro('users',"id,name,username","(user_type = 'casual_calibrator') AND name NOT LIKE 'Rory%'",'','') ;

	$selected{calibrator_id}{all} = 'SELECTED' ;
	
	if ($i{calibrator_id}) {
		$selected{calibrator_id}{$i{calibrator_id}} = 'SELECTED' ;
		$selected{calibrator_id}{all} = '' ;
	} 
	
	# $opts{calibrator_id} .= qq~<option value="-1" $selected{calibrator_id}{-1}>None</option>~ ; 
	foreach (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) {
		next if $useropts{it}{$db{users}{$_}{username}} ;
		$opts{calibrator_id} .= qq~<option value="$_" $selected{calibrator_id}{$_}>$db{users}{$_}{name}</option>~ ; 
	}
	$opts{calibrator_id} .= qq~<option value="all" $selected{calibrator_id}{all}>All</option>~ ; 

	$opts{paid_status} .= qq~<option value="all">All</option>~ ; 
	$opts{paid_status} .= qq~<option value="paid">Paid</option>~ ; 
	$opts{paid_status} .= qq~<option value="outstanding" SELECTED>Outstanding</option>~ ; 


	&common_min_select_opts('event_quote_id','event_quotes',"ref",$i{event_quote_id},'','',"") ;
	
	# if ($i{event_quote_id}) {
		# $selected{event_quote_id}{$i{event_quote_id}} = 'SELECTED' ;
	# } else {
		# $selected{event_quote_id}{all} = 'SELECTED' ;
	# }	
	
	# $opts{event_quote_id} .= qq~<option value="all" $selected{event_quote_id}{all}>All</option>~ ; 	
	
	# $print_box_content_rows  .= &common_min_form_select('operator_id','') ; 
	# $print_box_content_rows  .= &common_min_form_select('event_quote_id','') ; 
	# $print_box_content_rows  .= &common_min_form_select('calibration_status','') ; 
	$print_box_content_rows  .= &common_min_form_select('calibrator_id','') ; 
	
	$print_box_content_rows  .= &common_min_form_select('event_quote_id','') ; 
	$print_box_content_rows  .= &common_min_form_select('paid_status','') ; 
	$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="date_from" 			value="$i{date_from}">
<input type="hidden" name="date_to"				value="$i{date_to}">
<input type="hidden" name="calibrator_id"		value="$i{calibrator_id}">
<input type="hidden" name="calibration_status" 	value="$i{calibration_status}">~;

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

require _blank ;

exit ;

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

sub redirect_screen {
	
&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="$lcpage">
<input type="hidden" name="iaction"				value="report">
<input type="hidden" name="date_from"        	value="$i{date_from}">
<input type="hidden" name="date_to"          	value="$i{date_to}">
<input type="hidden" name="calibrator_id"      	value="$i{calibrator_id}">
<input type="hidden" name="calibration_status"	value="$i{calibration_status}">
<input type="hidden" name="isaved"				value="$success">
</form>

</html>
ENDOFTEXT
#

exit ;

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

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

1;