#!/usr/bin/perl

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

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

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

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

use CGI::Carp qw(fatalsToBrowser);
use CGI;
use Mail::Sendmail;
use Fcntl qw(:flock);
use File::Copy;
use File::Basename;
use Date::Calc qw(:all);
use Excel::Writer::XLSX;
use Time::Piece ; 
use Image::Size;
use File::Temp qw(tempfile);
use Image::Magick;
# use GD::Image;

&today;

# $now_ccyymmdd = "20250321" ;
# $now_dd = "21" ;
 
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------

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

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

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

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

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

&page_opts ;

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

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

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

exit;

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

sub validate {
	
} #------------------------------------------------------------------------------------------

sub insert {
	
} #------------------------------------------------------------------------------------------

sub update {
	
	my %ii = () ; my %iii = %i ; my %can_update = () ; my %update = () ; 
	
	&db_min_ro($table,'id,event_system_id_multiple','','','') ; 

	my %changed_events = () ; 

	foreach my $field (keys %i) {
		next if $field !~ /^update_/ || ($field =~ /^update_/ && !$i{$field}) ; 
		my @field_split = split(/\_/,$field) ; 
		$changed_events{$field_split[-3]} = 1 ; 
	}
	
	my $table2_sql = join(" OR ",map { "event_quote_id='$_'" } keys %changed_events ) ; 

	&db_min_ro($table2,'event_quote_id,request_sent,late_start,reason_ids,comments',$table2_sql,'','') ; 
	
	foreach my $event_id (keys %{$db{$table2}}) {
		$can_update{$event_id} = 1 ;
	}
	
	my %field_arr = ('request_sent' => 'request_sent','live' => 'live','late_start' => 'late_start','reason' => 'reason_ids','comments' => 'comments') ;  
	
	foreach my $e_id (keys %{$db{$table2}}) {
		$can_update{$e_id} = 1 ;

		foreach my $col (keys %{$db{$table2}{$e_id}}) {
			
			next if $col eq 'event_quote_id' || !$db{$table2}{$e_id}{$col} ;
			
			my $delim = ($col eq 'comments') ? qr/\|\|/ : qr/\|/ ; 

			foreach my $system_data (split $delim,$db{$table2}{$e_id}{$col}) {
				
				next unless $system_data ;
				my ($system_id,$data) = split(/\~/,$system_data) ; 
				next if !$system_id || $db{$table}{$e_id}{event_system_id_multiple} !~ /\b$system_id\b/ ;
				my $delim = ($col eq 'comments') ? qr/\;\;/ : qr/;/ ; 
				
				my $day_cnt = 0 ;
				foreach my $daily_data (split $delim,$data) {
					$day_cnt++ ;
					$ii{$e_id}{$system_id}{$day_cnt}{$col} = $daily_data ;
				}
			}
		}
	}
			
	foreach (keys %i) {
		
		local @a = split(/\_/,$_) ;
		
		my $upd_field = "update_$a[-3]\_$a[-2]\_$a[-1]"  ; 
		next unless $i{$upd_field} ;
		
		$update{$a[-3]} = 1 ;
		
		if (substr($_,0,13) eq 'request_sent_') {
			$ii{$a[-3]}{$a[-2]}{$a[-1]}{request_sent} = $i{$_} ;
		} elsif (substr($_,0,11) eq 'late_start_') {
			$ii{$a[-3]}{$a[-2]}{$a[-1]}{late_start} = $i{$_} ;
		} elsif (substr($_,0,7) eq 'reason_') {
			$ii{$a[-3]}{$a[-2]}{$a[-1]}{reason_ids} = $i{$_} ;
		} elsif (substr($_,0,9) eq 'comments_') {
			$ii{$a[-3]}{$a[-2]}{$a[-1]}{comments} = $i{$_} ;
		}
	}
	
	foreach my $event_id (keys %ii) {

		%i = () ;

		foreach my $system_id (sort {$a <=> $b} keys %{$ii{$event_id}}) {
			# $i{event_system_ids} .= qq~$system_id;~ ; 
			my $day_cnt_exists = 0 ; my %system_data = () ; 
			my $prev_day_cnt = 0 ; 

			foreach my $day_cnt (sort {$a <=> $b} keys %{$ii{$event_id}{$system_id}}) {
				if ($day_cnt - $prev_day_cnt > 1) {
					for my $a (1 .. $day_cnt - $prev_day_cnt - 1) {
						foreach (keys %field_arr) {
							$system_data{$field_arr{$_}} .= ($_ eq 'comments') ? qq~;;~ : qq~;~ ;
						}
					}
				}
				
				$prev_day_cnt = $day_cnt ;
				$day_cnt_exists = 1 ;
				foreach (keys %field_arr) {  
					$system_data{$field_arr{$_}} .= ($_ eq 'comments') ? qq~$ii{$event_id}{$system_id}{$day_cnt}{$field_arr{$_}};;~ : qq~$ii{$event_id}{$system_id}{$day_cnt}{$field_arr{$_}};~ ;
				}
				
				my $field1 = qq~late_start_$event_id\_$system_id\_$day_cnt~ ;   
				my $field2 = qq~reason_$event_id\_$system_id\_$day_cnt~ ;   
				my $field3 = qq~comments_$event_id\_$system_id\_$day_cnt~ ;   
				
			}
			foreach (keys %field_arr) {
				$system_data{$field_arr{$_}}  =~ s/;+$// ;
				$i{$field_arr{$_}} .= qq~$system_id\~$system_data{$field_arr{$_}}~ if $system_data{$field_arr{$_}} ;
				$i{$field_arr{$_}} .= ($_ eq 'comments') ? qq~||~ : qq~|~ ;
			}
		}
		
		foreach (keys %i) {
			$i{$_}  =~ s/\|+$// ;
			$ignore{$_} = ($i{$_} eq $db{$table2}{$event_id}{$_} || (!$i{$_} && !$db{$table2}{$event_id}{$_})) ? 1 : 0 ;
		}
		
		$i{user_id} = $userid ;
		$i{last_updated} = "$now_year-$now_mm-$now_dd $now_hour:$now_min:$now_sec" ;
		
		our $testing = 1 ;
		
		if ($can_update{$event_id} && $update{$event_id}) {
			$ignore{event_quote_id} = 1 ; 
			&db_min_upd($table2,"event_quote_id='$event_id'") ; 
		} elsif ($update{$event_id}) {
			$i{id} = &db_min_get_max($table2,'id') ;
			$i{id} = 1 unless $i{id} ; 
			$i{event_quote_id} = $event_id ;
			&db_min_insert($table2) ; 
		}
	}
	
	%i = %iii ;

	exit ;
	
} #------------------------------------------------------------------------------------------

