#!/usr/bin/perl

use lib "/home/libs/modules" ;
use lib "/home/libs/html" ;
    
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 {
	
	my %ii = %i ; 
	local $min_id = 0 ; local $max_id = 0 ; 
	
	foreach (sort keys %i) {
		local @a = split("_") ;
		if ($a[0] eq 'update') {
			$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,item_costing_event","`id` <= '$max_id' AND `id` >= '$min_id'",'','') ; 

	foreach my $id (keys %{$db{event_quotes_min}}) {
		%i = () ;
		my $cnt_item = -1 ; my $update = 0 ;  
		foreach (split /;/,$db{event_quotes_min}{$id}{item_costing_event}) {
			$cnt_item++ ;
			if ($ii{"update_$id\_$cnt_item"} and $ii{"invoice_nr_$id\_$cnt_item"}) {
				$i{invoice_nr} = $ii{"invoice_nr_$id\_$cnt_item"} ;
				$update = 1 ; 
			}
		}
		&db_min_upd("event_quotes","id='$id'") ;
	}

	# foreach my $id (keys %{$db{event_quotes_min}}) {
		# %i = () ;
		# my $cnt_item = -1 ; my $update = 0 ; 
		# my @saved_invoice_nrs = split(/;/,$db{event_quotes_min}{$id}{invoice_nr_costing_event}) ;
		# foreach (split /;/,$db{event_quotes_min}{$id}{item_costing_event}) {
			# $cnt_item++ ;
			# if ($ii{"update_$id\_$cnt_item"} and $ii{"invoice_nr_$id\_$cnt_item"}) {
				# $i{invoice_nr_costing_event} .= qq~$ii{"invoice_nr_$id\_$cnt_item"};~ ;
				# $update = 1 ; 
			# } elsif ($saved_invoice_nrs[$cnt_item]) {
				# $i{invoice_nr_costing_event} .= qq~$saved_invoice_nrs[$cnt_item];~ ;
			# } else {
				# $i{invoice_nr_costing_event} .= qq~;~ ;
			# }
		# }
		# next unless $update ; 
		
		# chop $i{invoice_nr_costing_event} if $i{invoice_nr_costing_event} ;
		
		# # &common_debug("UPDATE event_quotes_min SET invoice_nr_costing_event = $i{invoice_nr_costing_event} WHERE id = '$id'") if $i{invoice_nr_costing_event} ;
		
		# &db_min_upd("event_quotes_min","id='$id'")  ; 
	# }
	
	%i = %ii ; 
	
} #------------------------------------------------------------------------------------------

sub report_ifields {

	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, "((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!~ ; 
	}
	
	our $where_min = qq~~ ; 

	if ($i{event_costing_id} and $i{event_costing_id} ne 'all') { 
		&db_min_ro('event_cost_items','1,name',"`id` = '$i{event_costing_id}'",'','') ;
		# $where_min = "m.item_costing_event LIKE '%;$i{event_costing_id};%' OR m.item_costing_event LIKE '$i{event_costing_id};%' OR m.item_costing_event LIKE '%;$i{event_costing_id}'" ;
		$where_min = "FIND_IN_SET($i{event_costing_id},REPLACE(m.item_costing_event,';',','))" ;
		push @report_results,"EVENT COSTING = $db{event_cost_items}{1}{name}" ;
	}
	
	if ($i{client_id} and $i{client_id} ne 'all') {
		&db_min_ro('customers','1,name',"`id`='$i{client_id}'",'','') ;
		push @report_sql, "(e.quote_to = '$i{client_id}')" ;
		push @report_results,"CLIENT = $db{customers}{1}{name}" ;		
	}

	if ($i{event_quote_id} and $i{event_quote_id} ne 'all') {
		&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,"COSTINGS ARE ALL PAID" ; 
	} elsif ($i{paid_status} eq 'outstanding') {
		push @report_results,"COSTINGS 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) ;
	
	our @sql_col_display = ("event_quote_nr","event_name","event_date_from","event_date_to","days","type_of_system","description","production_hours","cloud_recording_hours","qty_half_day","qty_full_day","rate","total","invoice_nr") ;
	
	my $table_colspan = 0 ; 
	
	foreach (@sql_col_display) { 
		$table_colspan += 1 ; 
	}

	&report_xlsx_export_header("Event_Invoicing_Report$xlsreportname",'event_invoicing_report') ;
	
	&load_list_vars("$srch_where_sql","$where_min") ;
	
	my $field = "" ; my @qty_costing = () ; my @amnt_usd_work = () ; my @amnt_work = () ; my @op_work  = () ; my @item = () ; 
	my @paid_work = () ; 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("event_costing_id",$i{event_costing_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("paid_status",$i{paid_status}) ; 
	$print_box_content_rows .= &common_min_form_input_col("client_id",$i{client_id}) ; 	
	$print_box_content_rows .= qq~</div>~ ; 
	
	$fcol = 12 ; my $val_min = 0 ; $row_cnt = 0 ;
	
	my $date_pay = qq~~ ; my $quote_ids_and_item_cnt = qq~~ ; my $op_ids = qq~~ ; 

	push @sql_col_display,"update" ;

	my %totals_at_bottom = () ; my %seen_description = () ; my %xlsxrow_extra_sheets = () ; my %input_fields = () ; 
	
	my $cnt_nr_of_events = 0 ; 
	
	$seen_description{$ws} = 1 ; my %seen_month = () ;
	
	our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; 
	
	my %seen_item_in_quote = () ; my %total_hours = () ; 
	
	foreach my $time_type (keys %total_seconds) {

		foreach my $system_id (keys %{$total_seconds{$id}}) {
			
			my $desc = $db{event_systems}{$system_id}{description} ;
			my $sys_type = $db{event_systems}{$system_id}{system_type} ;
			
			$total_hours{$time_type}{mobile}{$id}{$system_id} 		+= $total_seconds{$time_type}{$id}{$system_id} if $sys_type eq 'mobile' && $desc !~ 'SSS' && $desc !~ 'AISA' && lc $desc !~ /cricket/ ;
			$total_hours{$time_type}{mobile_sss}{$id}{$system_id} 	+= $total_seconds{$time_type}{$id}{$system_id} if $sys_type eq 'mobile' && $desc =~ 'SSS' && $desc !~ 'AISA' && lc $desc !~ /cricket/ ;
			$total_hours{$time_type}{mobile_aisa}{$id}{$system_id} 	+= $total_seconds{$time_type}{$id}{$system_id} if $sys_type eq 'mobile' && $desc !~ 'SSS' && $desc =~ 'AISA' && lc $desc !~ /cricket/ ;
			$total_hours{$time_type}{solo}{$id}{$system_id} 		+= $total_seconds{$time_type}{$id}{$system_id} if $sys_type eq 'solo' && $desc !~ 'SSS' && $desc !~ 'AISA' && lc $desc !~ /cricket/ ;
			$total_hours{$time_type}{solo_sss}{$id}{$system_id} 	+= $total_seconds{$time_type}{$id}{$system_id} if $sys_type eq 'solo' && $desc =~ 'SSS' && $desc !~ 'AISA' && lc $desc !~ /cricket/ ;
			$total_hours{$time_type}{solo_aisa}{$id}{$system_id} 	+= $total_seconds{$time_type}{$id}{$system_id} if $sys_type eq 'solo' && $desc !~ 'SSS' && $desc =~ 'AISA' && lc $desc !~ /cricket/ ;
			$total_hours{$time_type}{cricket}{$id}{$system_id} 		+= $total_seconds{$time_type}{$id}{$system_id} if $sys_type eq 'cricket' || lc $desc =~ /cricket/ ;
			$total_hours{$time_type}{fixed}{$id}{$system_id} 		+= $total_seconds{$time_type}{$id}{$system_id} if $sys_type eq 'fixed' && lc $desc !~ /cricket/ ;
		}
	}		
	
	my %tooltip = () ; 
	
	foreach my $time_type (keys %total_hours) {
		foreach my $type (keys %{$total_hours{$time_type}}) {
			foreach my $event_id (keys %{$total_hours{$time_type}{$type}}) {
				foreach my $system_id (keys %{$total_hours{$time_type}{$type}{$event_id}}) {
					$total_hours{$time_type}{$type}{$event_id}{$system_id} = sprintf("%.02f",$total_hours{$time_type}{$type}{$event_id}{$system_id}/3600) ; 
					$tooltip{$time_type}{$type}{$event_id} .= qq~$db{event_systems}{$system_id}{name} [$db{event_systems}{$system_id}{description}] : $total_hours{$time_type}{$type}{$event_id}{$system_id} HRS<br>~ ; 
				}	 
			}				
		}
	}
	
	my %seen_tooltip_data = () ;
	
	foreach my $id (sort {$b <=> $a} keys %{$db{$tables}}) {
		
		if ($i{client_id}) { 
			next unless $client{$i{client_id}} eq $quote_customer{$id} ; 
		}
		# next unless $id == 8050 ;
		$cnt_nr_of_events++ ;
				
		$cnt_in_stock 		= -1 ; 
		my $in_stock  		= "" ; 
	
		@qty_costing		= split(/;/,$db{$tables}{$id}{qty_costing_event}) ;
		# @paid_costing		= split(/;/,$db{$tables}{$id}{invoice_nr_costing_event}) ;
		@item				= split(/;/,$db{$tables}{$id}{item_costing_event}) ;
		@item_ttl			= split(/;/,$db{$tables}{$id}{item_ttl_costing_event}) ;
		@vat				= split(/;/,$db{$tables}{$id}{vat_costing_event}) ;
		@qty				= split(/;/,$db{$tables}{$id}{qty_costing_event}) ;
		# @qty_half			= split(/;/,$db{$tables}{$id}{qty_half_day_costing_event}) ;
		@qty_full       	= () ;
		@qty_half       	= () ;
		@price				= split(/;/,$db{$tables}{$id}{usd_amnt_costing_event}) ;

		my $full_day_cnt 	= 0 ; 
		my $half_day_cnt 	= 0 ; 

		if ($db{$tables}{$id}{event_length} eq 'full_day' || $db{$tables}{$id}{event_length} eq 'half_day'){
			my $full_half = ($db{$tables}{$id}{event_length} eq 'full_day') ? 1 : 2 ;
			$db{$tables}{$id}{event_length} = qq~~ ;
			for (1 .. $db{$tables}{$id}{qty}) {
				$db{$tables}{$id}{event_length} .= qq~$full_half;~ ;
			}
			chop $db{$tables}{$id}{event_length} if $db{$tables}{$id}{event_length} ;
		} elsif (!$db{$tables}{$id}{event_length} || $db{$tables}{$id}{event_length} !~ /(\d+)/g) {
			my $start_time = substr($db{$tables}{$id}{date_from},11) ;
			my $end_time = substr($db{$tables}{$id}{date_to},11) ;
			my $time_diff 	= (Time::Piece->strptime($end_time,"%H:%M:%S") - Time::Piece->strptime($start_time,"%H:%M:%S"))/ONE_HOUR ;
			my $full_half 	= ($time_diff >= 5) ? 1 : 2 ;
			$db{$tables}{$id}{event_length} = qq~~ ;
			for (1 .. $db{$tables}{$id}{qty}) {
				$db{$tables}{$id}{event_length} .= qq~$full_half;~ ; 
			}
			chop $db{$tables}{$id}{event_length} if $db{$tables}{$id}{event_length} ;
		}

		@full_half_day = split(/;/,$db{$tables}{$id}{event_length}) ;
		
		if ($db{$tables}{$id}{days_active} !~ /(\d+)/g) {
			$db{$tables}{$id}{days_active} = qq~~ ;
			for (1 .. $db{$tables}{$id}{qty}) {
				$db{$tables}{$id}{days_active} .= qq~1;~ ; 
			}
			chop $db{$tables}{$id}{days_active} if $db{$tables}{$id}{days_active} ; 
		}
		
		@days_active 		= split(/;/,$db{$tables}{$id}{days_active}) ;
		
		@full_half_start	= ($db{$tables}{$id}{times_from} =~ /(\d+)/g) ? split(/;/,substr($db{$tables}{$id}{date_from},11) . ';' . $db{$tables}{$id}{times_from}) : (substr($db{$tables}{$id}{date_from},11)) ;
		@full_half_end		= ($db{$tables}{$id}{times_to} =~ /(\d+)/g) ? split(/;/,$db{$tables}{$id}{times_to} . ';' . substr($db{$tables}{$id}{date_to},11)) : (substr($db{$tables}{$id}{date_to},11)) ;
		
		my $nr_of_hrs 		= 0 ; 
		my $full_day_hrs 	= 0 ; 
		my $half_day_hrs 	= 0 ;
		my $day_cnt	 		= 0 ;
		
		my %nr_of_hrs_cnt = () ; 
		
		my $date_month = substr($db{$tables}{$id}{date_from},0,4) . substr($db{$tables}{$id}{date_from},5,2) ;
		my $date_month_2 = substr($db{$tables}{$id}{date_to},0,4) . substr($db{$tables}{$id}{date_to},5,2) ;
		
		# foreach (@full_half_day) {
			# $full_day_hrs
			# $summary_table{$worksheet}{a_total_event_hours}{$date_month} += (Time::Piece->strptime($full_half_end[$day_cnt],"%H:%M:%S") - Time::Piece->strptime($full_half_start[$day_cnt],"%H:%M:%S"))/ONE_HOUR ;
			# $day_cnt++ ;
		# }
		
		# $day_cnt = 0 ;
		
		# foreach (@days_active) {
			# $nr_of_hrs += (Time::Piece->strptime($full_half_end[$day_cnt],"%H:%M:%S") - Time::Piece->strptime($full_half_start[$day_cnt],"%H:%M:%S"))/ONE_HOUR if $_ ;
			# $day_cnt++ ;
		# } 
		
		$day_cnt = 0 ;
		
		foreach (@full_half_day) {
			
			my $month = $date_month ; 
			
			if ($date_month ne $date_month_2 && $day_cnt) {
				my ($yr,$mn,$dd) = Add_Delta_Days(substr($db{$tables}{$id}{date_from},0,4),substr($db{$tables}{$id}{date_from},5,2),substr($db{$tables}{$id}{date_from},8,2),$day_cnt) ; 
				$mn = sprintf("%02d",$mn) ;
				$month = $yr . $mn ;
			}
			
			$summary_table{zzzzz_totals}{h_total_days_of_events}{$month} += 1 ;

			my $hours_diff = (Time::Piece->strptime($full_half_end[$day_cnt],"%H:%M:%S") - Time::Piece->strptime($full_half_start[$day_cnt],"%H:%M:%S"))/ONE_HOUR ;

			if ($_ eq '1') {
				$full_day_cnt++ ;
				$nr_of_hrs_cnt{full}{$month} += $hours_diff ;
			} elsif ($_ eq '2') {
				$half_day_cnt++ ;
				$nr_of_hrs_cnt{half}{$month} += $hours_diff ;
			}
			
			$day_cnt++ ;
			
		}

		my $cnt_item = -1 ;  
		
		my %max_amnt_per_item = () ;
		foreach my $item_id (@item) {
			$cnt_item++ ;
			next unless $item_id ; 
			$max_amnt_per_item{$item_id} = $price[$cnt_item] if !$max_amnt_per_item{$item_id} || $max_amnt_per_item{$item_id} < $price[$cnt_item] ; 
		}
		
		my %second_max_amnt_per_item = () ; 
		$cnt_item = -1 ;   
		
		foreach my $item_id (@item) {
			$cnt_item++ ;
			$second_max_amnt_per_item{$item_id} = $price[$cnt_item] if $price[$cnt_item] ne $max_amnt_per_item{$item_id} && (!$second_max_amnt_per_item{$item_id} || $second_max_amnt_per_item{$item_id} < $price[$cnt_item]) ; 
		}
		$cnt_item = -1 ;  my %seen_quote_desc = () ; my %seen_item = () ; 
		
		my $cnt_item_full = -1 ; my $cnt_item_half = -1 ; 
		
		$summary_table{zzzzz_totals}{a_total_event_hours}{$date_month} += $nr_of_hrs_cnt{full}{$date_month} ; 				 
		$summary_table{zzzzz_totals}{a_total_event_hours}{$date_month} += $nr_of_hrs_cnt{half}{$date_month} ; 				 
		$summary_table{zzzzz_totals}{b_nr_of_half_day_events}{$date_month} += 1 if $db{$tables}{$id}{event_length} =~ /2/ ; 			 
		$summary_table{zzzzz_totals}{d_nr_of_full_day_events}{$date_month} += 1 if $db{$tables}{$id}{event_length} =~ /1/ ; 			 
		$summary_table{zzzzz_totals}{g_total_unique_events}{$date_month} += 1 ;
		if ($date_month_2 ne $date_month) {
			$summary_table{zzzzz_totals}{a_total_event_hours}{$date_month_2} 					+= $nr_of_hrs_cnt{full}{$date_month_2} ;	
			$summary_table{zzzzz_totals}{a_total_event_hours}{$date_month} 						+= $nr_of_hrs_cnt{half}{$date_month_2} ;		
			$summary_table{zzzzz_totals}{b_nr_of_half_day_events}{$date_month_2} 	+= 1 if $db{$tables}{$id}{event_length} =~ /2/ ; 			 
			$summary_table{zzzzz_totals}{d_nr_of_full_day_events}{$date_month_2} 	+= 1 if $db{$tables}{$id}{event_length} =~ /1/ ;
			$summary_table{zzzzz_totals}{g_total_unique_events}{$date_month_2} += 1 ;
		}		
		
		$summary_table_ytd{unique_events}{zzzzz_totals}{all} 		+= 1 ;
		$summary_table_ytd{unique_full_events}{zzzzz_totals}{all} 	+= 1 if $db{$tables}{$id}{event_length} =~ /1/ ; 			 
		$summary_table_ytd{unique_half_events}{zzzzz_totals}{all} 	+= 1 if $db{$tables}{$id}{event_length} =~ /2/ ; 			 
 
		foreach my $item_id (sort @item) { 
			
			# local $amnt_owed = $tot_amnt{$op_id} - $amnt_paid{$op_id} ;
			$cnt_item++ ;  
			next if ($i{paid_status} eq 'outstanding' && $db{$tables}{$id}{invoice_nr}) || ($i{paid_status} eq 'paid' && !$db{$tables}{$id}{invoice_nr}) ;
			
			my $hide_from_first_sheet = ($db{event_cost_items}{$item_id}{name} !~ /Mobile/ && $db{event_cost_items}{$item_id}{name} !~ /Cricket/ && $db{event_cost_items}{$item_id}{name} !~ /Fixed/) ? 1 : 0 ;
			
			$first_id = $id unless $first_id ; 
			$last_id = $id if $last_id < $id ; 
			
			$amnt_owed = $item_ttl[$cnt_item] ;
			$amnt_owed = 0 if $db{$tables}{$id}{invoice_nr} ;
			$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++ ;

			my $extra_ws = $db{event_cost_items}{$item[$cnt_item]}{name} ; 
			
			if (length($extra_ws) >= 31) {
				$extra_ws = substr($extra_ws,0,28) . '...' ;
			}
			
			# $extra_ws =~ s/ //g ;
			unless ($seen_description{$extra_ws}) {
				
				&xlsxcreator_add_worksheet($extra_ws) ;
				$xlsxrow_extra_sheets{$extra_ws} = 2 ;
				@sql_col_display = grep { $_ ne "update" } @sql_col_display ;
				&report_build_headings($report,$extra_ws,$title_heading,1,1) ; 
				push @sql_col_display,"update" ;
			}
			$seen_description{$extra_ws} = 1 ;
			
			$description_and_event{$extra_ws}{$id} = 1 ; 
 
			# $summary_table{$extra_ws}{a_total_event_hours}{$date_month} += $nr_of_hrs ;
			
			# $totals_at_bottom{$worksheet}{a_total_event_hours}
			# $totals_at_bottom{$worksheet}{b_nr_of_half_day_events}
			# $totals_at_bottom{$worksheet}{c_total_of_half_day_events_ZAR}
			# $totals_at_bottom{$worksheet}{d_nr_of_full_day_events}
			# $totals_at_bottom{$worksheet}{e_total_of_full_day_events_ZAR}
			# $totals_at_bottom{$worksheet}{f_total_ZAR}
			# $totals_at_bottom{$worksheet}{g_total_unique_events}
			
			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_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>~ ; 
					
					$val = &common_min_get_event_quote_button($id,$tables) ;
					
				} elsif ($_ eq 'event_name') {
					$val = $db{$tables}{$id}{ref} ;
					$align = qq~class="dt-left"~ ; 
				} elsif ($_ eq 'event_date_from' || $_ eq 'event_date_to') {	
					$val = ($_ eq 'event_date_from') ? &common_min_date_as_string(substr($db{$tables}{$id}{date_from},0,10)) : &common_min_date_as_string(substr($db{$tables}{$id}{date_to},0,10)) ;
				} elsif ($_ eq 'days') {
					$val = $db{$tables}{$id}{qty} ;
				} elsif ($_ eq 'type_of_system') {
					$val = $db{event_types}{$db{$tables}{$id}{type}}{name} ;
				} elsif ($_ eq 'description') { 
					$val = $db{event_cost_items}{$item[$cnt_item]}{name} ; 
				} elsif ($_ eq 'production_hours' || $_ eq 'cloud_recording_hours') {
					
					my $desc = $db{event_cost_items}{$item[$cnt_item]}{name} ;
					
					my $type = 
						($desc =~ /Mobile/ && $desc !~ /SSS/ && $desc !~ /AISA/ && $desc !~ /\bSolo\b/ && $desc !~ /Cricket/) ? 'mobile' : 
						($desc =~ /Mobile/ && $desc =~ /SSS/ && $desc !~ /AISA/ && $desc !~ /\bSolo\b/ && $desc !~ /Cricket/) ? 'mobile_sss' : 
						($desc =~ /Mobile/ && $desc !~ /SSS/ && $desc =~ /AISA/ && $desc !~ /\bSolo\b/ && $desc !~ /Cricket/) ? 'mobile_aisa' : 
						($desc =~ /Cricket/) ? 'cricket' : 
						($desc =~ /\bSolo\b/ && $desc !~ /SSS/ && $desc !~ /AISA/ ) ? 'solo' : 
						($desc =~ /\bSolo\b/ && $desc =~ /SSS/ && $desc !~ /AISA/ ) ? 'solo_sss' : 
						($desc =~ /\bSolo\b/ && $desc !~ /SSS/ && $desc =~ /AISA/ ) ? 'solo_aisa' : 
						($desc =~ /Fixed/) ? 'fixed' :
						'' 
					;
					
					my $tooltip_data = ($tooltip{$_}{$type}{$id} && !$seen_tooltip_data{$_}{$type}{$id}) ? substr($tooltip{$_}{$type}{$id},0,-4) : ($tooltip{$_}{$type}{$id}) ? $tooltip{$_}{$type}{$id} : '' ;
					
					$seen_tooltip_data{$_}{$type}{$id} = 1 ;
					
					$val = ($type && $tooltip_data) ? qq~<i class="glyphicon glyphicon-time" title data-toggle="tooltip" data-placement="top" data-original-title="$tooltip_data">~ : ($type && !$tooltip_data) ? "N/A" : qq~~ ; 
		
				} elsif ($_ eq 'qty_half_day') {
					
					$summary_table{$extra_ws}{a_total_event_hours}{$date_month} 				+= 0 ; 				 
					$summary_table{$extra_ws}{a_total_event_hours}{$date_month_2} 				+= 0 ; 				 
					$summary_table{$extra_ws}{c_total_of_half_day_events_ZAR}{$date_month}		+= 0 ; 	
					$summary_table{$extra_ws}{c_total_of_half_day_events_ZAR}{$date_month_2}	+= 0 ; 	
					$summary_table{$extra_ws}{e_total_of_full_day_events_ZAR}{$date_month}		+= 0 ; 	
					$summary_table{$extra_ws}{e_total_of_full_day_events_ZAR}{$date_month_2}	+= 0 ; 	
					$summary_table{$extra_ws}{f_total_ZAR}{$date_month}							+= 0 ; 	
					$summary_table{$extra_ws}{f_total_ZAR}{$date_month_2}						+= 0 ; 	
					$summary_table{$extra_ws}{b_nr_of_half_day_events}{$date_month}				+= 0 ; 			 
					$summary_table{$extra_ws}{b_nr_of_half_day_events}{$date_month_2}      		+= 0 ;
					$summary_table{$extra_ws}{d_nr_of_full_day_events}{$date_month}				+= 0 ; 	
					$summary_table{$extra_ws}{d_nr_of_full_day_events}{$date_month_2}			+= 0 ; 	
					$summary_table{$extra_ws}{g_total_unique_events}{$date_month}				+= 0 ; 		
					$summary_table{$extra_ws}{g_total_unique_events}{$date_month_2}				+= 0 ; 						

					unless ($seen_item{$item_id}) {
						$summary_table_ytd{unique_events}{g_total_unique_events}{$extra_ws}			+= 1 ;
						$summary_table_ytd{unique_full_events}{d_nr_of_full_day_events}{$extra_ws}	+= 1 if $db{$tables}{$id}{event_length} =~ /1/ ; 			 
						$summary_table_ytd{unique_half_events}{b_nr_of_half_day_events}{$extra_ws} 	+= 1 if $db{$tables}{$id}{event_length} =~ /2/ ; 	
					}
						
					my $full_not_half = 0 ; 
					
					if ($max_amnt_per_item{$item_id} eq $price[$cnt_item] && $full_day_cnt) {
						$cnt_item_full++ ; 
						$qty_full[$cnt_item] = $qty[$cnt_item] ;
						$full_not_half = 1 ; 
					} elsif (($second_max_amnt_per_item{$item_id} eq $price[$cnt_item] || !$full_day_cnt) && $half_day_cnt) {
						$cnt_item_half++ ;
						$qty_half[$cnt_item] = $qty[$cnt_item] ;
						$summary_table{$extra_ws}{a_total_event_hours}{$date_month} += $nr_of_hrs_cnt{half}{$date_month} ;
						$summary_table{$extra_ws}{b_nr_of_half_day_events}{$date_month} += 1 if !$seen_quote_desc{$item_id}{half} ;
						$summary_table{$extra_ws}{c_total_of_half_day_events_ZAR}{$date_month_2} += $item_ttl[$cnt_item] ;
						$summary_table{zzzzz_totals}{c_total_of_half_day_events_ZAR}{$date_month_2} += $item_ttl[$cnt_item] ;
						
						if ($date_month ne $date_month_2) {
							$summary_table{$extra_ws}{a_total_event_hours}{$date_month_2} += $nr_of_hrs_cnt{half}{$date_month_2} ;
							$summary_table{$extra_ws}{b_nr_of_half_day_events}{$date_month_2} += 1 if !$seen_quote_desc{$item_id}{half} ;
						}
						
						$seen_quote_desc{$item_id}{half} = 1 ; 
						# $item_price{$item[$cnt_item]}{$id}{half}{$price[$cnt_item]} = 1 ; 
						$seen_item_with_amnt{$item[$cnt_item]}{$id}{half}{$price[$cnt_item]} = 1 ;		
						$nr_unique_prices_per_item{$item[$cnt_item]}{half}++ unless $seen_item_price{$item[$cnt_item]}{half}{$price[$cnt_item]} ;
						$seen_item_price{$item[$cnt_item]}{half}{$price[$cnt_item]} = 1 ;
					} else {
						$cnt_item_full++ ; 
						$qty_full[$cnt_item] = $qty[$cnt_item] ;
						$full_not_half = 1 ;
					}

					if ($full_not_half) {
						$summary_table{$extra_ws}{a_total_event_hours}{$date_month} += $nr_of_hrs_cnt{full}{$date_month} ; 
						$summary_table{$extra_ws}{d_nr_of_full_day_events}{$date_month} += 1 if !$seen_quote_desc{$item_id}{full} ;
						if ($date_month ne $date_month_2) {
							$summary_table{$extra_ws}{a_total_event_hours}{$date_month_2} += $nr_of_hrs_cnt{full}{$date_month_2} ;
							$summary_table{$extra_ws}{d_nr_of_full_day_events}{$date_month_2} += 1 if !$seen_quote_desc{$item_id}{full} ;
						}
						$summary_table{$extra_ws}{e_total_of_full_day_events_ZAR}{$date_month_2} += $item_ttl[$cnt_item] ;	
						$summary_table{zzzzz_totals}{e_total_of_full_day_events_ZAR}{$date_month_2} += $item_ttl[$cnt_item] ;	
						$seen_quote_desc{$item_id}{full} = 1 ;	
						$seen_item_with_amnt{$item[$cnt_item]}{$id}{full}{$price[$cnt_item]} = 1 ;
						$nr_unique_prices_per_item{$item[$cnt_item]}{full}++ unless $seen_item_price{$item[$cnt_item]}{full}{$price[$cnt_item]} ;
						$seen_item_price{$item[$cnt_item]}{full}{$price[$cnt_item]} = 1 ;
					}

					$summary_table{$extra_ws}{f_total_ZAR}{$date_month_2} += $item_ttl[$cnt_item] ;
					$summary_table{zzzzz_totals}{f_total_ZAR}{$date_month_2} += $item_ttl[$cnt_item] ;
					$summary_table{$extra_ws}{g_total_unique_events}{$date_month} += 1 if !$seen_item{$item_id} ;
					$summary_table{$extra_ws}{g_total_unique_events}{$date_month_2} += 1 if !$seen_item{$item_id} && $date_month ne $date_month_2 ;
					
					$seen_item{$item_id} = 1 ; 
					$seen_month{$date_month} = 1 ; 
					$val = $qty_half[$cnt_item] ;
					
				} elsif ($_ eq 'qty_full_day') {
					$val = $qty_full[$cnt_item] ;
				} elsif ($_ eq 'rate') {
					$val = &common_commify($price[$cnt_item]) ;
					$val_min = $val ;
				} elsif ($_ eq 'total') { 
					$val = &common_commify($item_ttl[$cnt_item]) ;
					$val_min = $item_ttl[$cnt_item] ;
					$totals_at_bottom{$ws}{1} += $item_ttl[$cnt_item] unless $hide_from_first_sheet ;
					$totals_at_bottom{$ws}{4} += $item_ttl[$cnt_item]  ;
					$totals_at_bottom{$extra_ws}{1} += $item_ttl[$cnt_item] ; 
				} elsif ($_ eq 'vat') { 
					# $align = 'nowrap' ;
					$totals_at_bottom{$ws}{2} += ($vat[$cnt_item]) ? $item_ttl[$cnt_item]*0.15 : 0  unless $hide_from_first_sheet ;
					$totals_at_bottom{$extra_ws}{2} += ($vat[$cnt_item]) ? $item_ttl[$cnt_item]*0.15 : 0 ; 
					$val   = ($vat[$cnt_item]) ? sprintf("%.2f",$item_ttl[$cnt_item]*0.15) : qq~&nbsp;&nbsp;<i class="glyphicon glyphicon-warning-sign red" data-placement="right" data-toggle="tooltip" data-original-title="VAT not ticked!"></i>~ ;
					$val_min = ($vat[$cnt_item]) ? $item_ttl[$cnt_item]*0.15 : 0 ;
				} elsif ($_ eq 'total_amount') {
					
					if ($vat[$cnt_item]) {
						$val = $item_ttl[$cnt_item]*1.15 ;
						$val = sprintf("%.2f",$val) ;	
						$totals_at_bottom{$ws}{3} += $val unless $hide_from_first_sheet ;
						$totals_at_bottom{$extra_ws}{3} += $val ;
					} else {
						$val = $item_ttl[$cnt_item] ;
						$totals_at_bottom{$ws}{3} += $val unless $hide_from_first_sheet ;
						$totals_at_bottom{$extra_ws}{3} += $val ; 
					}			
				} elsif ($_ eq 'invoice_nr') {
					$val	= ($amnt_owed > 0) ? &common_min_form_input_col("invoice_nr_$id\_$cnt_item",$db{$tables}{$id}{invoice_nr}) : "$db{$tables}{$id}{invoice_nr} " ;
					$val_min = $db{$tables}{$id}{invoice_nr} ;
					$input_fields{$id} .= qq~input[name='invoice_nr_$id\_$cnt_item'],~ ; 
				} elsif ($_ eq 'update') {
					if ($amnt_owed > 0) {
						$val = &common_min_form_checkbox_col("update_$id\_$cnt_item",1)  ; 	
						$trigger_jquery_raw .= qq~
							\$("input[name='invoice_nr_$id\_$cnt_item']").change(function () {
								\$("#checkboxUpdate_$id\_$cnt_item").prop("checked",true) ;
							}) ;
						~ ;	
					} else {
						$val = '<i class="glyphicons glyphicons-remove"></i>' ;	
					}
					$val_min = "" ;
				}
				
				$print_tbody .= qq~<td $align>$val</td>~ ;  

				if ($_ ne 'event_quote_nr' && $_ ne 'days' && $_ ne 'qty_full_day' && $_ ne 'qty_half_day' && $_ ne 'total' && $_ ne 'rate' && $_ ne 'update' && $_ ne 'invoice_nr' && $_ ne 'event_name' && $_ ne 'vat') {
					&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format_management_report_data) unless $hide_from_first_sheet ;
					&xlsxcreator_write_xlsx($extra_ws,$xlsxrow_extra_sheets{$extra_ws},$xlsxcol+1,$val,$format_management_report_data) ;
				} elsif ($_ eq 'event_name') {
					&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format_management_report_months_2) unless $hide_from_first_sheet ;
					&xlsxcreator_write_xlsx($extra_ws,$xlsxrow_extra_sheets{$extra_ws},$xlsxcol+1,$val,$format_management_report_months_2) ;
				} elsif ($_ eq 'event_quote_nr') {
					&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$id,$format_management_report_data_ref_nr) unless $hide_from_first_sheet ;
					&xlsxcreator_write_xlsx($extra_ws,$xlsxrow_extra_sheets{$extra_ws},$xlsxcol+1,$id,$format_management_report_data_ref_nr) ;
				} elsif ($_ eq 'qty_full_day' || $_ eq 'qty_half_day' || $_ eq 'days') {
					&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format_management_report_data_ref_nr) unless $hide_from_first_sheet ;
					&xlsxcreator_write_xlsx($extra_ws,$xlsxrow_extra_sheets{$extra_ws},$xlsxcol+1,$val,$format_management_report_data_ref_nr) ;
				} elsif ($_ eq 'invoice_nr') {
					&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$format_management_report_data_ref_nr) unless $hide_from_first_sheet ;
					&xlsxcreator_write_xlsx($extra_ws,$xlsxrow_extra_sheets{$extra_ws},$xlsxcol+1,$val_min,$format_management_report_data_ref_nr) ;
				} elsif ($_ eq 'total' or $_ eq 'rate') {
					&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$format7) unless $hide_from_first_sheet ; 	
					&xlsxcreator_write_xlsx($extra_ws,$xlsxrow_extra_sheets{$extra_ws},$xlsxcol+1,$val_min,$format7) ; 	
				} elsif ($_ ne 'update' or $_ ne 'vat') {
					&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$format_management_report_data) unless $hide_from_first_sheet ;
					&xlsxcreator_write_xlsx($extra_ws,$xlsxrow_extra_sheets{$extra_ws},$xlsxcol+1,$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~</tr>~ ;
			$xlsxrow++ unless $hide_from_first_sheet ;
			$xlsxrow_extra_sheets{$extra_ws}++ ;
			$quote_ids_and_item_cnt .= qq~"$cnt_item\_$id":"1",~ if $item_id ; 
		}
		
		if ($input_fields{$id}) {
			chop $input_fields{$id} ;
			$trigger_jquery_raw .= qq~
				\$("$input_fields{$id}").change( function () {	
					console.log("change input") ;
					selectAll($id,\$(this).val()) ;
				}) ;
			~ ;
		}

		chop $op_ids if $op_ids ; 
		# $quote_ids_and_item_cnt .= qq~"$row_cnt_$id":[$op_ids],~ if $op_ids ; 

	}

	$box_icon .= qq~<div class="box-icon" title='Bulk add Invoices' 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>~ ;
	
	$trigger_jquery_raw .= qq~
	
		function selectAll(specific_event_id,given_input) {
			
			console.log("specific_event_id : "+specific_event_id+" , changed_input : "+given_input)  ;
			
			let jsObject = {
				$quote_ids_and_item_cnt
			}; 
			let find_input = '' ;
			if (!specific_event_id) {
				for (let key in jsObject) {
					let parts = key.split("_") ;
					let event_id = parts[1] ;
					if (specific_event_id && specific_event_id != event_id) { continue ; }
					let item_cnt = parts[0] ;
					
					console.log("event_id : "+event_id+" , item_cnt : "+item_cnt) ; 
					
					if (\$("input[name=invoice_nr_"+event_id+"_"+item_cnt+"]").val()) {
						find_input = \$("input[name=invoice_nr_"+event_id+"_"+item_cnt+"]").val() ;
						break ;
					}
				}
				if (!find_input) { return ; }
			} else {
				find_input = given_input ; 
			}

			for (let key in jsObject) {

				let parts = key.split("_") ;
				let event_id = parts[1] ;
				if (specific_event_id && specific_event_id != event_id) { continue ; }
				let item_cnt = parts[0] ;
				\$(\$("#itv-table").dataTable().fnGetNodes()).find(\$("input[name=update_"+event_id+"_"+item_cnt+"]")).each(function () {      
					\$("input[name=invoice_nr_"+event_id+"_"+item_cnt+"]").val(find_input) ;
					if (!\$(this).is(':checked')) {
						\$(this).prop('checked',true);
					} else if (\$(this).is(':checked') && !find_input) {
						\$(this).prop('checked',false);
					}
				}) ;
			}
		}
	~;
	
	$print_tbody .= qq~<tr id="total">~ ;	

	foreach my $worksheet (sort keys %seen_description) {
		for (1 .. 4) {
			$totals_at_bottom{$worksheet}{$_} = sprintf("%.02f",$totals_at_bottom{$worksheet}{$_}) ; 
			$totals_at_bottom{$worksheet}{$_} = &common_commify($totals_at_bottom{$worksheet}{$_}) ;
		}		
	}

	# $format_management_report_totals -> set_bottom('1') ;

	foreach (@sql_col_display) {

		if ($_ eq $sql_col_display[-4]) {
			$print_tbody .= ($cnt_nr_of_events == 1) ? qq~<td class="dt-right"><b style="font-size:14px;"><span style="display:none;">-1</span>TOTALS<br>($cnt_nr_of_events Event)</b></td>~ : qq~<td class="dt-right"><b style="font-size:14px;"><span style="display:none;">-1</span>TOTALS<br>($cnt_nr_of_events Events)</b></td>~ ;
		} elsif ($_ eq $sql_col_display[-3]) {
			&xlsxcreator_write_xlsx($ws,$xlsxrow,10,$totals_at_bottom{$ws}{1},$format_management_report_totals) ;
			foreach my $worksheet (sort keys %seen_description) {
				&xlsxcreator_write_xlsx($worksheet,$xlsxrow_extra_sheets{$worksheet},11,$totals_at_bottom{$worksheet}{1},$format_management_report_totals) if $worksheet ne $ws ;
			}
			$print_tbody .= qq~<td class="dt-center"><b style="font-size:14px;"><span style="display:none;">-1</span>$totals_at_bottom{$ws}{4}</b></td>~ ;
		}
		# elsif ($_ eq $sql_col_display[-4]) {
			# &xlsxcreator_write_xlsx($ws,$xlsxrow,10,$totals_at_bottom{2},$format_management_report_totals ) ;
			# $print_tbody .= qq~<td class="dt-center"><b style="font-size:14px;"><span style="display:none;">-1</span>$totals_at_bottom{2}</b></td>~ ;
		# } elsif ($_ eq $sql_col_display[-3]) {
			# &xlsxcreator_write_xlsx($ws,$xlsxrow,11,$totals_at_bottom{3},$format_management_report_totals ) ;
			# $print_tbody .= qq~<td class="dt-center"><b style="font-size:14px;"><span style="display:none;">-1</span>$totals_at_bottom{3}</b></td>~ ;
		# } 
		else  {
			$print_tbody .= qq~<td><span style="display:none;">-1</span></td>~ ;
		}
	}	
	
	# # foreach (@sql_col_display) { 

		# # if ($_ eq $sql_col_display[-4]) {
			# # $print_tbody .= qq~<td class="dt-right" colspan="10"><b style="font-size:14px;"><span style="display:none;">-1</span>TOTALS ($cnt_nr_of_events Events)</b></td>~ ;
		# # } elsif ($_ eq $sql_col_display[-3]) {
			# # &xlsxcreator_write_xlsx($ws,$xlsxrow,10,$totals_at_bottom{1},$format_management_report_totals ) ;
			# # $print_tbody .= qq~<td class="dt-center"><b style="font-size:14px;"><span style="display:none;">-1</span>$totals_at_bottom{1}</b></td>~ ;
		# # } elsif ($_ eq $sql_col_display[-1] || $_ eq $sql_col_display[-2]) {
			# # $print_tbody .= qq~<td><span style="display:none;">-1</span></td>~ ;
		# # }
		
		# # # elsif ($_ eq $sql_col_display[-4]) {
			# # # &xlsxcreator_write_xlsx($ws,$xlsxrow,11,$totals_at_bottom{2},$format_management_report_totals ) ;
			# # # $print_tbody .= qq~<td class="dt-center"><b style="font-size:14px;"><span style="display:none;">-1</span>$totals_at_bottom{2}</b></td>~ ;
		# # # } elsif ($_ eq $sql_col_display[-3]) {
			# # # &xlsxcreator_write_xlsx($ws,$xlsxrow,12,$totals_at_bottom{3},$format_management_report_totals ) ;
			# # # $print_tbody .= qq~<td class="dt-center"><b style="font-size:14px;"><span style="display:none;">-1</span>$totals_at_bottom{3}</b></td>~ ;
		# # # } 
		# # # else { 
			# # # $print_tbody .= qq~<td><span style="display:none;">-1</span></td>~ ;
		# # # }

	# # }
	
	my %event_cnt_by_des = () ; 
	
	my @months_of_year = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; 
	
	foreach my $des (keys %description_and_event) {
		foreach my $evnt (keys %{$description_and_event{$des}}) {
			$event_cnt_by_des{$des}++ ; 
		}
	}
	
	$xlsxrow++ ;
	# &xlsxcreator_write_xlsx($ws,$xlsxrow,9,"TOTAL",$format_management_report_total) ;
	my $event_word = ($cnt_nr_of_events == 1) ? "Event" : "Events" ; 
	&xlsxcreator_merge_xlsx($ws,"A$xlsxrow:J$xlsxrow","TOTAL ($cnt_nr_of_events $event_word)",$format_management_report_total) ;
	
	my $summary_ws = "Summary" ;
	my $rates_ws = "Rates" ;
	
	&xlsxcreator_add_worksheet($rates_ws) ;

	# $seen_item_with_amnt{$item[$cnt_item]}{half}{$price[$cnt_item]} = 1 ; 
	
	&xlsxcreator_write_xlsx($rates_ws,1,1,"Description",$format_management_report_headings) ;
	&xlsxcreator_write_xlsx($rates_ws,1,2,"Rate - Full Day",$format_management_report_headings) ;
	&xlsxcreator_write_xlsx($rates_ws,1,3,"Rate - Half Day",$format_management_report_headings) ;
	
	my $rates_row = 2 ; 
	
	my %seen_item_fh = () ; my %cnt_item = () ; my %seen_item_price = () ;
	
	foreach my $item_id (sort {$db{event_cost_items}{$a}{name} cmp $db{event_cost_items}{$b}{name}} keys %seen_item_with_amnt) {
		
		next if $db{event_cost_items}{$item_id}{name} !~ /Mobile/ && $db{event_cost_items}{$item_id}{name} !~ /Cricket/ && $db{event_cost_items}{$item_id}{name} !~ /Fixed/ ;
		
		foreach my $event_id  (sort {$b <=> $a} keys %{$seen_item_with_amnt{$item_id}}) {
			
			# my $nr_of_skipped_prices = 0 ; 
			
			foreach my $full_or_half_day (sort keys %{$seen_item_with_amnt{$item_id}{$event_id}}) {
				
				my $rate = "" ; 
				my $rates_col = ($full_or_half_day eq 'full') ? 2 : 3 ;

				foreach my $item_price (sort {$a <=> $b} keys %{$seen_item_with_amnt{$item_id}{$event_id}{$full_or_half_day}}) {
					
					# $nr_of_skipped_prices++ if $seen_item_price{$item_id}{$full_or_half_day}{$item_price} ; 
					
					next if $seen_item_price{$item_id}{$full_or_half_day}{$item_price} ; 
					$seen_item_price{$item_id}{$full_or_half_day}{$item_price} = 1 ;
					
					$item_price = &common_commify($item_price) ; 
					
					if ((!$seen_item_price{$item_id}{half}{$item_price} && !$seen_item_price{$item_id}{full}{$item_price} && !$cnt_item{$item_id}) || ($nr_unique_prices_per_item{$item_id}{half} == 1 && $nr_unique_prices_per_item{$item_id}{full} == 1)) {
						if ($nr_unique_prices_per_item{$item_id}{half} == 1 && $nr_unique_prices_per_item{$item_id}{full} == 1 && $full_or_half_day eq 'half') {
							#Do Nothing
						} else {
							$rates_row++ ; 
							&xlsxcreator_write_xlsx($rates_ws,$rates_row,1,"$db{event_cost_items}{$item_id}{name}",$format98) ;
							$cnt_item{$item_id}++ ;							
						}
					} elsif (!$seen_item_price{$item_id}{half}{$item_price} || !$seen_item_price{$item_id}{full}{$item_price}) {
						$cnt_item{$item_id}++ ; 
						$rates_row++ ; 
						&xlsxcreator_write_xlsx($rates_ws,$rates_row,1,"$db{event_cost_items}{$item_id}{name} ($cnt_item{$item_id})",$format98) ;
					} else {
						# $nr_of_skipped_prices++
					}
					# $seen_item_fh{$item_id}{$full_or_half_day} = 1 ;
					&xlsxcreator_write_xlsx($rates_ws,$rates_row,$rates_col,$item_price,$format7) ;
					
				}
			}
		}
	}
	
	&xlsxcreator_add_worksheet($summary_ws) ; 
	
	my $description_cnt = 3 ; 
	
	# format_management_report_headings
	
	# &xlsxcreator_write_xlsx($summary_ws,0,0,"Description",$format_management_report_headings) ; 
	# &xlsxcreator_write_xlsx($summary_ws,0,1,"Total",$format_management_report_headings) ; 
	&xlsxcreator_merge_xlsx($summary_ws,"B2:C2","Summary",$format_management_report_headings) ; 
	my $mnt_cnt = 3 ; my $month_cnt = 0 ; 
	
	foreach (sort keys %seen_month) {
		my $month_name = $months_of_year[substr($_,4,2)] . '-' . substr($_,0,4) ; 
		&xlsxcreator_write_xlsx($summary_ws,1,$mnt_cnt,$month_name,$format_management_report_headings) ;
		$mnt_cnt++ ;
	}
	
	&xlsxcreator_write_xlsx($summary_ws,1,$mnt_cnt,"YTD Total",$format_management_report_headings) ;
	&xlsxcreator_freeze_panes($summary_ws,2,0) ;
	&xlsxcreator_freeze_panes($rates_ws,2,0) ;
	
	$format3->set_align('center');
	
	# $totals_at_bottom{$worksheet}{a_total_event_hours}
	# $totals_at_bottom{$worksheet}{b_nr_of_half_day_events}
	# $totals_at_bottom{$worksheet}{c_total_of_half_day_events_ZAR}
	# $totals_at_bottom{$worksheet}{d_nr_of_full_day_events}
	# $totals_at_bottom{$worksheet}{e_total_of_full_day_events_ZAR}
	# $totals_at_bottom{$worksheet}{f_total_ZAR_of_full_day_events}
	# $totals_at_bottom{$worksheet}{g_total}
	# $totals_at_bottom{$worksheet}{h_total_unique_events}
	
	my @small_words = qw(of);
	
	my $formatting = $format7 ;
	
	foreach my $worksheet (sort keys %summary_table) {
		
		if ($worksheet ne 'zzzzz_totals') {
			
			next if $worksheet eq $ws ; 
			$xlsxrow_extra_sheets{$worksheet}++ ;
			$event_word = ($event_cnt_by_des{$worksheet} == 1) ? "Event" : "Events" ; 
			# &xlsxcreator_merge_xlsx($worksheet,"A$xlsxrow_extra_sheets{$worksheet}:J$xlsxrow_extra_sheets{$worksheet}","TOTAL ($event_cnt_by_des{$worksheet} $event_word)",$format_management_report_total)  ;
			$xlsxrow_extra_sheets{$worksheet}-- ;
			# &xlsxcreator_write_xlsx($worksheet,$xlsxrow_extra_sheets{$worksheet},9,"TOTAL",$format_management_report_total) if $worksheet ne $ws ;
			my $description_cnt_2 = $description_cnt+ 6 ; 
			
			&xlsxcreator_merge_xlsx($summary_ws,"B$description_cnt:B$description_cnt_2","$worksheet",$format98) ; 
			
			foreach my $category (sort keys %{$summary_table{$worksheet}}) {
				
				my $category_2 = substr($category,2) ; 
				$category_2 = join " ", map { my $word = lc($_); (grep { $_ eq $word } @small_words) ? $word : ucfirst($word) } split "_" , $category_2 ;
				$category_2 =~ s/Zar/\[ZAR\]/g;
				$description_cnt++ ; 
				
				&xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,2,$category_2,$format98) ;

				my $month_cnt = 3 ; my $ytd_total = 0 ; 
				
				$formatting = ($category eq 'c_total_of_half_day_events_ZAR' || $category eq 'e_total_of_full_day_events_ZAR' || $category eq 'f_total_ZAR' || ($category eq 'a_total_event_hours' && $summary_table{$worksheet}{$category}{$year_month} && $summary_table{$worksheet}{$category}{$year_month} ne int($summary_table{$worksheet}{$category}{$year_month}))) ? $format7 : $format99 ;
				
				foreach my $year_month (sort keys %seen_month) {
					
					$summary_table{$worksheet}{$category}{$year_month} = 0 unless $summary_table{$worksheet}{$category}{$year_month} ; 
					# my $month_name = $months_of_year[substr($year_month,4,2)] . '-' . substr($year_month,0,4) ;
					&xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$summary_table{$worksheet}{$category}{$year_month},$formatting) ;
					$month_cnt++ ;
					$ytd_total += $summary_table{$worksheet}{$category}{$year_month} ;
				
				}
				
				
				if ($category ne 'b_nr_of_half_day_events' && $category ne 'd_nr_of_full_day_events' && $category ne 'g_total_unique_events') {
					&xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$ytd_total,$formatting) ;		
				} elsif ($category eq 'g_total_unique_events') {
					&xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$summary_table_ytd{unique_events}{$category}{$worksheet},$formatting) ;		
				} elsif ($category eq 'd_nr_of_full_day_events') {
					&xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$summary_table_ytd{unique_full_events}{$category}{$worksheet},$formatting) ;		
				} elsif ($category eq 'b_nr_of_half_day_events') {
					&xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$summary_table_ytd{unique_half_events}{$category}{$worksheet},$formatting) ;		
				}
				
				# &xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$ytd_total,$formatting) ; 
			}
			
			# &xlsxcreator_write_xlsx($summary_ws,$description_cnt,3,"$summary_table{$worksheet}{1}",$format3) ; 
			$description_cnt++ ;			
			
		} else {
			
			my $description_cnt_2 = $description_cnt+ 7 ; 
			
			&xlsxcreator_merge_xlsx($summary_ws,"B$description_cnt:B$description_cnt_2","TOTALS",$format98) ; 
			
			foreach my $category (sort keys %{$summary_table{$worksheet}}) {
				
				my $category_2 = substr($category,2) ; 
				$category_2 = join " ", map { my $word = lc($_); (grep { $_ eq $word } @small_words) ? $word : ucfirst($word) } split "_" , $category_2 ;
				$category_2 =~ s/Zar/\[ZAR\]/g;
				$description_cnt++ ; 
				
				&xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,2,$category_2,$format98) ;
				
				my $month_cnt = 3 ; my $ytd_total = 0 ; 
				
				$formatting = ($category eq 'c_total_of_half_day_events_ZAR' || $category eq 'e_total_of_full_day_events_ZAR' || $category eq 'f_total_ZAR' || ($category eq 'a_total_event_hours' && $summary_table{$worksheet}{$category}{$year_month} && $summary_table{$worksheet}{$category}{$year_month} ne int($summary_table{$worksheet}{$category}{$year_month}))) ? $format7 : $format99 ;
				
				foreach my $year_month (sort keys %seen_month) {
					
					$summary_table{$worksheet}{$category}{$year_month} = 0 unless $summary_table{$worksheet}{$category}{$year_month} ; 
					# my $month_name = $months_of_year[substr($year_month,4,2)] . '-' . substr($year_month,0,4) ;
					&xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$summary_table{$worksheet}{$category}{$year_month},$formatting) ;
					$month_cnt++ ;
					$ytd_total += $summary_table{$worksheet}{$category}{$year_month} ;
				
				}

				if ($category ne 'b_nr_of_half_day_events' && $category ne 'd_nr_of_full_day_events' && $category ne 'g_total_unique_events') {
					&xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$ytd_total,$formatting) ;		
				} elsif ($category eq 'g_total_unique_events') {
					&xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$summary_table_ytd{unique_events}{zzzzz_totals}{all},$formatting) ;		
				} elsif ($category eq 'd_nr_of_full_day_events') {
					&xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$summary_table_ytd{unique_full_events}{zzzzz_totals}{all},$formatting) ;		
				} elsif ($category eq 'b_nr_of_half_day_events') {
					&xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$summary_table_ytd{unique_half_events}{zzzzz_totals}{all},$formatting) ;		
				}
			}
		}
	}
	
	$xlsxrow-- ;
	
	$worksheet{$rates_ws} -> set_column(0,0,1) ;
	$worksheet{$summary_ws} -> set_column(0,0,1) ;
	$worksheet{$summary_ws} -> set_column(1,2,30) ;
	$worksheet{$summary_ws} -> set_column(3,$mnt_cnt,15) ;
	$worksheet{$rates_ws} -> set_column(1,1,40) ;
	$worksheet{$rates_ws} -> set_column(2,3,30) ;
	
	$print_tbody .= qq~</tr>~ ;
	chop $quote_ids_and_item_cnt if $quote_ids_and_item_cnt ;
	
	# my @extra_columns = ("Validated Amount","Validated Total Amount","Difference Amount") ; 
	my @extra_columns = () ; 
	# my @extra_columns2 = ("Is Amount Difference","Month") ; 
	my @extra_columns2 = () ; 

	foreach my $sheet (sort keys %seen_description) {
		
		my $heading_row = ($sheet eq $ws) ? 2 : 1 ; 
		my $start_col = ($sheet eq $ws) ? 0 : 1 ; 
		
		$worksheet{$sheet} -> set_row(0,30) if $sheet eq $ws ;
		$worksheet{$sheet} -> set_column(0,0,1) if $sheet ne $ws ;
		$worksheet{$sheet} -> set_row($heading_row,40) ;
		$worksheet{$sheet} -> set_column($start_col,$start_col,15) ;
		$worksheet{$sheet} -> set_column($start_col+1,$start_col+1,50) ;
		$worksheet{$sheet} -> set_column($start_col+2,$start_col+3,15) ;
		$worksheet{$sheet} -> set_column($start_col+4,$start_col+4,5) ;
		$worksheet{$sheet} -> set_column($start_col+5,$start_col+5,20) ;
		$worksheet{$sheet} -> set_column($start_col+6,$start_col+6,30) ;
		$worksheet{$sheet} -> set_column($start_col+7,$start_col+16,15) ;
		
		my $heading_cnt = $start_col+11 ;
		foreach (@extra_columns) {
			$heading_cnt++ ;
			&xlsxcreator_write_xlsx($sheet,$heading_row,$heading_cnt,"$_",$format100) ;	
		}		
		
		foreach (@extra_columns2) {
			$heading_cnt++ ;
			&xlsxcreator_write_xlsx($sheet,$heading_row,$heading_cnt,"$_",$format101) ;
		}
	
	}
	
	$worksheet{$summary_ws} -> set_row(0,10) ;
	$worksheet{$rates_ws} -> set_row(0,10) ;
	
	# $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-ok icon-white"></i></a></div>~ ;
	
	&report_xlsx_export_footer('L',15,'event_invoicing_report') ;
	
	$fnsortcol   = 0; 
	$fnsortorder = 'desc' ;
	&common_min_extra_crumb("$lcpage\s","Search Screen") ;
					
	# $trigger_jquery_raw .= qq~
	
	# function selectAll() {
				
		# let jsObject = {
			# $quote_ids_and_item_cnt
		# };

		# 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=update_"+event_id+"_"+op_id+"]")).each(function () {      
				
				# console.log("input[name=update_"+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 costings 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 AS 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.id,e.type,e.invoice_nr,e.qty,e.ref,e.date_from,e.date_to,e.quote_completed,e.event_length,e.times_from,e.times_to,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[$_] ;
			
        }    
    }
	
	&db_min_ro('event_cost_items','id,name','','','') ;
	
	&db_min_ro('event_types','id,name','','','') ;
	
	&db_min_ro('event_systems','*','','','') ;
	
	&db_min_ro('event_production_time','quote_id,event_system_production_seconds,event_system_cloud_recording_seconds','','','') ;
	
	our %total_seconds = () ;
	
	foreach my $quote_id (keys %{$db{event_production_time}}) {
		foreach (split("|",$db{event_production_time}{$quote_id}{event_system_production_seconds})) {
			my @a = split(":",$_) ;
			$total_seconds{production_seconds}{$quote_id}{$a[0]} += $a[1] ;
		}		
		foreach (split("|",$db{event_production_time}{$quote_id}{event_system_cloud_recording_seconds})) {
			my @a = split(":",$_) ;
			$total_seconds{cloud_recording_seconds}{$quote_id}{$a[0]} += $a[1] ;
		}
	}
	
} #------------------------------------------------------------------------------------------

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

