#!/usr/bin/perl

BEGIN { use lib '/usr/home/cfg' ; require push_inc ; }
    
require cfg ;
# unless ($username eq 'handre') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; }
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------

use CGI::Carp qw(fatalsToBrowser);
use CGI;

&today;

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

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

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

our $double_box_layout = 1 ;

our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab

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

&page_opts ; 

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

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

if ($iaction eq 'update') {  
	&common_min_load_params ;
	&validate ;
	&update ;
    &common_min_screen2 ; 
	exit ;
}

&common_min_action ;

exit ;

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

sub validate {
 
	my $exists   = '' ;
	
	# $i{item_name} = lc $i{item_name} ;
	# $i{item_name} =~ s/ //gi ;

	&db_min_ro($table,'*',"name = '$i{name}'",'name','') ;

	foreach my $id (keys %{$db{$table}}) {
		next if $i{id} && $i{id} eq $id ; 
		if (lc $db{$table}{$id}{name} eq lc $i{name}) {
			$exists = 1 ; 
		}
	}

	if ($exists) {
		$alert = &common_min_alert('warning',"'$i{name}' AS AN EVENT COST ITEM NAME ALREADY EXISTS!",'ok') ;
		%col_name = ();
		&common_min_error_screen;
		&common_min_screen1;
	}
	
	my %seen_full_half_day = () ; 
	
	$seen_full_half_day{$i{full_half_day_add}} += 1 if $i{full_half_day_add};
	
	my $full_day_rate = 0 ; my $half_day_rate = 0 ;
	$full_day_rate = $i{rates_add} if $i{rate_add} && $i{full_half_day_add} eq '1' ;
	$half_day_rate = $i{rates_add} if $i{rate_add} && $i{full_half_day_add} eq '2' ;
	
	for (1 .. 2) {
		$seen_full_half_day{$i{"full_half_day_$_"}} += 1 if $i{"full_half_day_$_"} ; 
		$full_day_rate = $i{"rates_$_"} if $i{"rates_$_"} && $i{"full_half_day_$_"} eq '1' ;
		$half_day_rate = $i{"rates_$_"} if $i{"rates_$_"} && $i{"full_half_day_$_"} eq '2' ;
	}
	
	my $extra_full_half = '' ;
	
	if ($seen_full_half_day{1} > 1 || $seen_full_half_day{2} > 1) {
		if ($seen_full_half_day{1} > 1) {
			$extra_full_half = 'Full' ;
		}
		if ($seen_full_half_day{2} > 1) {
			$extra_full_half = 'Half' ;
		}
	}
	
	if ($extra_full_half) {
		$alert = &common_min_alert('warning',"ONLY SELECT A MAX OF ONE FULL AND HALF DAY!",'ok') ;
		%col_name = ();
		$i{id} = '' if $iaction eq 'save' ;
		foreach (keys %i) { $db{$table}{''}{$_} = $i{$_} ; }
		&common_min_add_screen ;
		&common_min_screen1 ;		
	}	
	
	if ($half_day_rate > $full_day_rate) {
		$alert = &common_min_alert('warning',"HALF DAY RATE MUST BE LESS THAN FULL DAY!",'ok') ;
		%col_name = ();
		$i{id} = '' if $iaction eq 'save' ;
		foreach (keys %i) { $db{$table}{''}{$_} = $i{$_} ; }
		&common_min_add_screen ;
		&common_min_screen1 ;		
	}
	
	# $now_ccyymmdd
		
	# &db_min_ro($table,'1,valid_from,valid_to,rates,full_half_day',"id='$i{id}'",'name','') ;
	# &db_min_ro($table,'1,rates,full_half_day',"id='$i{id}'",'name','') ;
	
	# my $cnt1 = 0 ; 
	
	# my $saved_valid_from_str 		= "$db{$table}{1}{valid_from};$i{valid_from_add}" ;
	# my $saved_valid_to_str 			= "$db{$table}{1}{valid_to};$i{valid_to_add}" ;
	# my $saved_rates_str 			= "$db{$table}{1}{rates};$i{rate_add}" ;
	# my $saved_full_half_day_str 	= "$db{$table}{1}{full_half_day};$i{full_half_day_add}" ;
	
	# $saved_valid_from_str =~ s/\-//g ;
	# $saved_valid_to_str =~ s/\-//g ;
	
	# my @saved_valid_from	= split(/\;/,$saved_valid_from_str) ;
	# my @saved_valid_to 		= split(/\;/,$saved_valid_to_str) ;
	# my @saved_rates			= split(/\;/,$saved_rates_str) ;
	# my @saved_full_half_day	= split(/\;/,$saved_full_half_day_str) ;
	
	# my $input_valid_from_str 	= qq~~ ;
	# my $input_valid_to_str 		= qq~~ ;
	# my $input_rates_str 		= qq~~ ;
	# my $input_full_half_day_str = qq~~ ;
	
	# foreach (@saved_rates) {
		# $cnt1++ ;
		# $input_valid_from_str 		.= qq~$i{"valid_from_$cnt1"};~ ;
		# $input_valid_to_str 		.= qq~$i{"valid_to_$cnt1"};~ ;
		# $input_rates_str 			.= qq~$i{"rate_$cnt1"};~ ;
		# $input_full_half_day_str 	.= qq~$i{"full_half_day_$cnt1"};~ ;
	# }
	
	# my @input_valid_from_arr	= split(/\;/,$input_valid_from_str) ;
	# my @input_valid_to_arr 		= split(/\;/,$input_valid_to_str) ;
	# my @input_rates_arr			= split(/\;/,$input_rates_str) ;
	# my @input_full_half_day_arr	= split(/\;/,$input_full_half_day_str) ;
	
	# $cnt1 = 0 ; 
	 
	# foreach my $rate1 (@saved_rates) {
		# my $cnt2 = 0 ; 
		# foreach my $rate2 (@input_rates_arr) {
			# next if $cnt1 == $cnt2 ;
			# if ((($input_valid_from_arr[$cnt2] <= $saved_valid_from[$cnt1] && $saved_valid_from[$cnt1] <= $input_valid_to_arr[$cnt2]) || ($input_valid_from_arr[$cnt2] <= $saved_valid_to[$cnt1] && $saved_valid_to[$cnt1] <= $input_valid_to_arr[$cnt2])) && $saved_full_half_day[$cnt1] eq $input_full_half_day_arr[$cnt2]) {
				# $alert = &common_min_alert('warning',"YOUR INPUT RATE $rates[$cnt1] FOR THE PERIOD '$valid_from[$cnt1]' TO '$valid_to[$cnt1]' OVERLAPS WITH THE RATE $rates[$cnt2] FOR THE PERIOD '$valid_from[$cnt2]' TO '$valid_to[$cnt2]'!",'ok') ;
				# %col_name = ();
				# $i{id} = '' if $iaction eq 'save' ;
				# foreach (keys %i) { $db{$table}{''}{$_} = $i{$_} ; }
				# # $db{$table}{''}{}
				# &common_min_add_screen ;
				# &common_min_screen1 ;
			# }
			# $cnt2++ ;
		# }
		# $cnt1++ ;
	# }
	
} #------------------------------------------------------------------------------------------