sub report_ifields {
	
	&load_search_vars ;
		
	if ($i{date_from} and $i{date_to}) { # check dates
		my $date_from_check = $i{date_from} ;
		   $date_from_check =~ s/\-//g ;
		my $date_to_check = $i{date_to} ;
		   $date_to_check =~ s/\-//g ;
		if ($date_from_check > $date_to_check) { 
			$error = qq~'$i{date_from}' > '$i{date_to}'~ ; &report_screen ; 
		}
		
		my @srch_ed_from = &common_split_sql_time($i{date_from}) ;
		my @srch_ed_to   = &common_split_sql_time($i{date_to}) ; 
		
		&common_date_array("$srch_ed_from[0]$srch_ed_from[1]$srch_ed_from[2]","$srch_ed_to[0]$srch_ed_to[1]$srch_ed_to[2]") ;
		
		@report_sql_or = () ;	
		
		foreach my $_srch_date (@common_date_array) {
			my $srch_ccyy_mm_dd = substr($_srch_date,0,4) . '-' . substr($_srch_date,4,2) . '-' . substr($_srch_date,6,2) ;
			push @report_sql_or, "('$srch_ccyy_mm_dd 23:59:59' >= date_from AND '$srch_ccyy_mm_dd 00:00:00' <= date_to)"
		}
		
		my $sql_or = join(' OR ',@report_sql_or) ;
		push @report_sql, "($sql_or)" if $sql_or ; 
		
		# push @report_sql, "((`date_from` >= '$i{date_from} 00:00:00' AND `date_from` <= '$i{date_to} 23:59:59') OR (`date_to` >= '$i{date_from} 00:00:00' AND `date_to` <= '$i{date_to} 23:59:59'))" ;
		push @report_results, "(BETWEEN '$i{date_from}' AND '$i{date_to}')" ;
	} elsif (not $i{date_from}) {
		$error = qq~PLEASE ENTER A START DATE!~ ; 
		&report_screen; 
	} elsif (not $i{date_to}) {
		$error = qq~PLEASE ENTER AN END DATE!~ ; 
		&report_screen; 
	}
	
	if ($i{calibrator_id} and $i{calibrator_id} ne 'all') { 
		push @report_results,"`CALIBRATOR` = '$db{users}{1}{name}'" ;
		push @report_sql, "
			(
				`event_system_calibration_ids` LIKE '%;$i{calibrator_id};%' OR 
				`event_system_calibration_ids` LIKE '%;$i{calibrator_id}' OR 
				`event_system_calibration_ids` LIKE '$i{calibrator_id};%' OR 
				`event_system_calibration_ids` LIKE '%-$i{calibrator_id};%' OR 
				`event_system_calibration_ids` LIKE '%;$i{calibrator_id}-%' OR
				`event_system_calibration_ids` LIKE '%-$i{calibrator_id}-%' OR	
				`event_system_calibration_ids` LIKE '$i{calibrator_id}-%' OR		
				`event_system_calibration_ids` LIKE '%-$i{calibrator_id}' OR		
				`event_system_calibration_ids` LIKE '%~$i{calibrator_id}' OR		
				`event_system_calibration_ids` LIKE '%~$i{calibrator_id}-%' OR		
				`event_system_calibration_ids` LIKE '%~$i{calibrator_id};%'				
			)
		" ; 
	} elsif ($i{calibrator_id} and $i{calibrator_id} eq 'all') {
		push @report_results,"`CALIBRATORS` = 'ALL'" ;
	} else {
		# push @report_sql, "(`user_id` = '')" ; 
	}
	
	if ($i{calibration_status} and $i{calibration_status} ne 'all') {
		push @report_sql, "
			(
				`event_system_calibration_status` LIKE '%;$i{calibration_status};%' OR 
				`event_system_calibration_status` LIKE '%;$i{calibration_status}' OR 
				`event_system_calibration_status` LIKE '$i{calibration_status};%' OR 
				`event_system_calibration_status` LIKE '%-$i{calibration_status};%' OR 
				`event_system_calibration_status` LIKE '%;$i{calibration_status}-%' OR
				`event_system_calibration_status` LIKE '%-$i{calibration_status}-%' OR	
				`event_system_calibration_status` LIKE '$i{calibration_status}-%' OR		
				`event_system_calibration_status` LIKE '%-$i{calibration_status}' OR		
				`event_system_calibration_status` LIKE '%~$i{calibration_status}' OR		
				`event_system_calibration_status` LIKE '%~$i{calibration_status}-%' OR		
				`event_system_calibration_status` LIKE '%~$i{calibration_status};%'				
			)
		" ; 
		push @report_results,"`STATUS` = '$db{calibration_status}{$i{calibration_status}}{status}'" ;
	}
		
	$report_results_msg = uc join(', ', @report_results) ;

	if (not $report_results_msg) { 
		$error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); 
		&report_screen; 
	} else { 
		$isaved = qq(SELECT WHERE $report_results_msg) ; 
	}
	
	our $srch_where_sql = join(' AND ',@report_sql) ; 
 
} #------------------------------------------------------------------------------------------

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

