#!/usr/bin/perl

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

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

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

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

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

&today;

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

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

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

our $temp_calibrator_report = 1 ;

# our $debug   = 1 ;
# our $testing = 1 ;
# our $testing = ($username eq 'handre') ? 1 : 0 ;

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

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

&page_opts ;

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

our $srchscr   = 1 ;

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

# if ($iaction eq 'delete') {  	
	# &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; 
		# &list_screen ;    
		# &delete ;
		# $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
	# &db_close_conn ;
	# exit if $username eq 'handre' && $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 hidden_fields {
	
	# $ignore{id} = 1 ;
	$ignore{iaction} = 1 ;  
	$ignore{date} = 1 ;   
	$ignore{temp_calibrator_id} = 1 ; 
	for my $date_cnt (1 .. $date_counter) {	
		for (1 .. 4) {
			$ignore{"shifttempcalibratorid_$_\_$date_cnt"} = 1 ; 
			$ignore{"shift_temp_calibrator_$_\_$date_cnt"} = 1 ; 
		}
	}
	# $ignore{temp_calibrator_ids} = 1 if $date_inp_val < $today_val ; 
	$ignore{update} = 1 ;
	$ignore{update_table_1} = 1 ;
	$ignore{"itv-table_length"} = 1 ;  
	
} #------------------------------------------------------------------------------------------

sub update {
	
	&schedule_update("shift_operator_ids","temp_calibrator_ids","shifttempcalibratorid","") ; 

} #------------------------------------------------------------------------------------------
 
# sub delete {
	
	# my %ii = %i ; 
	# %i = () ; 
	# foreach my $support_to_shift (split(/\|/,$db{$table_}{$ii{date}}{temp_calibrator_support_shifts})) {
		# my @abc = split(/\:/,$support_to_shift) ;
		# if ($abc[0] ne $ii{id}) {
			# $i{temp_calibrator_support_shifts} .= qq~$support_to_shift|~ ;
		# }
	# }
	# chop $i{temp_calibrator_support_shifts} if $i{temp_calibrator_support_shifts} ;
	# &db_min_upd("$table_","`date`='$ii{date}'") ; 		
	
# } #------------------------------------------------------------------------------------------

sub report_ifields {
	
	&load_search_vars ;
	
	# if ($i{date}) { # check dates
		# push @report_sql, " `date_from` <= '$i{date} 23:59:59' AND '$i{date} 00:00:00' <= `date_to` "  ; 
		# push @report_results, "DATE IS '$i{date}'" ;
	# } else {
		# $error = qq~PLEASE ENTER A DATE!~ ; 
		# &report_screen; 
	# }
	
	my $date_from_val = $i{date_from} ; my $date_to_val = $i{date_to} ; 
	
	$date_from_val =~ s/\-//g ; $date_to_val =~ s/\-//g ;

	if ($i{date_from} && $i{date_to} && $date_from_val > $date_to_val) {  
		$error = qq~THE START MUST BE BEFORE THE END DATE!!!~ ; 
		&report_screen; 	
	} elsif ($i{date_from} && $i{date_to}) { # check dates
		push @report_sql, "(('$i{date_from} 00:00:00' <= `date_from` AND `date_from` <= '$i{date_to} 23:59:59') OR ('$i{date_from} 00:00:00' <= `date_to` AND `date_to` <= '$i{date_to} 23:59:59') OR (`date_from` <= '$i{date_from} 00:00:00' AND '$i{date_to} 23:59:59' <= `date_to`))" ; ############################################### > OR >=
		push @report_results, "(EVENT BETWEEN '$i{date_from}' AND '$i{date_to}')" ;
	} else {
		$error = qq~PLEASE ENTER A START AND END DATE!!!~ ; 
		&report_screen; 
	}
	
	if ($i{temp_calibrator_id} and $i{temp_calibrator_id} ne 'all') { 
		push @report_results,"`TEMP CALIBRATOR` = '$db{users}{1}{name}'" ;
		push @report_sql, " `temp_calibrator_ids` LIKE '%$i{temp_calibrator_id}%' "  ; 
	} elsif ($i{temp_calibrator_id} and $i{temp_calibrator_id} eq 'all') {
		push @report_results,"`TEMP CALIBRATORS` = 'ALL'" ;
	} else {
		# push @report_sql, "(`user_id` = '')" ; 
	}

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

	if ($iaction eq 'save') {
		$isaved = qq(SUCCESSFULLY SAVED) ; 
	} elsif ($iaction eq 'delete') {
		$isaved = qq(SUCCESSFULLY DELETED SUPPORT TEMP) ; 
	} elsif (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) ; 
 
 	# my @date = split(/ /,$i{date}) ; 

	# my ($year_inp,$month_inp,$day_inp) = split(/\-/,$date[0]) ; 
	
	# our $date_inp_val = int("$year_inp$month_inp$day_inp") ; 
	# our $today_val = int("$now_year$now_mm$now_dd") ; 
 
} #------------------------------------------------------------------------------------------

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