sub page_opts {

	our $glyphicon = 'list' ;
	our $lcpage    = 'event-invoicing-report' ;

	&common_page_name ;
	   
	our $table     = 'event_quotes' ;
	$page_title    = 'Event Invoicing' ;

	$box_icon .= qq~
		<div class="box-icon">
			<a class="btn btn-primary btn-round" href="javascript:importDoc('csv','fnb');" 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.pl?"+t+"&"+b,"Import CSV",'','max-dialog') ;
		}
	~;

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

sub report_screen {

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

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

	$opts{client_id} = qq~<option value="all">All</option>~ ;
	&common_min_select_opts('client_id','customers',"name",5,'','','','','','','') ;
	
	$print_box_content_rows  .= &common_min_form_select('client_id','') ; 

	# &common_min_select_opts('operator_id','users',"name",$i{operator_id},'','',"user_type LIKE 'casual%'") ;
	$opts{event_quote_id} = qq~<option value="all" SELECTED>All</option>~ ;
	&common_min_select_opts('event_quote_id','event_quotes',"ref",$i{event_quote_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">Invoice Paid</option>~ ; 
	$opts{paid_status} .= qq~<option value="outstanding" SELECTED>Invoice Unpaid</option>~ ; 
	
	$opts{event_costing_id} = qq~<option value="all" SELECTED>All</option>~ ;
	&common_min_select_opts('event_costing_id','event_cost_items',"name",'','','','','','','','') ;
	
	$print_box_content_rows  .= &common_min_form_select('event_costing_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="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}">
~ ;

$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;