sub load_list_vars {
	
	my ($where) = @_ ;

	our %quote_status = () ; 

	our %calibrator_users = () ; 
	
	&db_min_ro('regions','*','','','') ;
	
	&db_min_ro('users','id,name,user_type,username,region_ids',"name NOT LIKE 'Rory%' AND name NOT LIKE 'Handre%'",'','') ;

	my @event_quote_ids = () ; our %calibration_status_hash = () ; 
					
	&db_min_ro($table,"id,ref,organisation_ids,quote_accepted,event_system_id_multiple,event_system_calibration_status,region_id,sport_type_ids,operator_ids,date_from,date_to,times_from,times_to,daily_operator_ids,days_active,monitor_ids,temp_calibrator_ids","$where AND `quote_accepted` = '1'",'','') ; 
	
	foreach my $id (keys %{$db{$table}}) {

		next unless $id ; my $cnt = 0 ; 

		my @ed_from = &common_split_sql_time($db{$table}{$id}{date_from}) ;
		my @ed_to   = &common_split_sql_time($db{$table}{$id}{date_to}) ; 
		
		&common_date_array("$ed_from[0]$ed_from[1]$ed_from[2]","$ed_to[0]$ed_to[1]$ed_to[2]") ;
		
		$sort_calibration_by_time_ref{"$ed_from[0]$ed_from[1]$ed_from[2]$ed_from[3]$ed_from[4]-$id"} = $id ;
	
		my @status_arr = split(/\;/,$db{$table}{$id}{event_system_calibration_status}) ;
		
		my @system_arr = split(/\;/,$db{$table}{$id}{event_system_id_multiple}) ;
		
		my $cnt = 0 ; 
		
		foreach my $status_data (@status_arr) {
			my ($system_id,$data) = split(/\~/,$status_data) ; 
			if ($system_id && !$data) {
				$data = $system_id ; $system_id = "" ;
			}
			$system_id = $system_arr[$cnt] if !$system_id ; 
			$cnt++ ; 
			my @daily_status_arr = split(/\-/,$data) ; 
			my $day_cnt = 0 ; 
			foreach (@daily_status_arr) {
				$day_cnt++ ;
				$calibration_status_hash{$id}{$system_id}{$day_cnt} = $_ if $_ ; 
			}
		}
	}

	&db_min_ro('sport_types','id,name','','','') ;
	&db_min_ro('organisations','id,name','','','') ;
	
} #------------------------------------------------------------------------------------------