sub list_screen {
	
	# $print_box_content_rows .= &common_min_forms_start("$lcpage") if $date_inp_val >= $today_val ;
	
	$print_box_content_rows .= &common_min_forms_start("$lcpage") ;

	&schedule_load_list_vars("$srch_where_sql") ;
 
	$fcol = 12 ; 
	
	my $report = 1 ; 
	
	our $xlsxdir = "temp_calibrator_report" ; 
	
	our $xlsxreportname = "Temp_Calibrator_Allocations" ; 
 
	my $date = &common_write_date_interval($i{date_from},$i{date_to}) ;
	
	our $xlsx_title_heading = "Temp Calibrator Allocations $date" ;

	# my $field_name = "shift_monitor" ;
	# my $uc_field_name = ucfirst $field_name ;
	
	our $print_tbody_extra = qq~~ ;

	our @sql_col_display_extra = ("date","shift_1_(07:00-10:00)","shift_2_(10:00-13:00)","shift_3_(13:00-16:00)","shift_4_(16:00-19:00)") ;
	# our @sql_col_display_extra = ("date","shift_1_(08:00-11:00)","shift_2_(11:00-14:00)","shift_3_(14:00-17:00)","shift_4_(17:00-21:00)") ;
	push @sql_col_display_extra,"update" ;
	# if $date_inp_val >= $today_val ;
	
	our @sql_col_display = ("count","event","date","day","start_date","start_time","end_time","venue","region","type","system","sport","operator") ;
	
	# push @sql_col_display,"update" if ($monitoring_report || $temp_calibrator_report) && $date_inp_val >= $today_val ; 
	
	&report_xlsx_export_header("$xlsxreportname",$xlsxdir,'',$xlsx_title_heading) ;	
	
	&schedule_build_extra_table("shift_temp_calibrator","shift_operator_ids","temp_calibrator_ids",'',"select_temp_calibrators") ; 
	
	our @sql_col_display_2 = ("date","name","shift","update","") ;
	
	&schedule_build_extra_second_table("temp_support","shift_operator_ids","temp_calibrator_support_shifts") ; 
 
	my $table_col_name = "temp_calibrator_ids" ; 
	
	$xlsxrow-- ;
	
	&schedule_build_table("temp_calibrator_ids") ; 
	
	# if ($date_inp_val >= $today_val) {
		# $trigger_jquery_raw .= qq~
			# \$("#itv-table tr th:nth-last-child(5)").css("width","10%") ;
			# \$("#itv-table tr th:nth-last-child(4)").css("width","10%") ;
			# \$("#itv-table tr th:nth-last-child(3)").css("width","10%") ;
			# \$("#itv-table tr th:nth-last-child(2)").css("width","10%") ;
		# ~ ;	
				
	# } else {
		# $trigger_jquery_raw .= qq~
			# \$("#select_temp_calibrators tr th:nth-last-child(1)").css("width","23%") ;
			# \$("#select_temp_calibrators tr th:nth-last-child(4)").css("width","23%") ;
			# \$("#select_temp_calibrators tr th:nth-last-child(3)").css("width","23%") ;
			# \$("#select_temp_calibrators tr th:nth-last-child(2)").css("width","23%") ;
		# ~ ;	 
	# }

	# &calibration_build_table_and_or_excel(1) ; 
	
	# if ($found_after_date) {
		
	

	# } else {
		# $trigger_jquery_raw .= qq~
			# \$("#itv-table tr th:nth-last-child(2)").css("width", "7.5%") ;
			# \$("#itv-table tr th:nth-last-child(3)").css("width", "7.5%") ;
			# \$("#itv-table tr th:nth-last-child(4)").css("width", "7.5%") ;
			# \$("#itv-table tr th:nth-last-child(5)").css("width", "7.5%") ;
			
		# ~ ;
	# }

	$fnsortorder = 'asc' ;
	
	&common_min_extra_crumb("$lcpage","Search Screen") ;
 
} #------------------------------------------------------------------------------------------

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

