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

&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 $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab

#-------- 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 '' ; 
	
	if ($iaction eq 'report') {  	
		&common_min_load_params ;
		&report_ifields;
		&list_screen ;    
		&screen3;
	}
	
	if ($iaction eq 'save') {  	
		&common_min_load_params ;
		&update ;
		&screen4;
	}
	
	&common_min_action;
	$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
&db_close_conn ;

exit;

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

sub update {
	
	# our $testing = 1 ;
	
	my %iii = %i ; 
	my %ii = () ; 
	local $min_id = 0 ; local $max_id = 0 ; 
	foreach (sort keys %i) {
		local $cell_name = $_ ;
		local @a = split("_") ;
		next if $a[-2] ne int($a[-2]) ;
		
		if ($i{"paid_$a[-2]\_$a[-1]"} and $i{"amount_payble_$a[-2]\_$a[-1]"}) {
			if ($a[0] eq 'amount') {
				$i{$_} = sprintf("%.2f",$i{$_}) ;
				$ii{$a[-2]}{$a[-1]}{operator_amounts_paid} .= qq~$a[-1]:$i{$_}~ ;
			} elsif ($a[0] eq 'date') {
				$ii{$a[-2]}{$a[-1]}{operator_dates_paid} .= qq~$i{$_}~ ; 
			}
		}
		$min_id = $a[-2] if ($min_id and $a[-2] < $min_id) or not $min_id ; 
		$max_id = $a[-2] if $a[-2] > $max_id ;
	}	
	
	&db_min_ro('event_quotes_min',"id,operator_dates_paid,operator_amounts_paid,operator_dates_paid_min","`id` <= '$max_id' AND `id` >= '$min_id'",'','') ; 
	&common_debug("SELECT id,operator_dates_paid,operator_amounts_paid FROM event_quotes_min WHERE `id` <= '$max_id' AND `id` >= '$min_id'") ;
	
	foreach my $id (sort keys %ii) {
		
		%i = () ;
		$i{operator_dates_paid} = '' ; 
		$i{operator_amounts_paid} = '' ;
		
		foreach my $op_id (keys %{$ii{$id}}) {
			$i{operator_dates_paid} .= qq~;~ if $i{operator_dates_paid} ; 
			$i{operator_amounts_paid} .= qq~;~ if $i{operator_amounts_paid} ;
			$i{operator_dates_paid} .= qq~$ii{$id}{$op_id}{operator_dates_paid}~ ;
			$i{operator_amounts_paid} .= qq~$ii{$id}{$op_id}{operator_amounts_paid}~ ;				
		} 
		
		$i{operator_amounts_paid} = qq~$db{event_quotes_min}{$id}{operator_amounts_paid};$i{operator_amounts_paid}~ if $db{event_quotes_min}{$id}{operator_amounts_paid} ;
		# $ignore{operator_amounts_paid} = 1 unless $i{operator_amounts_paid} ;

		$i{operator_dates_paid} = qq~$db{event_quotes_min}{$id}{operator_dates_paid};$i{operator_dates_paid}~ if $db{event_quotes_min}{$id}{operator_dates_paid} ;
		# $ignore{operator_dates_paid} = 1 unless $i{operator_dates_paid} ;
																  
		my @dates = split(/\;/,$i{operator_dates_paid}) ;
		my $all_same = 1 ;	my $prev_date = "" ;
		foreach my $date (@dates) {
			if ($prev_date && $date ne $prev_date) {
				$all_same = 0;
				last;
	 
						
			}
			$prev_date = $date ;
		}

		if ($all_same) {
			$i{operator_dates_paid_min} = $dates[0] ;
		} else {
			$i{operator_dates_paid_min} = $i{operator_dates_paid} ;
		}
		
		$ignore{operator_dates_paid_min} 	= ((!$i{operator_dates_paid_min} 	&& !$db{event_quotes_min}{$id}{operator_dates_paid_min}) 	|| ($i{operator_dates_paid_min} && $db{event_quotes_min}{$id}{operator_dates_paid_min} 	&& $i{operator_dates_paid_min} 	eq $db{event_quotes_min}{$id}{operator_dates_paid_min})) 	? 1 : 0 ;
		$ignore{operator_dates_paid} 		= ((!$i{operator_dates_paid} 		&& !$db{event_quotes_min}{$id}{operator_dates_paid})		|| ($i{operator_dates_paid} 	&& $db{event_quotes_min}{$id}{operator_dates_paid} 		&& $i{operator_dates_paid} 		eq $db{event_quotes_min}{$id}{operator_dates_paid})) 		? 1 : 0 ;
		$ignore{operator_amounts_paid} 		= ((!$i{operator_amounts_paid} 		&& !$db{event_quotes_min}{$id}{operator_amounts_paid}) 		|| ($i{operator_amounts_paid} 	&& $db{event_quotes_min}{$id}{operator_amounts_paid} 	&& $i{operator_amounts_paid} 	eq $db{event_quotes_min}{$id}{operator_amounts_paid})) 		? 1 : 0 ;
		
		&db_min_upd("event_quotes_min","id='$id'") if !$ignore{operator_dates_paid_min} || !$ignore{operator_dates_paid} || !$ignore{operator_amounts_paid}; 
		
		# &common_debug("UPDATE event_quotes_min SET operator_dates_paid = $i{operator_dates_paid},operator_amounts_paid = $i{operator_amounts_paid} WHERE id = '$id'") if $i{operator_dates_paid} or $i{operator_amounts_paid} ; 
	}

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

sub report_ifields {
	
	our $where_min = qq~~ ; 
	
	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 ; 
		}
		if ($i{paid_status} eq 'paid') {
			# $where_min .= "(m.operator_dates_paid LIKE '%;%' OR (m.operator_dates_paid NOT LIKE '%;%' AND (m.operator_dates_paid >= '$i{date_from}' AND m.operator_dates_paid <= '$i{date_to}')))" ;
			push @report_sql_min, "(m.operator_dates_paid_min LIKE '%;%' OR (m.operator_dates_paid_min NOT LIKE '%;%' AND (m.operator_dates_paid_min >= '$i{date_from}' AND m.operator_dates_paid_min <= '$i{date_to}')))" ;
			push @report_results, "(AMOUNTS PAID BETWEEN '$i{date_from}' AND '$i{date_to}')" ;			
		} else {
			push @report_sql, "((e.date_from >= '$i{date_from} 00:00:00' AND e.date_from <= '$i{date_to} 23:59:59') OR (e.date_to <= '$i{date_to} 23:59:59' AND e.date_to >= '$i{date_from} 00:00:00'))" ;
			push @report_results, "(BETWEEN '$i{date_from}' AND '$i{date_to}')" ;			
		}
	} elsif (not $i{date_from}) {
		$error = qq~PLEASE ENTER A START DATE!~ ; 
	} elsif (not $i{date_to}) {
		$error = qq~PLEASE ENTER A END DATE!~ ; 
	}
	
	
	if ($i{operator_id}) { 
		&db_min_ro('users','1,name',"`id` = '$i{operator_id}'",'','') ;
		# $where_min = "(m.operator_workings_event LIKE '%;$i{operator_id};%' OR m.operator_workings_event LIKE '$i{operator_id};%' OR m.operator_workings_event LIKE '%;$i{operator_id}')" ;
		
		# $where_min .= qq~ AND ~ if $where_min ; 
		# $where_min .= "FIND_IN_SET($i{operator_id},REPLACE(m.operator_workings_event,';',','))" ;
		push @report_sql_min, "FIND_IN_SET($i{operator_id},REPLACE(m.operator_workings_event,';',','))" ;
		push @report_results,"OPERATOR = $db{users}{1}{name}" ;
	}

	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,"OPERATOR ARE ALL PAID" ;
		
	} elsif ($i{paid_status} eq 'outstanding') {
		push @report_results,"OPERATORS PAY OUTSTANDING" ;
	}
		
	$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('invoice') ;
	
	push @report_sql, "(e.quote_completed = '1')" ;
	
	my $srch_where_sql 		= join(' AND ', @report_sql) ;
	my $srch_where_sql_min 	= join(' AND ', @report_sql_min) ;
	
	our @sql_col_display = 
		($i{paid_status} eq 'all') ? 	("event_quote_nr","operator_names","event_name","event_date_from","event_date_to","description","amount","date_paid","amount_paid","date_payable","amount_payable","paid") : 
		($i{paid_status} eq 'paid') ? 	("event_quote_nr","operator_names","event_name","event_date_from","event_date_to","description","amount","date_paid","amount_paid","paid") : 
										("event_quote_nr","operator_names","event_name","event_date_from","event_date_to","description","amount","date_payable","amount_payable","paid") ;
	
	my $table_colspan = 0 ; 
	
	foreach (@sql_col_display) { 
		$table_colspan += 1 ; 
	}

	&report_xlsx_export_header("Operators_Report$xlsreportname",'operators_report') ;

	&load_list_vars("$srch_where_sql","$srch_where_sql_min") ;
	
	my $field = "" ; 
	my $row_cnt = 0 ; my $first_id = 0 ; my $last_id = 0 ; my %row_cnt_to_id = () ; 
	
	$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("operator_id",$i{operator_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("operators_paid",$i{operators_paid}) ;  
	$print_box_content_rows .= qq~</div>~ ; 
	
	$fcol = 12 ; my $val_min = 0 ; $row_cnt = 0 ;
	
	 my $quote_and_ops_ids = qq~~ ; my $op_ids = qq~~ ; my %historic_payments_tooltip = () ; 
	
	our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; 
	
	my $datefrom = $i{date_from} ;
	my $dateto = $i{date_to} ;
	
	$datefrom =~ s/\-//g ;
	$dateto =~ s/\-//g ;
	
	$datefrom = int($datefrom) ; 
	$dateto = int($dateto) ; 
	
	foreach my $id (sort {$b <=> $a} keys %{$db{$tables}}) {
		
		if ($i{client_id}) { 
			next unless $client{$i{client_id}} eq $quote_customer{$id} ; 
		}

		$cnt_in_stock  = -1 ; 
		my $in_stock   = "" ; 
		
		$db{$tables}{$id}{operator_dates_paid} = $db{$tables}{$id}{operator_dates_paid_min} ;

		my @date_pay      = split(";",$db{$tables}{$id}{operator_dates_paid}) ;
		my @amount_pay    = split(";",$db{$tables}{$id}{operator_amounts_paid}) ;
		# my @paid        = split(";",$db{$tables}{$id}{amount_is_paid_workings_event}) ;
		my @qty_work      = split(";", $db{$tables}{$id}{qty_workings_event}) ;
		my @amnt_usd_work = split(";", $db{$tables}{$id}{amount_usd_workings_event}) ;
		my @amnt_work     = split(";", $db{$tables}{$id}{amount_workings_event}) ;
		my @op_work       = split(";", $db{$tables}{$id}{operator_workings_event}) ;
		my @paid_work     = split(";", $db{$tables}{$id}{paid_workings_event}) ; # ????
		my @description   = split(";", $db{$tables}{$id}{description_workings_event}) ;
		
		# &common_debug("[$tables] $id -> $db{$tables}{$id}{operator_ids} [amount_workings_event=$db{$tables}{$id}{amount_workings_event}]") ;

		my $tot_amnt_work = 0 ; my %tot_amnt = () ; my %amnt_paid = () ; my $amount_paid = 0 ; my %historic_payments_tooltip = () ; my %historic_payments = () ; my %historic_payments_raw = () ;
		
		my $amnt_cnt = -1 ;
		
		foreach (@amount_pay) {
			$amnt_cnt++ ;	
			$amount_paid += $_ ;
			my ($op_id,$amnt_paid) = split(/\:/,$_) ; 
			my $date_paid = ($db{$tables}{$id}{operator_dates_paid_min} !~ /;/) ? $date_pay[0] : $date_pay[$amnt_cnt] ;
			if ($db{$tables}{$id}{operator_dates_paid} =~ /;/ && $i{paid_status} eq 'paid' && ($i{date_from} || $i{date_to})) {
				my $date_paid_int = $date_paid ; 
				$date_paid_int =~ s/\-//g ; 
				$date_paid_int = int($date_paid_int) ;  
				next if ($i{date_from} && $datefrom > $date_paid_int) || ($i{date_to} && $dateto < $date_paid_int) ;	
			}
			
			$historic_payments_tooltip{$id}{$op_id} .= qq~<br>~ if $historic_payments_tooltip{$id}{$op_id} ;
			$historic_payments_tooltip{$id}{$op_id} .= qq~PAID $amnt_paid ON ~ . &common_min_date_as_string($date_paid)   ;
			$historic_payments{$id}{$op_id}{date} .= qq~<br>~ if $historic_payments{$id}{$op_id}{date} ;
			$historic_payments{$id}{$op_id}{date} .= &common_min_date_as_string($date_paid) ; # qq~$date_paid~ ;
			$historic_payments{$id}{$op_id}{amnt} .= qq~<br>~ if $historic_payments{$id}{$op_id}{amnt} ;
			$historic_payments{$id}{$op_id}{amnt} .= qq~$amnt_paid~ ;
		}
		
		my %description_toolip = () ; my %seen_des = () ; my $cnt_des = -1 ; my %seen_op = () ; 

		foreach (@description) {
			$cnt_des++ ;
			next if $op_work[$cnt_des] != $i{operator_id} and $i{operator_id} ; 
			next unless $op_work[$cnt_des] ;
			next if $seen_des{$_} and $seen_op{$_} ; 
			$seen_des{$_} = 1 ; $seen_op{$op_work[$cnt_des] } = 1 ; 
			$description_toolip{$op_work[$cnt_des]} .= qq~<br>~ if $description_toolip{$op_work[$cnt_des]} ;
			$description_toolip{$op_work[$cnt_des]} .= qq~$db{event_cost_items}{$_}{name}~ ;
			
		}

		my $operator_toolip = qq~~ ; my %seen_op = () ; my $cnt_op = -1 ; 
		
		foreach (@op_work) {
			$cnt_op++ ;	
			next if $op_work[$cnt_op] != $i{operator_id} and $i{operator_id} ; 
			next unless $op_work[$cnt_op] ;
			next if $seen_op{$_} ; 
			$seen_op{$_} = 1 ; 
			$operator_toolip .= qq~<br>~ if $cnt_op ;
			$operator_toolip .= qq~$casual_names_from_ids{$_}~ ;
		}
		
		my %amnt_toolip = () ; my $cnt_amnt = -1 ; 

		foreach (@amnt_work) {
			$cnt_amnt++ ;
			next if $op_work[$cnt_amnt] != $i{operator_id} and $i{operator_id} ; 
			next unless $op_work[$cnt_amnt] ; 
			$amnt_toolip{$op_work[$cnt_amnt]} .= qq~<br>~ if $amnt_toolip{$op_work[$cnt_amnt]} ; 
			$amnt_toolip{$op_work[$cnt_amnt]} .= qq~$_~ ; 
			$tot_amnt{$op_work[$cnt_amnt]} += $_ ; 
		}
		
		foreach (@amount_pay) {
			my @abc = split(":",$_) ; 
			$amnt_paid{$abc[0]} += $abc[1] ;
		}

		my $amnt_usd_toolip = qq~~ ; my $cnt_usd_amnt = 0 ; 
		
		my $column_count = 0 ; 
		# $row_cnt = 0 ;
		
		$op_ids = qq~~ ;
		
		# my $operators_count = 0 ; 
			
		foreach my $op_id (sort {$casual_names_from_ids{$a} cmp $casual_names_from_ids{$b}} keys %seen_op) { 

			next if !$historic_payments{$id}{$op_id}{date} && $i{paid_status} eq 'paid' ;
			
			local $amnt_owed = $tot_amnt{$op_id} - $amnt_paid{$op_id} ;
			
			if ($amnt_owed <= 0.00001 && $amnt_owed >= -0.00001) {
				$amnt_owed = 0 ;
			}
			
			next if $i{paid_status} eq 'outstanding' && $amnt_owed <= 0 ;
			# next if $i{paid_status} eq 'paid' && $amnt_owed > 0 ;
			
			$first_id = $id unless $first_id ; 
			$last_id = $id if $last_id < $id ; 
			
			$amnt_owed = sprintf("%.2f",$amnt_owed) ; 
			
			$count_outstanding++ if $amnt_owed > 0 ;
			
			$op_ids .= qq~$op_id,~ ;
			
			$column_count++ ; 

			$xlsxcol = 0 ;
			$print_tbody .= qq~<tr id="$id">~ ;	
			$row_cnt++ ;
			
			foreach (@sql_col_display) { 
				
				next unless $_ ; # blank for the buttons column
				$display = 1 ; 
				my $val = $db{$tables}{$id}{$_} ;
				my $align = '' ;
				my $center = qq~ class="dt-center"~ ;
				$align = $center ;

				if ($_ eq 'event_date_from' or $_ eq 'event_date_to') {
					$val = $db{$tables}{$id}{date_from} if $_ eq 'event_date_from'  ;
					$val = $db{$tables}{$id}{date_to} if $_ eq 'event_date_to'  ;
					$val = &common_min_date_as_string(substr($val,0,10)) ;
				} elsif ($_ eq 'operator_names') {
					$val = $casual_names_from_ids{$op_id} ;					
				} elsif ($_ eq 'amount') {
					$tot_amnt{$op_id} = sprintf("%.2f",$tot_amnt{$op_id}) ; 
					$val = qq~<div title="$amnt_toolip{$op_id}" data-toggle="tooltip" data-placement="top">$tot_amnt{$op_id}</div>~ ; 
					$amnt_toolip{$op_id} = s/\<br>/\;/g ; 
					$val_min = "$tot_amnt{$op_id}" ; 
					# $val_min .= " [$amnt_toolip{$op_id}]" if $amnt_toolip{$op_id} && $amnt_toolip{$op_id} =~ /;/ ;	
				} elsif ($_ eq 'event_quote_nr') { 
					# my $class = 'info' ; 
					# if ($quote_status{$id} == 1) {
						# $class = 'danger' ;
					# } elsif ($quote_status{$id} == 2) {
						# $class = 'success' ; 
					# } elsif ($quote_status{$id} == 3) {
						# $class = 'danger' ;
					# } elsif ($quote_status{$id} == 4) {
						# $class = 'warning' ; 
					# }
					# $val = qq~<a class="btn btn-$class btn-xs" href="javascript:editMinItem('$id');">$id</a>~ ; 
					
					my $sort_val = sprintf("%09d",$id) ;
					
					$val = qq~<span style="display:none;">$sort_val</span>~ . &common_min_get_event_quote_button($id,$tables) ; 
					
				} elsif ($_ eq 'date_paid') {
					$val = join("<br>", map { $_ } split(/\<br>/,$historic_payments{$id}{$op_id}{date})) ;
					$val_min = $val ; 
					$val_min =~ s/\<br>/\;/g ;
				} elsif ($_ eq 'amount_paid') {
					$val = $historic_payments{$id}{$op_id}{amnt} ; 
					$val_min = $val ;
					$val_min =~ s/\<br>/\;/g ;
				} elsif ($_ eq 'date_payable') {
					
					# my $date_paid = ($db{$tables}{$id}{operator_dates_paid_min} !~ /;/) ? $date_pay[0] : $date_pay[$column_count - 1] ;

					if ($historic_payments{$id}{$op_id}{date}) {
						# $val     = ($amnt_owed > 0) ? &common_min_form_input_col("date_$id\_$op_id",$date_pay[$column_count - 1]) : "N/A" ;
						# $historic_payments_tooltip{$op_id} = qq~PAID<br>$historic_payments_tooltip{$op_id}~ if $historic_payments_tooltip{$op_id} ;
						# $historic_payments_tooltip{$op_id} = qq~~ ;
						$val     = ($amnt_owed > 0) ? &common_min_form_input_col("date_$id\_$op_id","$now_year-$now_mm-$now_dd") : ($historic_payments_tooltip{$id}{$op_id}) ? qq~<span title="$historic_payments_tooltip{$id}{$op_id}" data-toggle="tooltip" data-placement="top">N/A</span>~ : "N/A" ;
						$val_min = ($amnt_owed > 0) ? $date_paid : "N/A" ;
					} else {
						# my $date_payable = ($i{date_to}) ? $i{date_to} : "$now_year-$now_mm-$now_dd" ;
						my $date_payable = "$now_year-$now_mm-$now_dd" ;
						$val = &common_min_form_input_col("date_$id\_$op_id",$date_payable) ;
						$val_min = $date_payable ;
					}					
				} elsif ($_ eq 'amount_payable') {
						$val     = ($amnt_owed > 0) ? &common_min_form_input_col("amount_payble_$id\_$op_id",$amnt_owed) : $amnt_owed ;
						$val_min = $amnt_owed ;
				} elsif ($_ eq 'paid') {		
					# if ($amount_pay[$column_count - 1]) {
						# $val = ($amnt_owed > 0) ? &common_min_form_checkbox_col("paid_$id\_$op_id",1) : '<i class="glyphicons glyphicons-tick"></i>' ;	
					# } else {
						# $val = ($amnt_owed > 0) ? &common_min_form_checkbox_col("paid_$id\_$op_id",0) : '<i class="glyphicons glyphicons-tick"></i>' ;
					# }
					
					$val = ($amnt_owed > 0 && $i{paid_status} ne 'paid') ? &common_min_form_checkbox_col("paid_$id\_$op_id",0) : '<i class="glyphicons glyphicons-tick"></i>' ;
					$val_min = ($amnt_owed > 0) ? "No" : "Yes" ;
				} elsif ($_ eq 'event_name') {
					$val = $db{$tables}{$id}{ref} ;
				} elsif ($_ eq 'description') {
					if ($description_toolip{$op_id} =~ '<br>') {
						$val = qq~<i class="glyphicon glyphicon-list-alt" title="$description_toolip{$op_id}" data-toggle="tooltip" data-placement="top"></i>~ ; 
						$description_toolip{$op_id} = s/\<br>/\;/g ; 			
					} else {
						$val = $description_toolip{$op_id} ; 
					}
					$val_min = $description_toolip{$op_id} ; 
					$val_min =~ s/\<br>/\;/g ;
				}
				if ($_ ne 'event_quote_nr' and $_ ne 'availablity' and $_ ne 'qty' and $_ ne 'date_payable' and $_ ne 'amount_payable' and $_ ne 'paid' and $_ ne 'amount' and $_ ne 'description' and $_ ne 'amount_paid' and $_ ne 'date_paid') {
					&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format_management_report_data) ; 	
				} elsif ($_ eq 'event_quote_nr') {
					&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$id,$format_management_report_data_ref_nr) ; 	
				} elsif ($_ eq 'availablity') {
					if ($availability{$id}{$db{$tables}{$id}{$field}}) {
						&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$availability{$id}{$db{$tables}{$id}{$field}},$format_management_report_data)  ; 
					} else {
						&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,"No Response",$format_management_report_data)  ; 
					}	
				} elsif ($_ eq 'qty'){
					&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format_management_report_data_ref_nr) ; 	
				} elsif ($_ eq 'date_paid' or $_ eq 'amount_paid' or $_ eq 'date_payable' or $_ eq 'amount_payable' or $_ eq 'paid' or $_ eq 'amount' or $_ eq 'description') {
					&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$format_management_report_data) ; 	
				} 
				$xlsxcol++; 
				# if ($_ eq 'ref_nr' or $_ eq 'camera_nr')	{ $val = &common_camera_links($tables,$id,$val)  ;} 
				$print_tbody .= qq~<td $align>$val</td>~ ;  
			}		
			$print_tbody .= qq~</tr>~ ;
			$xlsxrow++ ;
			$quote_and_ops_ids .= qq~"$row_cnt\_$id":"$op_id",~ if $op_id ; 
		}
		
		chop $op_ids if $op_ids ; 
		# $quote_and_ops_ids .= qq~"$row_cnt_$id":[$op_ids],~ if $op_ids ; 

	}
	
	chop $quote_and_ops_ids if $quote_and_ops_ids ;
	
	# $print_tbody .= qq~<tr>~ ;
	# $print_tbody .= qq~</tr>~ ;
	$worksheet{$ws} -> set_column(0, 0, 15) ;
	$worksheet{$ws} -> set_column(1, 1, 20) ;
	$worksheet{$ws} -> set_column(2, 2, 40) ;
	$worksheet{$ws} -> set_column(3, 8, 20) ;
	if ($i{paid_status} eq 'all') {
		$worksheet{$ws} -> set_column(9, 10, 20) ;
		$worksheet{$ws} -> set_column(11, 11, 10) ;
	} else {
		$worksheet{$ws} -> set_column(9, 9, 10) ;
	}
	# $worksheet{$ws} -> set_column(10, 10, 25) ;
	$worksheet{$ws} -> set_row(0, 30) ;
	$worksheet{$ws} -> set_row(2, 20) ;

	$box_icon .= qq~<div class="box-icon" title='Toggle all Selected' 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>~ ;
	
	&report_xlsx_export_footer('L',15,'operators_report') ;
	
	$fnsortcol   = 0; 
	$fnsortorder = 'desc' ;
	&common_min_extra_crumb("$lcpage\s","Search Screen") ;
					
	$trigger_jquery_raw .= qq~
	
	function selectAll() {
				
		let jsObject = {
			$quote_and_ops_ids
		};

		for (let key in jsObject) {
			let op_id = jsObject[key];
			
			let parts = key.split("_") ;
			let event_id = parts[1] ;
			
			\$(\$("#itv-table").dataTable().fnGetNodes()).find(\$("input[name=paid_"+event_id+"_"+op_id+"]")).each(function () {      
				
				console.log("input[name=paid_"+event_id+"_"+op_id+"]") ; 
				if(\$(this).is(':checked')) { 
					\$(this).prop('checked',false);
				} else {
					\$(this).prop('checked',true);
				}
			}) ;
		}
	}
	~;
	
	my $savebuttjs = ($count_outstanding > 0) ? '$("#invoice-form").submit();' : 'noty({text:"There are no operators to pay!",layout:"center",type:"error",timeout:3000});return;' ;
	
	$trigger_jquery_raw .= qq~\$("#savebutt").click(function() {    
		$savebuttjs
	});

	~ ;
	
} #------------------------------------------------------------------------------------------

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 load_list_vars {
	
	my ($where,$where_min) = @_ ;
	
	our %quote_status = () ; 
	
	# &db_min_ro('event_quotes',"id, quote_cancelled, quote_accepted, if(concat(quote_expiry, ' 00:00:00') < now(), 1, 0) as 'expired', quote_pending","$where",'','');
	# &db_min_ro('event_quotes',"id, quote_cancelled, quote_accepted, quote_pending, quote_completed","$where",'','');
	
	my $t1      = "$table" ;
	my $t2      = 'event_quotes_min' ;
	our $tables = "$t1,$t2" ;

	# &db_min_raw("SELECT e.id,e.quote_cancelled,e.quote_accepted,e.quote_pending,e.quote_completed,e.quote_rejected FROM $t1 e WHERE $where;");
	
	# foreach $row (@$rows_array_ref) {        
		# for (0 .. $col_cnt){
			# $db{$table}{@$row[0]}{$col_name{$_}} = @$row[$_] ;
        # }    
    # }
	
	# foreach my $id (keys %{$db{$table}}) { 
		# if ($db{$table}{$id}{quote_cancelled} == 1){
			# $quote_status{$id} = 1 ; 
		# } elsif ($db{$table}{$id}{quote_accepted} == 1 || $db{$table}{$id}{quote_completed} == 1){
			# $quote_status{$id} = 2 ; 
		# } elsif ($db{$table}{$id}{quote_rejected} == 1){
			# $quote_status{$id} = 3 ; 
		# } elsif ($db{$table}{$id}{quote_pending} == 1) {
			# $quote_status{$id} = 4 ; 
		# }
	# }
	
	our %availability = () ; 
	
	&db_min_raw("
		SELECT e.event_quote_nr, e.user_id, e.category FROM events e 
		LEFT JOIN ( 
			select id, name, user_type FROM users WHERE user_type like '%casual%' 
		) u on u.id = e.user_id ;
	") ; 
	
	foreach $row (@$rows_array_ref) { 
		if (@$row[2] eq 'available') {
			$availability{@$row[0]}{@$row[1]} = "Available" ;
		} elsif (@$row[2] ne 'available' and @$row[2]) {
			$availability{@$row[0]}{@$row[1]} = "Not Available" ;
		} 
	}
	
	our %type_a_users = () ; 
	our %type_b_users = () ; 
	our %casual_names_from_ids = () ;
	
	&db_min_ro('users','id,name,user_type',"user_type LIKE 'casual%'",'','') ;
	foreach my $id (keys %{$db{'users'}}){
		$type_a_users{$id} = "A" if $db{'users'}{$id}{user_type} eq "casual_a" ;
		$type_b_users{$id} = "B" if $db{'users'}{$id}{user_type} eq "casual_b" ;
		
		# &common_debug("[$db{'users'}{$id}{user_type}] $db{'users'}{$id}{name}") ;
		
		$casual_names_from_ids{$id} =  $db{'users'}{$id}{name} ; 
	}
	
	my @event_quote_ids = () ; 
	
	# &db_min_ro($table,'*',"$where",'','') ;
	
	# &db_min_ro('event_quotes_min','*',"$where_min",'','') ;
	
	$where .= " AND $where_min" if $where_min ;
						
	&db_min_raw("SELECT e.*, m.* FROM $t1 e LEFT JOIN $t2 m ON e.id = m.id WHERE $where;");
	
	foreach $row (@$rows_array_ref) {        
		for (0 .. $col_cnt){
			# &common_debug("[$_] $col_name{$_} -> @$row[$_]") ;
			$db{$tables}{@$row[0]}{$col_name{$_}} = @$row[$_] ;
			
			if ($col_name{$_} eq 'quote_cancelled' && @$row[$_] == 1) {
				$quote_status{@$row[0]} = 1 ; 
			} elsif (($col_name{$_} eq 'quote_accepted' || $col_name{$_} eq 'quote_completed') && @$row[$_] == 1) {
				$quote_status{@$row[0]} = 2 ; 
			} elsif ($col_name{$_} eq 'quote_rejected' && @$row[$_] == 1) {
				$quote_status{@$row[0]} = 3 ; 
			} elsif ($col_name{$_} eq 'quote_pending' && @$row[$_] == 1) {
				$quote_status{@$row[0]} = 4 ; 
			}	
        }
    }
	
	&db_min_ro('event_cost_items','id,name','','','') ;
	
	if ($i{paid_status} eq 'paid') {
		&db_min_ro('shift_operator_ids','date,temp_calibrator_amounts_paid,temp_calibrator_dates_paid',"`date`<='$i{date_to}' AND `date`>='$i{date_from}'",'','') ;
	}

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

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

sub page_opts {

	our $glyphicon = 'list' ;
	our $lcpage    = 'operator-payment' ;

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

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

sub report_screen {

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

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

	&common_min_select_opts('operator_id','users',"name",$i{operator_id},'','',"user_type LIKE 'casual%'") ;
	&common_min_select_opts('event_quote_id','event_quotes',"ref",$i{event_quote_id},'','id',"") ;

	$first_day_month = sprintf("%02d",$first_day_month) ; $first_day = sprintf("%02d",$first_day) ;
	$print_box_content_rows .= &common_min_form_datepicker('date_from',"$now_year-$now_mm-01") unless $i{date_from} ;  
	
	my $days_in_month = Days_in_Month($now_year,$now_mm) ;
	
	$print_box_content_rows .= &common_min_form_datepicker('date_to',"$now_year-$now_mm-$days_in_month") ;
	
	$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>~ ; 
	
	$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('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="operator_id"      value="$i{operator_id}">
<input type="hidden" name="paid_status"      value="$i{paid_status}">~;

$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(){ \$('#operators-payments-form').submit(); })

</script>
</body>

<form role="form" id="operators-payments-form" method="post" action="operator-payments">
<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="operator_id"      value="$i{operator_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;