sub list_screen {
	
	our %default_vaules = () ; 
	
	our @sql_col_display = ("count","event","calib_date","day","start_date","start_time","venue","region","system","sport","operator") ;
	
	my @editable_columns = ("request_sent","late_start","calibration_done","reason_ids","comments","frames") ; 
	
	foreach (@editable_columns) {
		if ($_ ne 'reason_ids') {
			push @sql_col_display ,"$_" ;
		} else {
			push @sql_col_display ,"reason" ;
		}
	}
	
	$print_box_content_rows .= &common_min_forms_start("$lcpage") ;
	
	our $calibration_report = 1 ;
	
	&db_min_ro($table2,'event_quote_id,request_sent,late_start,reason_ids,comments,calibration_done,upload_names','','','') ; 
	
	$opts{reason} = qq~<option value="1">Equipment Failure</option><option value="2">Operator Issue</option><option value="-1">Other</option>~ ;
	$opts{late_start} = qq~<option value="1">Yes</option><option value="2">No</option>~ ;
	
	&db_min_ro('event_systems','*',"system_type = 'mobile'",'','') ;
	
	&load_list_vars("$srch_where_sql") ;
	
	foreach my $event_id (keys %{$db{$table2}}) {

		my @request_sent		= split(/\|/,$db{$table2}{$event_id}{request_sent}) ;  
		my @live 				= split(/\|/,$db{$table2}{$event_id}{live}) ;  
		my @late_start 			= split(/\|/,$db{$table2}{$event_id}{late_start}) ;  
		my @reason_ids 			= split(/\|/,$db{$table2}{$event_id}{reason_ids}) ;  
		my @calibration_done 	= split(/\|/,$db{$table2}{$event_id}{calibration_done}) ;  
		my @comments 			= split(/\|\|/,$db{$table2}{$event_id}{comments}) ;  
		 
		my $max_cnt = 0 ;  
		$max_cnt = scalar @request_sent ;  
		$max_cnt = scalar @live 		if scalar @live 		> $max_cnt ;  
		$max_cnt = scalar @late_start 	if scalar @late_start 	> $max_cnt ;  
		$max_cnt = scalar @reason_ids 	if scalar @reason_ids 	> $max_cnt ;  
		$max_cnt = scalar @comments 	if scalar @comments 	> $max_cnt ;   
		$max_cnt = scalar @calibration_done	if scalar @calibration_done 	> $max_cnt ;   

		if ($max_cnt > 0) {
		
			foreach my $sys_cnt (0 .. $max_cnt-1) {
				
				my ($system_id1,$data1) = split(/\~/,$request_sent[$sys_cnt]) ; 
				my ($system_id2,$data2) = split(/\~/,$live[$sys_cnt]) ; 
				my ($system_id3,$data3) = split(/\~/,$late_start[$sys_cnt]) ; 
				my ($system_id4,$data4) = split(/\~/,$reason_ids[$sys_cnt]) ; 
				my ($system_id5,$data5) = split(/\~/,$comments[$sys_cnt]) ; 
				my ($system_id6,$data6) = split(/\~/,$calibration_done[$sys_cnt]) ; 

				my @request_sent_day_splt 	= split(/\;/,$data1) ; 
				my @live_day_splt 			= split(/\;/,$data2) ;
				my @late_start_day_splt 	= split(/\;/,$data3) ; 
				my @reason_ids_day_splt 	= split(/\;/,$data4) ; 
				my @comments_day_splt 		= split(/\;\;/,$data5) ; 
				my @calibration_done_splt	= split(/\;/,$data6) ; 
				
				my $max_nr_days = 0 ; 
				
				$max_nr_days = scalar @request_sent_day_splt ;
				$max_nr_days = scalar @live_day_splt 		if scalar @live_day_splt		> $max_nr_days ;
				$max_nr_days = scalar @late_start_day_splt  if scalar @late_start_day_splt	> $max_nr_days ;
				$max_nr_days = scalar @reason_ids_day_splt  if scalar @reason_ids_day_splt	> $max_nr_days ;
				$max_nr_days = scalar @comments_day_splt	if scalar @comments_day_splt	> $max_nr_days ;
				$max_nr_days = scalar @calibration_done_splt	if scalar @calibration_done_splt	> $max_nr_days ;

				foreach my $day_cnt (1 .. $max_nr_days) {
					$default_vaules{request_sent}{$event_id}{$system_id1}{$day_cnt}		= $request_sent_day_splt[$day_cnt-1] if $system_id1	;
					$default_vaules{live}{$event_id}{$system_id2}{$day_cnt}				= $live_day_splt[$day_cnt-1]		 if $system_id2	;
					$default_vaules{late_start}{$event_id}{$system_id3}{$day_cnt} 		= $late_start_day_splt[$day_cnt-1] 	 if $system_id3	;
					$default_vaules{reason}{$event_id}{$system_id4}{$day_cnt} 			= $reason_ids_day_splt[$day_cnt-1]	 if $system_id4	;
					$default_vaules{comments}{$event_id}{$system_id5}{$day_cnt}			= $comments_day_splt[$day_cnt-1]	 if $system_id5	;
					$default_vaules{calibration_done}{$event_id}{$system_id6}{$day_cnt}	= $calibration_done_splt[$day_cnt-1] if $system_id6	;
				}
				$sys_cnt++ ;
			}
		}
	}
	
	$fcol = 12 ; 
	
	my $report = 1 ; 
	
	our $xlsxdir = "calibration_status_report" ; 
	
	our $xlsxreportname = "Calibration_Status_Report" ; 
 
	my $date = &common_write_date_interval($i{date_from},$i{date_to}) ;
	
	our $xlsx_title_heading = "Calibration Status Report $date" ;
	
	my $found_after_date = 0 ; 
	my $today_val = int("$now_year$now_mm$now_dd") ; 
	
	my @date_from_inp = split(/ /,$i{date_from}) ; 
	my ($year_inp1,$month_inp1,$day_inp1) = split(/\-/,$date_from_inp[0]) ; 
	my $date_inp_val1 = int("$year_inp1$month_inp1$day_inp1") ; 
	
	my @date_to_inp = split(/ /,$i{date_to}) ; 
	my ($year_inp2,$month_inp2,$day_inp2) = split(/\-/,$date_to_inp[0]) ; 
	my $date_inp_val2 = int("$year_inp2$month_inp2$day_inp2") ; 
			
	foreach (keys %{$db{$table}}) {
		my @date_from = split(/ /,$db{$table}{$_}{date_from}) ; 
		my ($year_1,$month_1,$day_1) = split(/\-/,$date_from[0]) ; 
		my $date_val1 = int("$year_1$month_1$day_1") ; 
		my @date_to = split(/ /,$db{$table}{$_}{date_to}) ; 
		my ($year_2,$month_2,$day_2) = split(/\-/,$date_to[0]) ; 
		my $date_val2 = int("$year_2$month_2$day_2") ; 
		$found_after_date = 1 if ($today_val <= $date_val1 && $today_val <= $date_inp_val1) || ($today_val <= $date_val2 && $today_val <= $date_inp_val2) ; 
	}
	
	my $width = 105 ; 
	
	$custom_column_styles{request_sent}		= qq~style="width:$width\px;min-width:$width\px;max-width:$width\px;"~ ;
	$custom_column_styles{live}				= qq~style="width:$width\px;min-width:$width\px;max-width:$width\px;"~ ;
	$custom_column_styles{late_start}		= qq~style="min-width:150px;"~ ;
	# $custom_column_styles{calibration_done}	= qq~style="min-width:150px;"~ ;
	$custom_column_styles{reason}			= qq~style="min-width:150px;"~ ;
	$custom_column_styles{comments}			= qq~style="min-width:150px;"~ ;
	# $custom_column_styles{frames}			= qq~style="min-width:150px;"~ ;
	
	our $found_editable = 0 ; 
	
	&build_table_and_or_excel(1) ; 

	if (!$found_editable) {
		$trigger_jquery_raw .= qq~
			\$("#$useropts{table_id} ").find("th:last").remove() ;
			\$("#$useropts{table_id} tr").each(function() {
				\$(this).find("td:last").remove() ;
			}) ;
		~ ;		
	} else {
		
		&common_min_table_select_jquery("#$useropts{table_id} td:nth-last-child(4),#$useropts{table_id} td:nth-last-child(6)") ;
		
		$trigger_jquery_raw_default_alt .= qq~
			
			let sel_value = \$("#"+changed_id).val() ; 
			
			if (changed_id.includes("textareaComments_")) {
				let sel_value = \$("#"+changed_id).val() ; 
				sel_value = sel_value.replace(/;;/g, "").replace("||", ""); 
				\$("#"+changed_id).val(sel_value) ;				
			} else if (changed_id.includes("selectLate_start_")) {
				let row_val = get_row_nr(changed_id,3) ;
				if (sel_value == '2' && \$("#selectReason_"+row_val).val()) {
					\$("#selectReason_"+row_val).val("").trigger("chosen:updated") ; 
				}
			} else if (changed_id.includes("selectReason_")) {
				
				console.log("1 Hello World!!") ; 
				
				let row_val = get_row_nr(changed_id,3) ;
				if (sel_value && (\$("#selectLate_start_"+row_val).val() == '2' || \$("input[name='late_start_"+row_val+"']").val() == '2')) {
					\$("#selectReason_"+row_val).val("").trigger("chosen:updated") ; 
					console.log("2 Hello World!!") ; 
				}				
			}
			
		~ ;		
			
		&common_min_table_update_checkbox_col("3",$useropts{table_id},"[id^='selectLate_start_'],[id^='selectReason_'],[id^='textareaComments_']","[id^='timepickerRequest_sent_'],[id^='timepickerLive_']") ;
	}
	
	if ($found_editable) {
		# $trigger_jquery .= qq~
			# \$("#$useropts{table_id} td:nth-last-child(3)").css("width","12.5%"); 
			# \$("#$useropts{table_id} td:nth-last-child(2)").css("width","12.5%"); 
		# ~ ;			
	}
 
	$fnsortorder = 'asc' ;
	
	&common_min_extra_crumb("$lcpage","Search Screen") ;
 
	$trigger_jquery_raw .= qq~
		\$("#savebutt").click(function() {
			\$("#$lcpage-form").submit() ;
		}) ;
	~ ;
	
} #------------------------------------------------------------------------------------------