sub page_opts {

	our $glyphicon = 'list' ;
	our $lcpage    = 'temp-calibrator-allocations' ;

	&common_page_name ;
	   
	our $table     = 'event_quotes' ;
	$page_title    = 'Temp Calibrator Allocations' ;

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

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',"$now_year-$now_mm-$now_dd") ; #unless $i{date_from} ;  
	$print_box_content_rows .= &common_min_form_datepicker('date_to',"$next_year-$next_month-$next_day") ; #unless $i{date_from} ;  
	
	push @date_value_ids,"input[name='date_from']" ;
	push @date_value_ids,"input[name='date_to']" ;
	
	&common_min_table_validate_date_inputs_jquery ;	
	
	$preferred_title{temp_calibrator_id} = "Temp Calibrator" ;
	
	# &db_min_ro('users',"id,name","`user_type` = 'support' OR `user_type` = 'casual_calibrator'",'','') ;
	# &db_min_ro('users',"id,name,username","`name` NOT LIKE 'Rory%'",'','') ;

	$selected{temp_calibrator_id}{all} = 'SELECTED' ;
	
	# if ($i{temp_calibrator_id}) {
		# $selected{temp_calibrator_id}{$i{temp_calibrator_id}} = 'SELECTED' ;
		# $selected{temp_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{temp_calibrator_id} .= qq~<option value="$_" $selected{temp_calibrator_id}{$_}>$db{users}{$_}{name}</option>~ ; 
	# }
	$opts{temp_calibrator_id} .= qq~<option value="all" $selected{temp_calibrator_id}{all}>All</option>~ ; 
	
	$print_box_content_rows  .= &common_min_form_select('temp_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 = "temp-calibratortest-report" ;

if ($s{no}) { $page = $lcpage ; }

# &db_min_ro('daily_monitor_ids','date,monitor_ids') ; 

my @sql_col_display_22 = @sql_col_display ;

@sql_col_display = @sql_col_display_extra ;
 
&common_min_thead ;

# &common_min_thead_2 ;

# $db{shift_operator_ids}{$i{date}}{temp_calibrator_support_shifts} .= "||" ;


# style="padding-bottom:10px;margin-left:10px;"

# alter table `shift_operator_ids` add column `temp_calibrator_support_shifts` varchar(255) default null 
$print_box_content_rows .= qq~	
    <table id="select_temp_calibrators" class="table table-striped table-bordered bootstrap-datatable responsive">    
        $print_thead
        <tbody>
            <tr>
				$print_tbody_extra
			</tr>
        </tbody>
    </table>    
	 $print_tbody_extra_2
	~ ;
	
		# <table id="select_temp_calibrators_2" class="table table-striped table-bordered bootstrap-datatable responsive">    
        # $print_thead_2
        # <tbody>
			# $print_tbody_extra_2
        # </tbody>
    # </table>
	# $plus_button
	

@sql_col_display = @sql_col_display_22 ; 

&common_min_thead ;

&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="temp_calibrator_id"	value="$i{temp_calibrator_id}">
~;

for (1 .. $date_cnt) {
	
	$extra_form_fields .= qq~
		<input type="hidden" name="shifttempcalibratorid_1_$_" id="shift-temp-calibrator-id-1-$_" value="">
		<input type="hidden" name="shifttempcalibratorid_2_$_" id="shift-temp-calibrator-id-2-$_" value="">
		<input type="hidden" name="shifttempcalibratorid_3_$_" id="shift-temp-calibrator-id-3-$_" value="">
		<input type="hidden" name="shifttempcalibratorid_4_$_" id="shift-temp-calibrator-id-4-$_" value=""> 
	~;
	
}

# $print_box_content_rows .= &common_min_forms_end('','','save') if $date_inp_val >= $today_val ;
$print_box_content_rows .= &common_min_forms_end('','','save')  ;

require _blank ;

exit ;

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

sub common_min_thead_2 {
	
	my $colspan = scalar @sql_col_display_2 ; 
	
	$print_thead_2  = qq(<THEAD><TR><TH class="dt-center" colspan="$colspan">TEMP SUPPORT</TH></TR><TR>) ; #

	foreach (@sql_col_display_2) { 
		my $coltitle = $_ ; $coltitle =~ s/\_id//g ; $coltitle =~ s/\_/ /g ; $coltitle = uc $coltitle ; $coltitle = $replace_blank_table_top_right if $coltitle eq '' and $replace_blank_table_top_right ;
		$print_thead_2 .= qq(<TH class="dt-center">$coltitle</TH>);
	}
		
	# if ($add_th_row) { $print_thead_2 .= $add_th_row ; } # used in agent_commission_report.pl and cruiseline_commission_report.pl

	$print_thead_2 .= qq(</TR></THEAD>) ;
    
} #-------------------------------------------------------------------------------


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="temp_calibrator_id"      	value="$i{temp_calibrator_id}">
<input type="hidden" name="isaved"				value="$success">
</form>

</html>
ENDOFTEXT
#

exit ;

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

use common ;
use report ;
use xlsxcreator ;
use today ;
# use calibration_test ;
use schedule ; 
1;