sub insert {

	&add_db_fields ;

	# $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;

	&process_rates ;

	$i{id} = &db_min_get_max($table,'id') ; 

	&db_min_insert($table) ;
	
	# exit ;

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

sub update {

	unless ($i{id}) { 
		$error = qq(NO ID) ; 
		return ; 
	}

	&edit_db_fields ;

	unless ($i{excl_from_expenses}) { $i{excl_from_expenses} = '0' ; }	
	# $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
	$i{active} = '0' unless $i{active} ;	
	
	&process_rates ;
	
	$ignore{id} = 1 ;
	
	&db_min_upd($table,"id='$i{id}'") ;

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

sub process_rates {
	
	# &db_min_ro($table,'1,valid_from,valid_to,rates,full_half_day',"id='$i{id}'",'','') if $i{id} ; 
	&db_min_ro($table,'1,rates,full_half_day',"id='$i{id}'",'','') if $i{id} ; 
	
	our %ii = () ;

	# my @valid_from 		= split(/\;/,$db{$table}{1}{valid_from}) ; 
	# my @valid_to 		= split(/\;/,$db{$table}{1}{valid_to}) ; 
	my @rates 			= split(/\;/,$db{$table}{1}{rates}) ; 
	my @full_half_day 	= split(/\;/,$db{$table}{1}{full_half_day}) ; 
	
	my $cnt_rate = 0 ;
	
	foreach (@rates) {
		
		$cnt_rate++ ;
		
		$ignore{"selected_$cnt_rate\_full_half_day"} = 1 ;
		# $ignore{"valid_from_$cnt_rate"} = 1 ;
		# $ignore{"valid_to_$cnt_rate"} = 1 ;
		$ignore{"rates_$cnt_rate"} = 1 ;
		$ignore{"full_half_day_$cnt_rate"} = 1 ;
		$ignore{"full_half_day_readonly_$cnt_rate"} = 1 ;
		
		# if ($i{"valid_from_$cnt_rate"} && $i{"valid_from_$cnt_rate"} =~ /^\d{4}-\d{2}-\d{2}$/ && $i{"valid_to_$cnt_rate"} && $i{"valid_to_$cnt_rate"} =~ /^\d{4}-\d{2}-\d{2}$/ && $i{"rates_$cnt_rate"}) {
		if ($i{"rates_$cnt_rate"}) {
			
			# &build_rates_fields("valid_from","$cnt_rate") ;
			# &build_rates_fields("valid_to","$cnt_rate") ;
			&build_rates_fields("rates","$cnt_rate") ;
			&build_rates_fields("full_half_day","$cnt_rate") ;			
		
		}
	}
	
	$ignore{"selected_add_full_half_day"} = 1 ;
	# $ignore{"valid_from_add"} = 1 ;
	# $ignore{"valid_to_add"} = 1 ;
	$ignore{"rates_add"} = 1 ;
	$ignore{"full_half_day_add"} = 1 ;
	
	# if ($i{valid_from_add} && $i{valid_from_add} =~ /^\d{4}-\d{2}-\d{2}$/ && $i{valid_to_add} && $i{valid_to_add} =~ /^\d{4}-\d{2}-\d{2}$/ && $i{rates_add}) {
	if ($i{rates_add}) {
		
		# &build_rates_fields("valid_from","add") ;
		# &build_rates_fields("valid_to","add") ;
		&build_rates_fields("rates","add") ;
		&build_rates_fields("full_half_day","add") ;
		%ii = () ;
	
	}
	
} #------------------------------------------------------------------------------------------

sub build_rates_fields {
	
	my ($field_name,$row_cnt) = @_ ; 
	
	# $ii{$field_name}	= qq~$db{$table}{1}{$field_name}~ ;
	$ii{$field_name}	.= ';' if $ii{$field_name} ;
	$ii{$field_name}	.= qq~$i{"$field_name\_$row_cnt"}~ ;
	$i{$field_name}		= $ii{$field_name} ; 
	
} #------------------------------------------------------------------------------------------

sub list_screen {
	
	# &db_min_ro('event_quotes','DISTINCT(type)','','','') ;

	# foreach my $id (keys %{$db{event_quotes}}) {
		# $type_id_used{$id} = 1 ;
	# }
	
	my %seen_event_item_costing  = () ; 
	my $delete_button = "" ;
	# my $sql_columns = " id" ; 
	# for (1 .. 15 ){
		 # $sql_columns .= ", item_$_\_costing_event" ; 
		 # $sql_columns .= ", description_$_\_workings_event" ; 
	# }
	
	# &db_min_ro('event_quotes',$sql_columns,'','','') ; 
 
	&db_min_ro('event_quotes_min','id,item_costing_event,description_workings_event',"",, '', '' );
	
	my @item_cost = () ;  
	my @des_work = () ;

	foreach my $id (keys %{$db{event_quotes_min}}) {
		
		@item_cost = split(";",$db{event_quotes_min}{$id}{item_costing_event}) ;
		@des_work = split(";",$db{event_quotes_min}{$id}{description_workings_event}) ;
		foreach (@item_cost) {
			next if $seen_event_item_costing{$_} ;
			next if not $_ ;
			$seen_event_item_costing{$_} = 1; 
		}
		
		foreach (@des_work){
			next if $seen_event_item_costing{$_} ;
			next if not $_ ;
			$seen_event_item_costing{$_} = 1 ; 
		}
		
		# for (1 .. 15) {
			# next if $seen_event_item_costing{$db{'event_quotes'}{$id}{"item_$_\_costing_event"}} ;
			# next if not $db{'event_quotes'}{$id}{"item_$_\_costing_event"} ;
			# $seen_event_item_costing{$db{'event_quotes'}{$id}{"item_$_\_costing_event"}} = 1; 

		# }
		# for (1 .. 15) {
			# next if $seen_event_item_costing{$db{'event_quotes'}{$id}{"description_$_\_workings_event"}} ;
			# next if not $db{'event_quotes'}{$id}{"description_$_\_workings_event"} ;
			# $seen_event_item_costing{$db{'event_quotes'}{$id}{"description_$_\_workings_event"}} = 1 ; 
		# }
	}

	&db_min_ro($table,'*','','id','') ;
	
	my $excl = "" ;
	
	our @sql_col_display = ("id","name","excl_from_expenses","active","rate","") ; 
	
	our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; 
	 
	foreach my $id (keys %{$db{$table}}) {
		
		$seen_event_item_costing{$id} = 1 if $db{$table}{$id}{name} eq 'Temp Support' || $db{$table}{$id}{name} eq 'Troubleshoot Monitor Allocations' || $db{$table}{$id}{name} eq 'Temp Calibrator Allocations' || $db{$table}{$id}{name} eq 'Monitor Allocations' || $db{$table}{$id}{name} eq 'Logistics Shipments' ;
		
		# next if $id ne '30' ;
		
		# if ($type_id_used{$id}) { 
			# $edit_butt = qq~&nbsp;<a class="btn btn-default btn-xs" href="#" title="In system use!" data-toggle="tooltip"><i class="glyphicon glyphicon-edit icon-white"></i></a>~ ;   
			# $del_butt  = qq~&nbsp;<a class="btn btn-default btn-xs" href="#" title="In system use!" data-toggle="tooltip"><i class="glyphicon glyphicon-trash icon-white"></i></a>~ ;  
		# }
		# $excl = qq~<span style="display:none;"></span><span class="label label-success"><i $tooltip class="glyphicon glyphicon-ok"></i></span>~ ; 
		# $excl = qq~<span style="display:none;"></span><span class="label label-danger"><i $tooltip class="glyphicon glyphicon-remove"></i></span>~ if not $db{$table}{$id}{excl_from_expenses} ; 
		
		$print_tbody .= qq~<tr id="$id">~ ;
		
		# my @arr_valid_from 		= split(/\;/,$db{$table}{$id}{valid_from}) ;
		# my @arr_valid_to 		= split(/\;/,$db{$table}{$id}{valid_to}) ;
		my @arr_rates 			= split(/\;/,$db{$table}{$id}{rates}) ;
		my @arr_full_half_day	= split(/\;/,$db{$table}{$id}{full_half_day}) ;
		
		my $row_cnt = 0 ;
		
		my %default_val = () ;

		foreach (@arr_rates) {
			
			# my $valid_from 		= $arr_valid_from[$row_cnt] ;
			# my $valid_to 		= $arr_valid_to[$row_cnt] ;
			my $rate 			= $_ ;
			my $full_half_day	= $arr_full_half_day[$row_cnt] ;
			$row_cnt++ ;
			# $valid_from =~ s/\-//g ;
			# $valid_to   =~ s/\-//g ;
			# if ($valid_from >= $now_ccyymmdd && $now_ccyymmdd <= $valid_to) {
				# $default_val{$full_half_day}{valid_from} = $valid_from ;
				# $default_val{$full_half_day}{valid_to}   = $valid_to ;
				$default_val{$full_half_day}{rates}      = $rate ;
			# }
			
			$default_val{$full_half_day}{rates} = $rate if $rate && $db{$table}{$id}{rates} !~ /;/ && !$valid_from && !$valid_to ;
			
		}
		
		foreach my $col (@sql_col_display) {
			
			$val = $db{$table}{$id}{$col} ;
			my $nowrap = "" ;
			my $align = qq~ class="dt-center"~ ;
			
			if ($col eq "id") {
				$align = qq~ class="dt-left"~ ; 
			} elsif ($col eq "name") {
				$align = qq~ class="dt-left"~ ; 
			} elsif ($col eq "excl_from_expenses") { 
				$val = qq~<span style="display:none;"></span>~ ;
				$val .= ($db{$table}{$id}{excl_from_expenses}) ? qq~<span class="label label-success"><i $tooltip class="glyphicon glyphicon-ok"></i></span>~ : qq~<span class="label label-danger"><i $tooltip class="glyphicon glyphicon-remove"></i></span>~ ;
			} 
			# elsif ($col eq "valid_from") { 
				
				# # print "\n valid_from ful : $default_val{1}{valid_from}" ;
				# # print "\n valid_from half : $default_val{2}{valid_from}" ;
				
				# $default_val{1}{valid_from} = ($default_val{1}{valid_from}) ? substr($default_val{1}{valid_from},0,4) . '-' . substr($default_val{1}{valid_from},4,2) . '-' . substr($default_val{1}{valid_from},6,2) : "" ;
				# $default_val{2}{valid_from} = ($default_val{2}{valid_from}) ? substr($default_val{2}{valid_from},0,4) . '-' . substr($default_val{2}{valid_from},4,2) . '-' . substr($default_val{2}{valid_from},6,2) : "" ;
				# if ($default_val{1}{valid_from} && $default_val{2}{valid_from}) {
					# my $val1 = &common_min_date_as_string($default_val{1}{valid_from}) ;				
					# my $val2 = &common_min_date_as_string($default_val{2}{valid_from}) ;				
					# $val = "Full Day : $val1<br>Half Day : $val2" ;
				# } else {
					# $val = ($default_val{1}{valid_from}) ? $default_val{1}{valid_from} : $default_val{2}{valid_from} ;
					# $val = "2000-01-01" unless $db{$table}{$id}{valid_from} ;
					# $val = &common_min_date_as_string($val) ;					
				# } 
			# } elsif ($col eq "valid_to") {
				# $default_val{1}{valid_to} = ($default_val{1}{valid_to}) ? substr($default_val{1}{valid_to},0,4) . '-' . substr($default_val{1}{valid_to},4,2) . '-' . substr($default_val{1}{valid_to},6,2) : "" ;
				# $default_val{2}{valid_to} = ($default_val{2}{valid_to}) ? substr($default_val{2}{valid_to},0,4) . '-' . substr($default_val{2}{valid_to},4,2) . '-' . substr($default_val{2}{valid_to},6,2) : "" ;
				# if ($default_val{1}{valid_to} && $default_val{2}{valid_to}) {
					# my $val1 = &common_min_date_as_string($default_val{1}{valid_to}) ;				
					# my $val2 = &common_min_date_as_string($default_val{2}{valid_to}) ;				
					# $val = "Full Day : $val1<br>Half Day : $val2" ;
				# } else {
					# $val = ($default_val{1}{valid_to}) ? $default_val{1}{valid_to} : $default_val{2}{valid_to} ;
					# $val = "2000-01-01" unless $db{$table}{$id}{valid_to} ;
					# $val = &common_min_date_as_string($val) ;					
				# } 
			# } 
			elsif ($col eq "active") { 
				$val = ($db{$table}{$id}{active}) ? qq~<span class="label label-success"><i $tooltip class="glyphicon glyphicon-ok"></i></span>~ : qq~<span class="label label-danger"><i $tooltip class="glyphicon glyphicon-remove"></i></span>~ ;
			} elsif ($col eq "rate") {
				if ($default_val{1}{rates} && $default_val{2}{rates}) {
					my $val1 = $default_val{1}{rates} ;				
					my $val2 = $default_val{2}{rates} ;
					$val = "Full Day : $val1<br>Half Day : $val2" ;
				} else {
					$val = ($default_val{3}{rates}) ? $default_val{3}{rates} : ($default_val{1}{rates}) ? $default_val{1}{rates} : $default_val{2}{rates} ;
				}
				
			} elsif ($col eq '') {
				$align = qq~ class="dt-left"~ ; 
				my $edit_butt = '' ; 
				my $del_butt  = '' ;	
				if ($useropts{super}{$username}) { 
					$edit_butt = qq~&nbsp;<a class="btn btn-info btn-xs" href="javascript:editMinItem('$db{$table}{$id}{id}');"><i class="glyphicon glyphicon-edit icon-white"></i></a>~ ; 
				}
				if ($useropts{boss}{$username} or $useropts{super}{$username}) { 
					$del_butt  = qq~&nbsp;<a class="btn btn-danger btn-xs" href="javascript:deleteMinItem('$db{$table}{$id}{name}','$db{$table}{$id}{id}')"><i class="glyphicon glyphicon-trash icon-white"></i></a>~ if not $seen_event_item_costing{$id}; 
					$del_butt  = qq~&nbsp;<a class="btn btn-default btn-xs" href="#" title data-toggle="tooltip" data-original-title="In system use!"><i class="glyphicon glyphicon-trash icon-white"></i></a>~ if $seen_event_item_costing{$id}; 
				}
				
				$edit_butt = qq~&nbsp;<a class="btn btn-default btn-xs" href="#" title="This event cost item has been retired!" data-toggle="tooltip"><i class="glyphicon glyphicon-edit icon-white"></i></a>~ if $id == 11 || $id == 18 || $id == 10 || $id == 12 || $id == 19 || $id == 20 ;
				$del_butt  = qq~&nbsp;<a class="btn btn-default btn-xs" href="#" title="This event cost item has been retired!" data-toggle="tooltip"><i class="glyphicon glyphicon-trash icon-white"></i></a>~ if $id == 11 || $id == 18 || $id == 10 || $id == 12 || $id == 19 || $id == 20 ;		
				
				$val = qq~$edit_butt$del_butt~ ;
			}
			$print_tbody .= qq~<td $nowrap $align>$val</td>~ ;	
		}
		$print_tbody .= qq~</tr>~ ;
	}

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

sub add_db_fields {
		
	# &sort_fields;
	&hidden_db_fields;
	# $ignore{id} = 1 ;

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

sub edit_db_fields {
		
	# &sort_fields;	
	&hidden_db_fields;
	$hidden{id} = 1 ; # 1 = bypass for db update

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

sub hidden_db_fields {
	
	$ignore{iaction}               = 1 ;
	# $readonly{name}              = 'READONLY' ;
	$required{name}                = 1 ;
	$checkbox{excl_from_expenses}  = 1 ;
	$checkbox{active}  = 1 ;
	# $required{description}       = 1 ;
	
	# if (!$i{rate} || !$i{valid_from} || !$i{valid_to}) {
		# $ignore{valid_from} = 1 ;
		# $ignore{valid_to} = 1 ;
		# $ignore{rate} = 1 ;
	# }
	
	&sort_fields ;
		
} #------------------------------------------------------------------------------------------

sub sort_fields {
	
	our %sort_field = () ;
	$sort_field{1}  = 'name' ;
	$sort_field{2}  = 'excl_from_expenses' ;
	$sort_field{3}  = 'active' ;

	# $sort_field{4}  = 'valid_from' ;
	# $sort_field{5}  = 'valid_to' ;
	# $sort_field{6}  = 'rate' ;
	
	# $checkbox{active} = 1 ;
	# $checkbox{excl_from_expenses} = 1 ;
	# $datepicker{valid_from} = 1 ;
	# $datepicker{valid_to} = 1 ;
	
	# $db{$table}{$i{id}}{valid_from} = "2000-01-01" ;
	# $db{$table}{$i{id}}{valid_to} = "2050-01-01" ;
	
	# $required{name} = 1 ;
	
} #-------------------------------------------------------------------------------

sub add_screen {

	&sort_fields ;

	# called from common_add_screen
	&select_opts ;
	
	&build_boxes ;
	
} #------------------------------------------------------------------------------------------

sub edit_screen {
	
	&select_opts ;

	&build_boxes ;
	
} #------------------------------------------------------------------------------------------

sub build_boxes {
	
	our ($lcol,$fcol) = &common_min_columns() ;

	$add_form_fields = '' ;
	
	$print_box_content_rows .= &common_min_forms_start($table,$skip) ;
	
	$print_box_content_rows .= qq~<input name='id' value='$i{id}' style='display:none;'>~ if $i{id} ;
	
	$fcol = 2 ;
	
	$db{$table}{''}{name} 				= $db{$table}{$i{id}}{name}               ;
	$db{$table}{''}{active} 			= $db{$table}{$i{id}}{active}             ;
	$db{$table}{''}{excl_from_expenses}	= $db{$table}{$i{id}}{excl_from_expenses} ;
	
	foreach my $cnt (sort {$a <=> $b} keys %sort_field) {
		$col   = $sort_field{$cnt} ;
		$add_form_fields .= &common_min_forms_loop($iid,$table,$ignore_colpart) ;    
	}
	
				# <div class='col-md-2'>
				# <label class="control-label">Valid&nbsp;From</label>
			# </div>
			# <div class='col-md-2'>
				# <label class='control-label'>Valid&nbsp;To</label>
			# </div>
	
	$add_form_fields .= qq~
		<div class='row'>
			<div class='col-md-2'>
				<label class='control-label'>Full/Half&nbsp;Day</label>
			</div>			
			<div class='col-md-2'>
				<label class='control-label'>Rates</label>
			</div>
		</div>
	~ ;

	$fcol = 2 ; my $row_cnt = 0 ;

	my @rates 			= split(/\;/,$db{$table}{$i{id}}{rates}) ;
	# my @valid_from 		= split(/\;/,$db{$table}{$i{id}}{valid_from}) ;
	# my @valid_to 		= split(/\;/,$db{$table}{$i{id}}{valid_to}) ;
	my @full_half_day 	= split(/\;/,$db{$table}{$i{id}}{full_half_day}) ;
	
	my %full_half_day_hash = (1 => "&nbsp;&nbsp;Full&nbsp;Day", 2 => "&nbsp;&nbsp;Half&nbsp;Day", 3 => "&nbsp;&nbsp;N/A") ; my @selected_radios = () ; my @rate_ids = () ; my $orig_rates = qq~~ ; my @dates_arr = () ; my $def_val = qq~~ ;
	
	my %full_half_day_is_used = () ;  my %full_half_day_is_used_not_editable = () ;  
	
	foreach (@rates) {
		
		$row_cnt++ ;
		$add_form_fields .= qq~<div class='row'>~ ;
 
		if ($rates[$row_cnt - 1] && $rate_is_used{$full_half_day[$row_cnt - 1]}{$rates[$row_cnt - 1]}) {
			$readonly{"valid_from_$row_cnt"} 	= "READONLY" ; 
			$readonly{"valid_to_$row_cnt"} 		= "READONLY" ; 
			$readonly{"rates_$row_cnt"}			= "READONLY" ; 
		}
		
		# $add_form_fields .= (!$readonly{"valid_from_$row_cnt"}) ? &common_min_form_datepicker_col("valid_from_$row_cnt",$valid_from[$row_cnt - 1]) : &common_min_form_input_col("valid_from_$row_cnt",$valid_from[$row_cnt - 1]) ;
		# $add_form_fields .= (!$readonly{"valid_to_$row_cnt"}) ? &common_min_form_datepicker_col("valid_to_$row_cnt",$valid_to[$row_cnt - 1]) : &common_min_form_input_col("valid_to_$row_cnt",$valid_to[$row_cnt - 1]) ;
		
		# push @dates_arr,"#datepickValid_to_$row_cnt" unless $readonly{"valid_to_$row_cnt"} ;
		# push @dates_arr,"#datepickerValid_to_$row_cnt" unless $readonly{"valid_to_$row_cnt"} ;
		# push @dates_arr,"#datepickValid_from_$row_cnt" unless $readonly{"valid_from_$row_cnt"} ;
		# push @dates_arr,"#datepickerValid_from_$row_cnt" unless $readonly{"valid_from_$row_cnt"} ;
		
		if (($_ && $rate_is_used{$full_half_day[$row_cnt - 1]}{$_}) || $i{"full_half_day_readonly_$row_cnt"}) {
			
			$add_form_fields .= qq~
				<div class='fieldname col-md-2' align="left">
					<label class='control-label'>$full_half_day_hash{$full_half_day[$row_cnt-1]}</label>
					<input name='full_half_day_$row_cnt' style='display:none;' value='$full_half_day[$row_cnt-1]'>
					<input name='full_half_day_readonly_$row_cnt' style='display:none;' value='1'>
				</div>
			~ ;	
			$readonly{"rates_$row_cnt"} 			= "READONLY" ; 
			$full_half_day_is_used{full} = 1 if $full_half_day[$row_cnt - 1] eq '1' ; 
			$full_half_day_is_used{half} = 1 if $full_half_day[$row_cnt - 1] eq '2' ; 			
			$full_half_day_is_used{na} = 1 if $full_half_day[$row_cnt - 1] eq '3' ; 			
			$full_half_day_is_used_not_editable{full} = 1 if $full_half_day[$row_cnt - 1] eq '1' ; 
			$full_half_day_is_used_not_editable{half} = 1 if $full_half_day[$row_cnt - 1] eq '2' ; 
			
		} else {
			$add_form_fields .= qq~<div class="col-md-2">~ ;
			$radio_opts{"full_half_day"} = "Full+Half+N/A" ;
			$lcol = 2 ; $fcol = 2 ;
			$def_val = ($i{"full_half_day_$row_cnt"}) ? $i{"full_half_day_$row_cnt"} : $full_half_day[$row_cnt-1] ;
			$add_form_fields .= &common_min_form_radio_col("full_half_day",$def_val,'',1,'','','',$row_cnt) ;
			$lcol = 2 ; $fcol = 2 ;
			$add_form_fields .= qq~</div>~ ;
			push @selected_radios, "#radio_$row_cnt\_$def_val" if $def_val ;
			$full_half_day_is_used{full} = 1 if $def_val eq '1' ; 
			$full_half_day_is_used{half} = 1 if $def_val eq '2' ; 
			$full_half_day_is_used{na}	 = 1 if $def_val eq '3' ;
		}
		
		$def_val = ($i{"rates_$row_cnt"}) ? $i{"rates_$row_cnt"} : $rates[$row_cnt-1] ;
		$add_form_fields .= &common_min_form_input_col("rates_$row_cnt",$def_val) ;
		push @rate_ids,"#inputRates_$row_cnt" ;
		$add_form_fields .= qq~</div>~ ;	
		$orig_rates .= qq~"inputRates_$row_cnt":$rates[$row_cnt - 1],~ ;
	}
	
	$orig_rates .= qq~"inputRates_add":""~ ;

	if (!$error && !$alert) {
		$i{full_half_day_add} = '' ;
		$i{rates_add} = '' ;
		$i{full_half_day_add} = '2' if $full_half_day_is_used{full} ;
	}
	
	if ((!$full_half_day_is_used{full} || !$full_half_day_is_used{half}) && !$full_half_day_is_used{na} && $row_cnt < 2) {

		$preferred_title{valid_from_add} = "Add Valid From" ;
		$preferred_title{valid_to_add} = "Add Valid To" ;
		$preferred_title{rates_add} = "Add Rate" ;
		
		$add_form_fields .= qq~<div class='row'>~ ;
		# $add_form_fields .= &common_min_form_datepicker_col("valid_from_add",$i{valid_from_add}) ;
		# $add_form_fields .= &common_min_form_datepicker_col("valid_to_add",$i{valid_to_add}) ;
		$radio_opts{"full_half_day"} = "&nbspFull+&nbsp;Half+&nbsp;N/A" ;
		$add_form_fields .= qq~<div class="col-md-2">~ ;
		$lcol = 2 ; $fcol = 2 ;
		$add_form_fields .= &common_min_form_radio_col("full_half_day",$i{full_half_day_add},'',1,'','','','add') ;
		push @selected_radios, "#radio_add_$i{full_half_day_add}" if $i{full_half_day_add} ;
		$lcol = 2 ; $fcol = 2 ;
		$add_form_fields .= qq~</div>~ ;		
		$add_form_fields .= &common_min_form_input_col("rates_add",$i{rates_add}) ;
		push @rate_ids,"#inputRates_add" ;
		$add_form_fields .= qq~</div>~ ;		
	}
	
	my $save_action = ($i{id}) ? 'update' : 'save' ;

	$add_form_fields .= &common_min_forms_end($iid,$table,$save_action,$skip) ;
	
	my $add_edit = ucfirst $iaction ; 
	
	$print_box_content_rows .= &common_min_box_top('',"&nbsp;$add_edit&nbsp;:&nbsp;$i{id}",$box_right_bg) ; 
	$print_box_content_rows .= $add_form_fields ;
	$print_box_content_rows .= &common_min_box_foot ;
	
	push @selected_radios, "#radio_add_1" ;
	
	my $selected_radios_str = join(",",@selected_radios) ; 
	my $rate_ids_str	 	= join(",",@rate_ids) ; 
	my $dates_str			= join(",",@dates_arr) ;

	$trigger_jquery_raw .= qq~
	
		\$("$dates_str").change( function () {
			console.log("date : "+this.id) ; 
		}) ;
	
		// function isDecimal(value) {
			// // If it's a string, make sure it's a clean numeric string
			// if (typeof value === 'string') {
				// // This regex matches valid decimals (including optional sign and leading zero)
				// const trimmed = value.trim();
				// const decimalRegex = /^[+-]?(\d*\.\d+|\d+\.\d*)$/;
				// if (!decimalRegex.test(trimmed)) {
				  // return false;
				// } else {
					// return true ;
				// }
			// }
		// }
		
		\$("$selected_radios_str").prop("checked",true);
		
		let orig_input_rate_add = {$orig_rates} ;
		
		\$("$rate_ids_str").change( function () {
			
			let val = \$("#"+this.id).val() ;
			
			if (val) {
				val = parseFloat(val) ;
				val = val.toFixed(2) ;				
			}
  
			let is_decimal = 1 ; // Show val is a decimal?
			
			if (is_decimal) {
				\$("#"+this.id).val(val) ;
				orig_input_rate_add[this.id] = \$("#"+this.id).val() ;
			} else {
				\$("#"+this.id).val(orig_input_rate_add[this.id]) ;
			}

			// if (isDecimal(\$("#"+this.id).val())) {
				// console.log("isDecimal") ;
			// } else {
				// console.log("isNotDecimal") ;
			// }
				
			// \$("#"+this.id).val(orig_input_rate_add) ;

			// orig_input_rate_add[this.id] = \$("#"+this.id).val() ;
			
			// console.log("2 . orig_input_rate_add : "+orig_input_rate_add) ; 
			
		}) ;
		
	~ ;
	
} #------------------------------------------------------------------------------------------

sub select_opts {
	
	$readonly{name} = "READONLY" if $db{$table}{$i{id}}{name} eq 'Temp Support' || $db{$table}{$i{id}}{name} eq 'Temp Calibrator Allocations' || $db{$table}{$i{id}}{name} eq 'Monitor Allocations' || $db{$table}{$i{id}}{name} eq 'Logistics Shipments' ;
	
	our %rate_is_used = () ;
	
	$db{$table}{''}{active} = 1 ; 
	
	$required{name}                = 1 ;
	$checkbox{excl_from_expenses}  = 1 ;
	$checkbox{active}  = 1 ;
	&sort_fields ;
	
	# if ($iaction eq 'edit' && $db{$table}{$i{id}}{rates} && $db{$table}{$i{id}}{valid_from} && $db{$table}{$i{id}}{valid_to} && $db{$table}{$i{id}}{full_half_day}) {
	if ($iaction eq 'edit' && $db{$table}{$i{id}}{rates} && $db{$table}{$i{id}}{full_half_day}) {
		
		&db_min_ro('event_quotes','id,date_from',"",'','') ; 
		&db_min_ro('event_quotes_min','id,item_costing_event,usd_amnt_costing_event',"",'','') ; 
		
		my $valid_from_str 	= $db{$table}{$i{id}}{valid_from} ; 
		my $valid_to_str 	= $db{$table}{$i{id}}{valid_to} ; 
		
		$valid_from_str 	=~ s/\-//g ; 
		$valid_to_str 		=~ s/\-//g ; 
		
		my @full_half_day	= split(/\;/,$db{$table}{$i{id}}{full_half_day}) ; 
		my @rates 			= split(/\;/,$db{$table}{$i{id}}{rates}) ; 
		# my @valid_from 		= split(/\;/,$valid_from_str) ; 
		# my @valid_to 		= split(/\;/,$valid_to_str) ; 
		
		my $cost_id = $i{id} ; 
		
		foreach my $id (keys %{$db{event_quotes}}) {
			
			if ($db{event_quotes_min}{$id}{item_costing_event} =~ /\b$cost_id\b/) {
				
				my $date = $db{event_quotes}{$id}{date_from} ; $date =~ s/\-//g ; $date = int($date) ;
				my $date_cnt = 0 ;
				
				my @saved_item_arr = split(/\;/,$db{event_quotes_min}{$id}{item_costing_event}) ; 
				my @saved_rate_arr = split(/\;/,$db{event_quotes_min}{$id}{usd_amnt_costing_event}) ; 
				
				# foreach my $date_valid_from (@valid_from) {
					
					# next unless $date_valid_from ; 
					# if ($valid_from[$date_cnt] <= $date && $date <= $valid_to[$date_cnt]) { 
						my $save_cnt = 0 ; 
						foreach my $item_id (@saved_item_arr) { 
							if ($item_id eq $cost_id && $saved_rate_arr[$save_cnt] eq $rates[$date_cnt]) {
								# $rate_is_used{$full_half_day[$date_cnt]}{$rates[$date_cnt]} = 1 ; 
							}
							$save_cnt++ ;
						}
					# }
					# $date_cnt++ ;
				# }
				
				# my @costs = split(/\;/,$db{event_quotes_min}{$id}{description_costing_event}) ; 
				# my @anmts = split(/\;/,$db{event_quotes_min}{$id}{amount_usd_costing_event}) ; 
				
				# my $cost_cnt = 0 ; 
				
				# foreach (@costs) {
					
					# next unless $_ eq $cost_id ;
					
				# }
			}
		}
	}
	
	# $required{based_in} = 1 ;
	# $select{based_in} = 1 ;
	# $opts{based_in} = qq(<option value="JNB" $selected{based_in}{'JNB'}>Johannesburg</option><option value="CPT" $selected{based_in}{'CPT'}>Cape Town</option>) ;

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

sub thead {
	
	&common_min_thead ;
	# $print_thead = qq(<THEAD><TR><TH>ID</TH><TH>NAME</TH><TH>EXCLUDED FROM EXPENSES</TH><TH>&nbsp;</TH></TR></THEAD>) ;
		
} #-------------------------------------------------------------------------------

sub page_opts {

	our $glyphicon = 'facetime-video' ;
	our $lcpage    = 'event-cost-item' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ;
	our $table     = 'event_cost_items' ;
	&common_min_add_extras ;

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

use common ;
use today ;

1;