sub build_table_and_or_excel {
	
	my ($report) = @_ ;
	
	my $width = 105 ; 
	
	&report_xlsx_export_header("$xlsxreportname",$xlsxdir,'',$xlsx_title_heading) ;
	
	push @sql_col_display,"update" ;
	
	my $nr_of_cols = scalar @sql_col_display ;
	
	my @rev_sql_col_display = reverse @sql_col_display ;
	
	foreach (@rev_sql_col_display) { $lastchild++ ; $last_child{$_} = $lastchild ; } # &common_debug("last-child : $_ [$last_child{$_}]");	
	
	$xlsxrow-- ;
	
	my $cali_cnt = 0 ;  
	# # # # # # # # # # # # # # # # # # # # my $found_editable = 0 ; 
	my @all_select_ids = () ; 
	
	$format84 -> set_align("center") ; 
	
	our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; 
	
	our $max_frame_width = 0 ; 
	
	my %temp_files = () ; 
	
	my %default_val_id = () ; 
	
	
	foreach my $date_ref (sort {$sort_calibration_by_time_ref{$b} <=> $sort_calibration_by_time_ref{$a}} keys %sort_calibration_by_time_ref) {
		
		my $id = $sort_calibration_by_time_ref{$date_ref} ;
	
		next unless $id ; 
		
		$db{$table2}{$id}{event_system_ids} = $db{$table}{$id}{event_system_id_multiple} ;
	
		my $system_count = 0 ; my $system_day_cnt = 0 ; 
		
		my %system_has_daily_op = () ; my %default_op_ids = () ; 
		
		foreach my $system_row (split(/\|/,$db{$table}{$id}{daily_operator_ids})) {
			$system_count++ ; 
			next unless $system_row ;
			$system_day_cnt = 0 ;
			foreach my $col (split(/\;/,$system_row)) {
				$system_day_cnt++ ;
				next unless $col ; 
				$default_op_ids{$system_count}{$system_day_cnt} = $col if $col ;
				$system_has_daily_op{$system_count} = 1 if $col ; 
			}
		}	
		$system_count = 0 ; 
		
		unless (&common_check_if_string_contains_an_integer($db{$table}{$id}{event_system_id_multiple})) {
			$db{$table}{$id}{event_system_id_multiple} = ";none;" ; 
		} 
		
		# my @system_name_ids = split(";",$db{$table}{$id}{event_system_id_multiple}) ;		

		my @system_name_ids = split(/\;/,$db{$table}{$id}{event_system_id_multiple}) ;		
		my @club_ids        = split(/\;/,$db{$table}{$id}{club_ids}) ;
		my @op_ids        	= ($db{$table}{$id}{operator_ids} =~ /,/) ? split(/\,/,$db{$table}{$id}{operator_ids}) : ($db{$table}{$id}{operator_ids} =~ /;/) ? split(/\;/,$db{$table}{$id}{operator_ids}) : $db{$table}{$id}{operator_ids} ;	
		my @start_times 	= split(/\;/,";".$db{$table}{$id}{times_from}) ;	  
		my @end_times 		= split(/\;/,$db{$table}{$id}{times_to}.";") ;	  
		my @days_active		= split(/\;/,$db{$table}{$id}{days_active}) ;	  
		
		my $cnt_rows = 0 ;
		for (1 .. 50) {
			$cnt_rows = $_ if $system_name_ids[$_ - 1] or $club_ids[$_ - 1] ;  
		}

		$system_count = 0 ; 
		
		$colname_to_id{head_operator} 	= "head_operator" ;
		$colname_to_id{calibrator} 		= "calibrator_id" ;
		$colname_to_id{status} 			= "calibration_status" ;
		
		$preferred_title{head_operator} = "Head Operator" ; 
		$preferred_title{calibrator} 	= "Calibrator" ; 
		$preferred_title{status} 		= "Calibration Status" ;	
		
		$default_val_table{head_operator} = 'users' ;
		$default_val_table{calibrator} 	= 'users' ;
		$default_val_table{status} 		= 'calibration_status' ;
		$default_val_table{late_start} 	= 'late_start' ;
		$default_val_table{reason}		= 'reason' ;
		
		$db{late_start}{1}{name} 		= "Yes" ;
		$db{late_start}{2}{name} 		= "No" ;
		
		$db{reason}{1}{name} = "Equipment Failure" ;
		$db{reason}{2}{name} = "Operator Issue" ;
		$db{reason}{-1}{name} = "Other" ;
		
		$default_val_id{reason}{"Equipment Failure"} = 1 ;
		$default_val_id{reason}{"Operator Issue"} = 2 ;
		$default_val_id{reason}{"Other"} = -1 ;
		
		$default_val_id{late_start}{"Yes"} = 1 ;
		$default_val_id{late_start}{"No"} = 2 ;
		
		&calibration_get_status_frames($id) ; 
 
		foreach my $event_sys_id (@system_name_ids) {
			
			$system_count++ ;	
					
			next unless $event_sys_id ;

			next unless $db{event_systems}{$event_sys_id}{system_type} ;

			$system_day_cnt = 0 ; 
				
			foreach my $cal_date (sort keys %day_of_week) {
				
				my $srch_date_from_comp   = $i{date_from} ; $srch_date_from_comp =~ s/\-//g ;
				my $srch_date_to_comp     = $i{date_to} ; $srch_date_to_comp =~ s/\-//g ;
				my $date_from_comp        = substr($db{$table}{$id}{date_from},0,10) ; $date_from_comp =~ s/\-//g ;
				my $date_to_comp          = substr($db{$table}{$id}{date_to},0,10) ; $date_to_comp =~ s/\-//g ;
				my $cal_date_comp         = $cal_date ; # $cal_date_comp =~ s/\-//g ;
				   $cal_date              = substr($cal_date,0,4) . '-' . substr($cal_date,4,2) . '-' . substr($cal_date,6,2) ; 
				my $date_from             = substr($db{$table}{$id}{date_from},0,10) ;
				$system_day_cnt++ ;
							
				next if $cal_date_comp < $date_from_comp ;
				next if $cal_date_comp > $date_to_comp ;
 
				$cnt{$event_sys_id}{$id}++ ;
				
				next if $db{$table}{$id}{days_active} && !$days_active[$cnt{$event_sys_id}{$id}-1] ; 
				next if $cal_date_comp > $srch_date_to_comp ;
				next if $cal_date_comp < $srch_date_from_comp ;
				
				next if $i{calibration_status} && $i{calibration_status} ne 'all' && $i{calibration_status} ne $default_vaules{status}{$id}{$event_sys_id}{$cnt{$event_sys_id}{$id}} ;

				$cali_cnt++;
					
				$xlsxcol = 0 ; 
				
				$print_tbody .= qq~<tr id="$id$dow">~ if $report ;
				
				my $nr_of_cols_cnt = $nr_of_cols + 1 ; 
				
				our $default_javascript = qq~~ ;
				
				my $contains_select = 0 ; 
				
				foreach (@sql_col_display) { 

					$nr_of_cols_cnt-- ; 
					
					next unless $_ ; # blank for the buttons column
					
					my $formatting = $format84 ;
					my $val        = $db{$table}{$id}{$_} ;
					our $val_min    = $val  ;
					my $align      = qq~ class="dt-center"~ ; 
					my $nowrap     = '' ;

					my $sys_day_cnt = $cnt{$event_sys_id}{$id} ;
					
					my $field = "" ; my $default_val = $default_vaules{$_}{$id}{$event_sys_id}{$sys_day_cnt} ; my $only_display_val = 0 ; my $background_color = "#424949" ; my $default_val_is_saved = ($default_val) ? 1 : 0 ;	

					if ($_ eq 'request_sent' || $_ eq 'live' || $_ eq 'late_start' || $_ eq 'reason' || $_ eq 'comments') {
	
						$val_min = '' ;
		
						$formatting = $format91 ;

						if ($report) {						
							# if ($db{$table}{$id}{after_start_date} and $event_sys_id ne "-1") {	
							# &common_debug("=== $cal_date_comp >= $now_ccyymmdd && $event_sys_id ne -1") ; 
							
							$field = ($colname_to_id{$_}) ? "$colname_to_id{$_}\_$id\_$event_sys_id\_$sys_day_cnt" : "$_\_$id\_$event_sys_id\_$sys_day_cnt" ;
						
							if (($cal_date_comp >= $now_ccyymmdd && $event_sys_id ne "-1") || (!$default_val)) {		
								$preferred_title{$field} = $preferred_title{$_} ;
								$opts{$field}            = $opts{$_} ;
								# $useropts{'common'}{'css'} .= qq~.$_ { min-width:180px; } ~ ; ????
								$val_min = $db{$default_val_table{$_}}{$default_val}{name} ;
								$found_editable	= 1 ; 							
								$contains_select = 1 ; 
							} else {
								$default_val = $db{$default_val_table{$_}}{$default_val}{name} if $default_val_table{$_} ;
								$default_val = "None" if $default_val eq 'none' ;
								$only_display_val = 1 ;
							}
						} else {
							$default_val = $db{$default_val_table{$_}}{$default_val}{name} if $default_val_table{$_} ;
							$default_val = "None" if $default_val eq 'none' ;
							$only_display_val = 1 ;
						}
					}
					
					if ($_ eq 'count') {		
						$val = $cali_cnt ; 
					} elsif ($_ eq 'event') {	
						$val = "$db{$table}{$id}{ref} [$id]" ;		
					} elsif ($_ eq 'calib_date' || $_ eq 'date') {			
						# $val = "$cal_date [$day_of_week{$cal_date}]" ;
						$val = &common_min_date_as_string("$cal_date") ;
						$nowrap = "nowrap" ;
					} elsif ($_ eq 'day') {			
						$val = "$sys_day_cnt" ;
					} elsif ($_ eq 'start_date') {	
						$nowrap = "nowrap" ;
						$val = &common_min_date_as_string($date_from) ;
					} elsif ($_ eq 'start_time') {	
						if ($sys_day_cnt == 1 or ($sys_day_cnt > 1 and not $start_times[$sys_day_cnt-1])) {
							$val = substr($db{$table}{$id}{date_from},11,5) ;		
						} else {
							$val = substr($start_times[$sys_day_cnt-1],0,5) ;
						} 
					} elsif ($_ eq 'venue') {			
						my @oids = split(/\,/,$db{$table}{$id}{organisation_ids}) ;
						foreach $_oid (@oids) {
							$val .= $db{organisations}{$_oid}{name} . '<br>' ;
						}
						$val = substr($val,0,-4) if $val ;
					} elsif ($_ eq 'region') {				
						$val = $db{regions}{$db{$table}{$id}{region_id}}{code} ;		
					} elsif ($_ eq 'system') {			
						$val = '' ; 
						$val = qq~($event_sys_id) $db{event_systems}{$event_sys_id}{name}~ ; 
						$val .= qq~ ($db{event_systems}{$event_sys_id}{description})~ if $db{event_systems}{$event_sys_id}{description} ; 
					} elsif ($_ eq 'sport') {		
						$val = '' ; 
						foreach my $sport_id (split(",",$db{$table}{$id}{sport_type_ids})) {
							$db{sport_types}{$sport_id}{name} = uc $db{sport_types}{$sport_id}{name} ;
							$val .= qq~$db{sport_types}{$sport_id}{name}<br>~ ; 
						}
						$val = substr($val,0,-4) if $val ;	
					} elsif ($_ eq 'operator') {	
						$nowrap = "nowrap" ;
						$val = '' ; 
						# $val = $db{users}{$table_op_ids[$system_count - 1]}{name} if $table_op_ids[$system_count - 1] ;			
						$val = ($default_op_ids{$system_count}{$cnt{$event_sys_id}{$id}}) ? $db{users}{$default_op_ids{$system_count}{$cnt{$event_sys_id}{$id}}}{name} : (!$default_op_ids{$system_count}{$system_day_cnt} && $system_has_daily_op{$system_count}) ? "None" : $db{users}{$op_ids[$system_count - 1]}{name} ;			
						# $formatting = $format92 if $event_cnt == 2 ;	
						$formatting = $format92 if $cali_cnt == 2 ;	
					} elsif ($_ eq 'request_sent') {
						# $val .= ($only_display_val && $default_val) ? qq~<input name='$field' value='$default_val' type='hidden'>~ : qq~~ ;  
						$default_val = "$now_hour:$now_min:$now_sec" unless $default_val ; 
						$val .= &common_min_table_timepicker($field,$default_val,$only_display_val,$cali_cnt,$nr_of_cols_cnt,$background_color,$default_val_is_saved,$_) ; 						
					} elsif ($_ eq 'live') {
						# $val .= ($only_display_val) ? qq~<input name='$field' value='$default_val' type='hidden'>~ : qq~~ ;  					
						$default_val = "$now_hour:$now_min:$now_sec" unless $default_val ;
						$val .= &common_min_table_timepicker($field,$default_val,$only_display_val,$cali_cnt,$nr_of_cols_cnt,$background_color,$default_val_is_saved,$_) ; 
					} elsif ($_ eq 'late_start') {
						if ($default_val eq '1') { # ||  
							$background_color = "#AD0502" ;		
							$formatting = $format90 ;
						} elsif ($default_val  eq '2') { #done  ||  
							$background_color = "#2ECC71" ;		
							$formatting = $format88 ;	
						}
						$preferred_placeholder{$field} = "Select Late Start $id $system_count $sys_day_cnt" ; 
						$val = &common_min_table_select($field,$default_val,$only_display_val,$cali_cnt,$nr_of_cols_cnt,$background_color,$default_val_is_saved,$_) ;
						$val_min = ($only_display_val) ? $default_val : $db{late_start}{$default_val}{name} ;
						# $val .= ($only_display_val) ? qq~<input name='$field' value='$default_val_id{$_}{$default_val}' type='hidden'>~ : qq~~ ;  								
					} elsif ($_ eq 'calibration_done') {
						
						$nowrap = 'nowrap' ; 
						$val = &common_min_date_as_string($default_val) ; 

						if ($calibration_status_hash{$id}{$event_sys_id}{$sys_day_cnt} eq '3') { #done
							
							my $startdatetime = $db{$table}{$id}{date_from} ;
							$startdatetime =~ s/\://g ;
							$startdatetime =~ s/\-//g ;
							$startdatetime =~ s/ //g ;
							
							my $done_set_date = $default_val ;
							$done_set_date =~ s/\://g ;
							$done_set_date =~ s/\-//g ;
							$done_set_date =~ s/ //g ;	
							
							if (!$done_set_date || ($done_set_date && $startdatetime && $done_set_date < $startdatetime)) {
								$background_color = "#2ECC71" ;		
								$formatting = $format88 ;		
							} elsif ($done_set_date && $startdatetime && $done_set_date >= $startdatetime) {	
								$background_color = "#AD0502" ;		
								$formatting = $format90 ;
							}
							$default_val_is_saved = 1 ;
						} else {
							$default_val_is_saved = 0 ;
						}
						
					} elsif ($_ eq 'reason') {
						$preferred_placeholder{$field} = "Select Reason $id $system_count $sys_day_cnt" ; 
						$val = &common_min_table_select($field,$default_val,$only_display_val,$cali_cnt,$nr_of_cols_cnt,$background_color,$default_val_is_saved,$_) ; 	
						# $val .= ($only_display_val) ? qq~<input name='$field' value='$default_val_id{$_}{$default_val}' type='hidden'>~ : qq~~ ;  			
						$val_min = ($only_display_val) ? $default_val : $db{reason}{$default_val}{name} ;
					} elsif ($_ eq 'comments') {
						$preferred_placeholder{$field} = "Comments $id $system_count $sys_day_cnt" ; 
						$val = &common_min_table_textarea($field,$default_val,$only_display_val,$cali_cnt,$nr_of_cols_cnt,$background_color,$default_val_is_saved,$_) ; 
						# $val .= ($only_display_val) ? qq~<input name='$field' value='$default_val' type='hidden'>~ : qq~~ ;  	
					} elsif ($_ eq 'frames') {
						$nowrap = "nowrap" ;
						$val .= &calibration_get_frames($id,$event_sys_id,$sys_day_cnt) ;
					} elsif ($_ eq 'update') {
						
						if (($report && $cal_date_comp >= $now_ccyymmdd && $event_sys_id ne "-1") || $contains_select) {
							$val = &common_min_table_checkbox("update_$id\_$event_sys_id\_$sys_day_cnt") ; 
							chop $default_javascript if $default_javascript ;
							if ($default_javascript) {
								push @default_javascript_by_id, qq~"$id\_$event_sys_id\_$sys_day_cnt":{$default_javascript}~ ;
								push @all_update_field_ids,"#selectHead_operator\_$id\_$event_sys_id\_$sys_day_cnt,#selectCalibrator_id\_$id\_$event_sys_id\_$sys_day_cnt,#selectCalibration_status\_$id\_$event_sys_id\_$sys_day_cnt,#timepickerRequest_sent\_$id\_$event_sys_id\_$sys_day_cnt,#timepickerLive_$id\_$event_sys_id\_$sys_day_cnt,#selectLate_start_$id\_$event_sys_id\_$sys_day_cnt,#selectReasons_$id\_$event_sys_id\_$sys_day_cnt,#textareaComments_$id\_$event_sys_id\_$sys_day_cnt" ;
							} 
						} else {
							$val = '' ;
						}
					}
					
					if ($_ ne 'live' && $_ ne 'late_start' && $_ ne 'request_sent' && $_ ne 'calibration_done' && $_ ne 'reason' && $_ ne 'comments' && $_ ne 'frames' && $_ ne 'update') {
						$val_min = $val unless $val_min ;
						$val_min =~ s/\<br>/\;/g ;	
					} else {
						$val_min = $default_val if $default_val && $default_val_is_saved && !$val_min ;
					}
					$val_min =~ s/MUSTBEBLANK//g ;
					# if ($_ ne 'head_operator' && $_ ne 'status' && $_ ne 'calibrator' && substr($_,0,5) ne 'shift' && $_ ne 'update') {
						# $val_min = $val ;
						# $val_min =~ s/\<br>/\;/g ;	
					# }
					
					my $style = ($default_val_is_saved && $background_color && $_ eq 'calibration_done') ? "style='background-color:$background_color;'" : "" ;
					
					$print_tbody .= qq~<td $align $nowrap $style>$val</td>~ if $report ; 

					&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$formatting) if $val_min && $_ ne 'update' ;
					$xlsxcol++ ;
				}
				
				$print_tbody .= qq~</tr>~ if $report ;

				$xlsxrow++ ; 	
			}

		}
	}
	
	$worksheet{$ws}->set_column(0,0,7.5) ; 
	$worksheet{$ws}->set_column(1,1,40) ; 
	$worksheet{$ws}->set_column(2,2,15) ; 
	$worksheet{$ws}->set_column(3,3,10) ; 
	$worksheet{$ws}->set_column(4,4,15) ;  
	$worksheet{$ws}->set_column(5,5,10) ;  
	$worksheet{$ws}->set_column(6,6,40) ;  
	$worksheet{$ws}->set_column(7,7,10) ;  
	$worksheet{$ws}->set_column(8,10,40) ;  
	$worksheet{$ws}->set_column(11,12,15) ;  
	$worksheet{$ws}->set_column(13,15,20) ;   
	$worksheet{$ws}->set_column(16,16,$max_frame_width/7) ;

	my $all_select_ids_string = join(",",@all_select_ids) ; 
	$trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({allow_single_deselect:true});~ ;
	
	&common_min_table_timepicker_jquery("[id^='timepickerRequest_sent_'],[id^='timepickerLive_']")	;
	
	# $worksheet{$ws}->set_row(0,100) ;
	# $worksheet{$ws}->set_column(4,4,15) ;

	&report_xlsx_export_footer('L',15,$xlsxdir) ;
	
	foreach (keys %temp_files) {
		unlink ($_) or die "unable to delete - $_ $!";
	}
	
} #-------------------------------------------------------------------------------

sub calibration_get_frames {
	
	my ($id,$event_sys_id,$sys_day_cnt) = @_ ; 

	$nowrap = "nowrap" ;
	my $attachments = "" ; my $attach_butt = "" ; 
	
	if ($gallery{$id}{$event_sys_id}{$sys_day_cnt}) {
		
		my $margin = 5 ; my $scaled_height = 100 ; my $total_width = 0 ; my $max_height = 350 ;  my $max_image_height = 0 ; 
		
		foreach my $img_name (split(/\;/,$gallery{$id}{$event_sys_id}{$sys_day_cnt})) {
			
			my $file_path = "$htmlpath/uploads/calibration_status_uploads/$id/$img_name";

			my ($width, $height) = imgsize($file_path);
			
			if ($height && -f $file_path) {
				
				my $final_file = $file_path;  # default: use original
				# my $scaled_width  = $width;
				# my $scaled_height = $height;

				if ($height > $max_height) {
					
					$max_image_height = $max_height if $max_image_height < $height ;
					
					# Load and resize with fixed height = 500
					my $img = Image::Magick->new ;
					$img->Read($file_path) ;

					my $scale = $max_height / $height;
					$width  = int($width * $scale);
					$height = $max_height;

					$img->Resize(geometry => "${width}x${height}");

					# Write to temporary file
					my ($fh, $tempfile) = tempfile(SUFFIX => '.jpg');
					$img->Write(filename => $tempfile, quality => 70);

					$final_file = $tempfile;
					$temp_files{$tempfile} = 1;   # track temp file for cleanup
				} else {
					$max_image_height = $height if $max_image_height < $height ;
				}
				
				($width,$height) = imgsize($final_file);
				
				$total_width += $margin;

				&xlsxcreator_insert_image($ws,$xlsxrow,$xlsxcol,$final_file,$total_width,$margin,150/$height,150/$height) if $height > 150 ;
				&xlsxcreator_insert_image($ws,$xlsxrow,$xlsxcol,$final_file,$total_width,$margin) if $height <= 150 ;

				$total_width += $width*150/$height;
			}

			$total_width += $margin;
		}

		$worksheet{$ws}->set_row($xlsxrow,(2*$margin+150)*(83/110)) if $max_image_height ;
		
		$max_frame_width = $total_width if $total_width && $max_frame_width < $total_width ;
		
		$attachments .= &calibration_get_uploads_list($db{$table2}{$id}{event_quote_id},$gallery{$id}{$event_sys_id}{$sys_day_cnt}) ;
	}
		
	if ($attachments) {
	
		$attach_butt = qq~
			&nbsp;
			<a href="#" data-toggle="popover" data-placement="left" data-content="$attachments" title="Uploads" data-html="true" data-trigger="focus" class="btn btn-round btn-default">
				<i class="glyphicon glyphicon-paperclip" style="top:4px;"></i>
			</a>
		~ ; 
		
	}

	my $val_return = qq~
		$attach_butt
		<a href="javascript:dlgMdl('$useropts{scripts}/dialog/calibration_status_report_uploads.pl?$id&$event_sys_id&$sys_day_cnt','Edit Images','','medium-dialog');" class="btn btn-round btn-info" data-toggle="tooltip" data-placement="left" title="" data-original-title="Edit Images">
			<i class="glyphicon glyphicon-edit" style="top:4px;">
			</i>
		</a>
	~ ; 	
	
	return $val_return ;
	
} #-------------------------------------------------------------------------------

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

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

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

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

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

sub page_opts {

	our $glyphicon = 'list' ;
	our $lcpage    = 'calibration-status-report' ;

	&common_page_name ;
	   
	our $table     	= 'event_quotes' ;
	our $table2		= 'calibration_status_report' ;
	$page_title   	= 'Calibration Report' ;

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

sub report_screen {

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

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

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

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

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

	$print_box_content_rows  .= &common_min_form_select('calibration_status','') ; 
	$print_box_content_rows  .= &common_min_form_select('calibrator_id','') ; 
	$print_box_content_rows  .= &common_min_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 ;

$extra_form_fields .= qq~
<input type="hidden" name="date_from" 			value="$i{date_from}">
<input type="hidden" name="date_to"				value="$i{date_to}">
<input type="hidden" name="calibrator_id"		value="$i{calibrator_id}">
<input type="hidden" name="calibration_status" 	value="$i{calibration_status}">~;

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

$useropts{'common'}{'css'} .= qq~tbody tr td { font-size: 10px; } ~ ;

require _blank ;

exit ;

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

sub redirect_screen {
	
&common_min_alert_type ;

print <<ENDOFTEXT;
<!DOCTYPE html>
<html lang="en">
<head>    
    <meta charset="utf-8">
    <title>$useropts{title}</title>
    <script src="$useropts{'bower_components'}/jquery/jquery.min.js"></script>   
</head>
<body>
<script>

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

</script>
</body>

<form role="form" id="$lcpage-form" method="post" action="$lcpage">
<input type="hidden" name="iaction"				value="report">
<input type="hidden" name="date_from"        	value="$i{date_from}">
<input type="hidden" name="date_to"          	value="$i{date_to}">
<input type="hidden" name="calibrator_id"      	value="$i{calibrator_id}">
<input type="hidden" name="calibration_status"	value="$i{calibration_status}">
<input type="hidden" name="isaved"				value="$success">
</form>

</html>
ENDOFTEXT
#

exit ;

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

use common ;
use common_min ;
use report ;
use xlsxcreator ;
use today ;
use calibration ;

1;