#!/usr/bin/perl

BEGIN { use lib '/usr/home/cfg' ; require push_inc ; }
    
use CGI qw( :standard );
use CGI::Carp qw(fatalsToBrowser);
    
require cfg ;

print header;   # CGI.pm method

# unless ($username eq 'handre'or  $username eq 'rory') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; }

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

use Fcntl qw(:flock);
use File::Copy;
use File::Basename;
use Date::Calc qw(:all);
use Excel::Writer::XLSX ;
use LWP::Simple qw($ua get);
use JSON ;

&today;

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

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

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

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

# our $redirtype = 'search' ;

# our $testing = 1 ;
# our $debug   = 1 ;
# &common_debug("glod_user_level = $glod_user_level [$usertype]") ;

# unless ($username eq 'rory') { print ">>>> DEVELOPMENT IN PROGRESS <<<<" ; exit ; }

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

# my $string = '3;;1;u16;a;;1;;s;s;;|5;;1;u17;a;;1;;s;s;;|5;;1;open;a;;1;;p;s;;';

# print "\n MAINTENANCE IN PROGRESS !" ;
# exit if $username ne 'handre'; 

if ($is_operator && $glod_user_level == 2) { $glod_user_level = 3 ; } # upgrade operators level 2&3 to 3&4

our $nr_of_system_names_and_clubs = 15 ; our @all_select_ids = () ; our $minify_jquery = 1 ;
 
&db_open_ro ;
	$db_ignore_open_close = 1 ;
		
		&page_opts ;
		
		if ($iaction eq 'filter' || $iaction eq 'search' || $iaction eq 'report') {
			our $srchscr = 1 ;
			our $savjqy  = 0 ; 
		}

		#------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		our @fixture_headers 	= ("Fixture Date/Time From","Sport","Age Group","Team","Home Team","HT Colour","Away Team","Coding Type","Footage Type");
		our @analytics_headers 	= ("Fixture Date/Time From","Sport","Age Group","Team","Home Team","HT Colour","Away Team","Coding Type","Footage Type","Service Type");
		our %service_types 		= (1 => "Live Coding",2 => "Post Coding 12 hrs",3 => "Post Coding 24 hrs") ;
		our %coding_type 		= ("s" => "Standard","p" => "Premium") ; 
		our %footage_type 		= ("s" => "SSS","r" => "Raw") ;
		
		if ($iaction eq 'add') {
			&add_screen ; 
			&common_min_screen1 ; 
		} elsif ($iaction eq 'edit') {
			&common_min_load_params ; 
			&edit_screen ; 
			&common_min_screen1 ; 
		} elsif ($iaction eq 'save') {
			&common_min_load_params ; 
			&insert ; 
			# &log_changes ;
			&edit_or_list ; 
		} elsif ($iaction eq 'update') {  	
			&common_min_load_params ; 
			&update ; 
			# &log_changes ; 
			&edit_or_list ; 
		} elsif ($iaction eq 'copy') { 
			&common_min_load_params ;
			&duplicate ; 
			&edit_screen ; 
			&common_min_screen1 ; 
		} elsif ($iaction eq 'delete') {    
			&common_min_load_params ; 
			&report_ifields ; 
			&delete ; 
			&common_min_screen2 ; 
		}
		
		&common_min_action ; 
		
	$db_ignore_open_close = 0 ; 
&db_close_conn ; 

exit ;

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

sub edit_or_list {
	
	exit if $testing && substr($username,0,4) eq 'rory' ; 

    &edit_screen ;    
    &common_min_screen1;
           
} #------------------------------------------------------------------------------------------

sub process_fixtures_tab {
	
	my ($id) = @_ ;
	
	&db_min_ro($table,"id,fixtures_saved_values,analytics_saved_values","id='$id'",'','') if $id ; 
	
	$i{fixtures_saved_values} = qq~~ ;
	
	my $suffix = "fixtures" ;
	
	my @changed_field_keys = ("age_group","team","home_team","ht_colour","away_team","coding_type","footage_type") ; 
	
	my @fixtures_saved_values_split = ($id) ? split(/\|/,$db{$table}{$id}{fixtures_saved_values}) : () ;
	
	for my $row_nr (1 .. 100) {
		
		# last if $row_nr > $i{total_fixtures} ;
		
		my $input_vals = qq~~ ;
		
		my @fixtures_saved_values_split_2 = ($id) ? split(/\;/,$fixtures_saved_values_split[$row_nr - 1]) : () ;
		
		foreach (@changed_field_keys) {
			$input_vals .= qq~;$i{"$_\_$suffix\_$row_nr"}~ ;
			$ignore{"$_\_$suffix\_$row_nr"} = 1 ;  
		}
		$input_vals .= qq~;$fixtures_saved_values_split_2[9];$fixtures_saved_values_split_2[10]~ ;
		
		my $changed_fixtures_date_field = "changed_fixtures_date_$row_nr" ; 
		
		my $date_field = "start_date_time_$suffix\_$row_nr" ;
		
		my $changed_sport_field = "sport_fixtures_$row_nr" ; 
		
		if ($input_vals =~ /[a-zA-Z]/ || $input_vals =~ /(\d+)/g || $i{$changed_sport_field} || $i{$changed_fixtures_date_field}) {
			$i{fixtures_saved_values} .= ($i{$changed_fixtures_date_field}) ? qq~$i{$date_field};$i{$changed_sport_field}~ : qq~;$i{$changed_sport_field}~ ;
			$i{fixtures_saved_values} .= qq~$input_vals~ ;
		}
		
		$i{fixtures_saved_values} .= qq~|~ ; 
		
		$ignore{"start_date_time_$suffix\_$row_nr"} = 1 ;
		$ignore{"readonly_sport_$suffix\_$row_nr"} = 1 ;
		$ignore{"sport_$suffix\_$row_nr"} = 1 ;
		
	}
	# 1;;;u14;a;;1;;s;s|2;;;u14;a;;1;;s;s|3;;2;u15;a;;1;;s;s|4;;1;u15;a;;1;;s;s|5;;2;u16;a;;1;;s;s|6;;1;u16;a;;1;;s;s|7;;2;open;b;;1;;s;s|8;;1;open;b;;1;;s;s|9;;2;open;a;;1;;p;s|10;;1;open;a;;1;;p;s
	# 1;;;u14;a;;1;;s;s;;|2;;;u14;a;;1;;s;s;;|3;;2;u15;a;;1;;s;s;;|4;;1;u15;a;;1;;s;s;;|5;;2;u16;a;;1;;s;s;;|6;;1;u16;a;;1;;s;s;;|7;;2;open;b;;1;;s;s;;|8;;1;open;b;;1;;s;s;;|9;;2;open;a;;1;;p;s;;|10;;1;open;a;;1;;p;s;; 1005
	
	
	# 1;;;open;a;7495;1;6684;s;s;;|2;;;u19;b;845;1;778;p;r;;|3;2025-06-18 06:00:00;8;u17;c;54;1;3975;s;s;; 1000 
	
	# 1;;;u14;a;;1;;s;s;;|2;;1;u15;a;;1;;s;s;;|3;;1;u16;a;;1;;s;s;;|4;;1;u17;a;;1;;s;s;;|5;;1;open;a;;1;;p;s;;
	# 1;;;u14;a;;1;;s;s|2;;1;u15;a;;1;;s;s|3;;1;u16;a;;1;;s;s|4;;1;u17;a;;1;;s;s|5;;1;open;a;;1;;p;s
	
	chop $i{fixtures_saved_values} if $i{fixtures_saved_values} ;
	
	$i{fixtures_saved_values} =~ s/([a-zA-Z0-9]);+(\|)/$1$2/g;
	$i{fixtures_saved_values} =~ s/([a-zA-Z0-9])\|+$/$1/;

	$ignore{fixtures_saved_values} = (($id && $i{fixtures_saved_values} eq $db{$table}{$id}{fixtures_saved_values}) || (!$i{fixtures_saved_values} && !$db{$table}{$id}{fixtures_saved_values})) ? 1 : 0 ;
	
} #------------------------------------------------------------------------------------------

sub process_analytics_tab {

	$i{analytics_saved_values} = qq~~ ;
	
	my $suffix = "analytics" ;
	
	my @changed_field_keys = ("stream_forwarding","stream_key","stream_URL") ; 

	for my $row_nr (1 .. 100) {
		
		foreach (@changed_field_keys) {
			$i{analytics_saved_values} .= ($i{"$_\_$suffix\_$row_nr"}) ? qq~$i{"$_\_$suffix\_$row_nr"};~ : ($i{"$_\_fixtures_$row_nr"}) ? qq~$i{"$_\_fixtures_$row_nr"};~ : qq~;~ ;
			$ignore{"$_\_$suffix\_$row_nr"} = 1 ;  
			$ignore{"$_\_fixtures_$row_nr"} = 1 ;  
		}
		
		$i{analytics_saved_values} =~ s/;+$// ;
		$i{analytics_saved_values} .= qq~|~ ; 
		
	}
	
	$i{analytics_saved_values} =~ s/\|+$// ;
	
	$ignore{analytics_saved_values} = (($id && $i{analytics_saved_values} eq $db{$table}{$id}{analytics_saved_values}) || (!$i{analytics_saved_values} && !$db{$table}{$id}{analytics_saved_values})) ? 1 : 0 ;	
	
} #------------------------------------------------------------------------------------------

sub insert {
	
	my $quote_cancelled = $i{quote_cancelled} ; my $quote_accepted = $i{quote_accepted} ; my $quote_rejected = $i{quote_rejected} ;

	&add_db_fields ;

	$i{last_updated} 	= "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
	$i{date_created}	= "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
	$i{created_by}     	= $userid ;
	$i{last_changed_by}	= $userid ;
	
	$i{id} = &db_min_get_max($table,'id') ; 
	$i{id} = 1000 if !$i{id} || $i{id} < 1000 ;
	
	&process_fixtures_tab('') ;
	
	&process_analytics_tab('') ;
	
	&set_default_i_vals ;
	
	&process_multi_select ; 
	
	&process_client_id ;
	
	$ignore{country_id} = 1 ;

	&db_min_insert($table) ;

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

sub update {

	unless ($i{id}) { 
		$error = qq(NO ID) ; 
		return ; 
	}
	
	$i{last_updated} 	= "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
	$i{last_changed_by}	= $userid ;

	&edit_db_fields ;
	
	&set_default_i_vals ;
	
	&process_fixtures_tab($i{id}) ;
	
	&process_analytics_tab($i{id}) ;
	
	&process_multi_select ; 
	
	&process_client_id ;
	
	# &log_changes($i{id}) ;

	# &db_min_upd($table,"id='$i{id}'") ;
	
	our $line = qq~~ ;
	
	$ignore{country_id} = 1 ;
	
	&common_shared_log_update_changes($table,"analytics_changes","changes_analytics") ;
	
} #------------------------------------------------------------------------------------------

# sub log_changes {
	
	# my ($id) = @_ ;
	
	# &db_min_ro($table,"*","`id`='$id'",'','') ;
	
	# my $line = qq~~ ;
	
	# my %col_to_be_updated = () ;
	
	# foreach (keys %i) {
		# $col_to_be_updated{$_} = 1 ;
	# }
	
	# foreach my $col (keys %{$db{$table}{$id}}) {
		
		# next if $ignore{$col} || $hidden{$col} == 1 || substr($col,0,3) eq 'new' || !$col_to_be_updated{$col} || $col eq 'last_updated' ;
		# if (($i{$col} || $db{$table}{$id}{$col}) && $db{$table}{$id}{$col} ne $i{$col}) {
			# $line .= qq~$col='$db{$table}{$id}{$col}',~ ;
		# } elsif ((!$i{$col} && !$db{$table}{$id}{$col}) || (($i{$col} || $db{$table}{$id}{$col}) && $db{$table}{$id}{$col} eq $i{$col})) {
			# $ignore{$col} = 1 ; 
		# }
	# }
	
	# $line = qq~$now_year$now_year$now_mm$now_dd$now_hour$now_min$now_sec|$now_year-$now_mm-$now_dd $now_hour:$now_min:$now_sec|event_quote_id='$id'|user_id=$userid|changed_from|~ . $line if $line ;
	
	# return unless $line ;
	
	# chop $line ;
	
	# &common_log_changes("events/changes_analytics.dat",$line) ;
	
	
	
# } #------------------------------------------------------------------------------------------

# sub process_event_to {
sub process_client_id {
	
	my @abc = split(/\:/,$i{client_id}) ;
	$i{client_id} = $abc[0] ;
	
} #------------------------------------------------------------------------------------------

sub process_multi_select {
	
	local @sporttypeids      = split(/\,/,$i{sporttypeids}) ;
	my $sporttypeids         = join(";",@sporttypeids) ;
	$sporttypeids            =~ s/\s//g; # remove white space
	$ignore{sporttypeids}    = 1 ;
	$i{sport_type_ids}       = $sporttypeids ;
	$i{sport_type_ids}       = 0 unless $i{sport_type_ids} ;	

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

sub duplicate {

	unless ($i{id}) { 
		$error = qq~NO ID~ ; 
		return ; 
	}
	
	&db_min_copy($table,$i{id}) ;
	
} #------------------------------------------------------------------------------------------

sub delete {

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

	&db_min_delete($table,"`id`='$i{id}'") ;

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

sub set_default_i_vals {
	
	$i{created_by} 					= '0' unless $i{created_by} ;
	$i{event_completed} 			= '0' unless $i{event_completed} ;
	$i{event_accepted} 				= '0' unless $i{event_accepted} ;
	$i{event_pending} 				= '0' unless $i{event_pending} ;
	$i{event_cancelled} 			= '0' unless $i{event_cancelled} ;
	$i{event_rejected} 				= '0' unless $i{event_rejected} ;
	$i{event_created} 				= '0' unless $i{event_created} ;
	$i{country_id} 					= '0' unless $i{country_id} ;
	$i{total_fixtures} 				= '1' unless $i{total_fixtures} ;
	$i{service_type_id} 			= '0' unless $i{service_type_id} ;
	$i{event_quote_id} 				= '0' unless $i{event_quote_id} ;
	$i{region_id}					= '0' unless $i{region_id} ;
	$i{home_teams_built_on_regions} = '0' unless $i{home_teams_built_on_regions} ;
	$i{derby_day_weekly_fixture_id} = '0' unless $i{derby_day_weekly_fixture_id} ;
	$i{tournament_festival_id} = '0' unless $i{tournament_festival_id} ;
 
} #----------------------------------------------------------------------------------------

sub list_screen {
		
	$trigger_jquery_raw .= qq~
		function deleteMinItem_custom (name,id) {
			BootstrapDialog.confirm({
				title: 'Confirm Delete',
				message: 'Are you sure you want to delete <strong>'+name+'</strong>?',
				type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING
				callback: function(result) {            
					if (result) {
						let delete_url = "$useropts{scripts}/get/get_delete_event_quote.pl?"+id+"&$table" ;
						\$.get(delete_url) ; 
						\$("#analytics_event_row_"+id).html("") ;
					}
				}
			}) ;
		}
	~ ; 
	
	&db_min_ro('users','id,username,name,email','','','') ;
	foreach my $_id (keys %{$db{users}}) {
		$username{$_id} = $db{users}{$_id}{username} ;
		$name{$_id}     = $db{users}{$_id}{name} ;
		$email{$_id}    = $db{users}{$_id}{email} ;
	}
		
	&db_min_ro('sport_types','*','','','') ;
	foreach my $_id (keys %{$db{sport_types}}) { $sport_type{$_id} = $db{sport_types}{$_id}{name} ; }

	if ($iaction eq 'completed' or $i{options} eq 'completed')  { push @report_sql, "q.event_completed='1'" ; }
	if ($iaction eq 'accepted' 	or $i{options} eq 'accepted')  	{ push @report_sql, "q.event_accepted='1'" ; }
	if ($iaction eq 'rejected' 	or $i{options} eq 'rejected')  	{ push @report_sql, "q.event_rejected='1'" ; }
	if ($iaction eq 'closed' 	or $i{options} eq 'closed')    	{ push @report_sql, "(q.event_cancelled='1' OR (q.event_expiry<'$now_year-$now_mm-$now_dd' AND q.event_accepted<>'1'))" ; }
	if ($iaction eq 'pending' 	or $i{options} eq 'pending')   	{ push @report_sql, "q.event_pending='1'" ; }
	if ($iaction eq 'list' 		or $i{options} eq 'list')      	{ push @report_sql, "q.event_cancelled<>'1'" ; }

	my $t1 = $table ;
	my $t2 = 'countries' ; 
	my $t3 = 'customers' ; 
	my $t4 = 'event_quotes' ;
	our $tables = "$t1,$t2,$t3,$t4" ;
	
	if ($is_schools_manager || $is_operator) {
		@report_sql_or = () ;
		foreach $_reg_id (keys %{$glob_regids{$userid}}) {
			push @report_sql_or, "q.region_id = '$_reg_id'"
		}
		my $sql_or = join(' OR ',@report_sql_or) ;
		push @report_sql, "($sql_or)" if $sql_or ; 
		push @report_sql, "(q.event_created='1')" if $is_schools_manager ;  
		# push @report_sql, "(q.user_id='$userid')" if $is_schools_manager ;  
		push @report_sql, "(q.event_accepted='1')" if $is_operator && !$i{options} ;  
	}
	
	push @report_sql, "(q.event_completed <> '1')" if $iaction eq 'list' ;  
	
	my $srch_where_sql = join(' AND ', @report_sql) ; my $sql_where = ($srch_where_sql) ? "WHERE $srch_where_sql" : '' ;
	
	&db_min_raw("SELECT q.id AS 'quote_id',
						q.sport_type_ids,
						q.start_date_time,
						q.event_name, 
						q.event_expiry,
						q.client_id,
						q.event_date,
						q.date_created,
						q.country_id,
						q.event_cancelled,
						q.event_accepted,
						q.event_completed,
						q.event_pending,
						q.event_created,
						q.event_rejected,
						q.created_by,
						q.additional_notes,
						q.total_fixtures,
						q.service_type_id,
						q.event_quote_id,
						q.fixtures_saved_values,
						q.analytics_saved_values,
						c.name AS 'country',
						t.name AS 'customer',
						eq.event_system_id_multiple
			FROM $t1 q LEFT JOIN $t2 c ON q.country_id = c.id 
					   LEFT JOIN $t3 t ON q.client_id	= t.id
					   LEFT JOIN $t4 eq ON q.event_quote_id	= eq.id
			$sql_where;");

	foreach $row (@$rows_array_ref) {        
		for (0 .. $col_cnt){
			# &common_debug("[$_] $col_name{$_} -> @$row[$_]") ;
			$db{$tables}{@$row[0]}{$col_name{$_}} = @$row[$_] ;
		}    
	}
 
	&db_min_ro('event_systems','id,name,description','','','') ; 
	
	&db_min_ro('customers','id,name','','','') ; 
	
	&db_min_ro('sport_types','id,name','','','') ; 
	
	&analytics_event_bookings_tabs_hash ; # load for PDF links
	&quote_list ; # load for PDF links

	if ($iaction eq 'update' or $iaction eq 'save'){  
		&common_min_extra_crumb("list-$lcpage\s","List $ucfirstpage\s") ;
	}
	
} #------------------------------------------------------------------------------------------

sub quote_list {
	
	# our @sql_col_display = ("nr","date","customer","user","event","venue","location","sports_type","date_from","date_to","days","type") ;
	# our @sql_col_display = ("nr","event_start","event_end","date_added","customer","user","event","venue","location","sports_type","days","type") ;
	
	our @sql_col_display   = ("nr","event_start","event_end","date_added","customer","event","sport","total_fixtures","service_type") ;
	
	our @col_display_excel = @sql_col_display ; 
		
	push @sql_col_display, "" ;
	
	&report_xlsx_export_header("Analytics-Events",'analytics_events') ; 

	our $ws2 = 'Individual Games' ;

	&xlsxcreator_add_worksheet($ws2) ;

	my %individual_games = () ; 

	our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ;
	
	foreach my $id (sort {$b <=> $a} keys %{$db{$tables}}) {
		
		next unless $id ; 
		
		my $quote_expiry		= $db{$tables}{$id}{event_expiry} ; $quote_expiry =~ s/\-//iog ;
		our $quote_accepted   	= $db{$tables}{$id}{event_accepted} ;		
		our $quote_pending    	= $db{$tables}{$id}{event_pending} ;
		our $quote_cancelled  	= $db{$tables}{$id}{event_cancelled} ;
		our $quote_completed  	= $db{$tables}{$id}{event_completed} ;
		our $quote_created    	= $db{$tables}{$id}{event_created} ;
		our $quote_rejected   	= $db{$tables}{$id}{event_rejected} ;
		
		if ($quote_completed) {
			$sortprefix = 'd' ;
		} elsif ($quote_accepted) {
			$sortprefix = 'c' ;
		} elsif ($quote_rejected) {
			$sortprefix = 'x' ;
		} elsif ($quote_cancelled) {
			$sortprefix = 'z' ;
		} elsif ($quote_created) { # create by schools_manager
			$sortprefix = 'a' ;
		} elsif ($quote_pending) {
			$sortprefix = 'b' ;
		}
		
		if ($usertype eq 'support') {
			next unless $quote_accepted && !$quote_completed ;
		}
		
		# if ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd" and $iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all') { next ; }
		
		my $quote_date = $db{$tables}{$id}{event_date} ; $quote_date =~ s/\-//iog ;
		
		$yr = substr($quote_date,0,4) ; 
		$mm = substr($quote_date,4,2) ; 
		$dd = substr($quote_date,6,2) ;
		
		my ($yr2,$mm2,$dd2) = Add_Delta_Days($yr,$mm,$dd,60); #

		$mm2  = sprintf("%02s",$mm2) ;
		$dd2  = sprintf("%02s",$dd2) ;

		$quote_date = "$yr2$mm2$dd2" ;
		
		if ($quote_date && $quote_date < "$now_year$now_mm$now_dd" && $quote_accepted!=1 &&
			$iaction ne 'report' && $iaction ne 'accepted' && $iaction ne 'closed' && $iaction ne 'all' && 
			$i{options} ne 'accepted' && $i{options} ne 'closed' && $i{options} ne 'all') { next ; }
		
		$print_tbody .= qq~<tr id="analytics_event_row_$id">~ ;
		
		$xlsxcol = 0 ;
		
		my $quote_nr = $db{$tables}{$id}{quote_nr} ;

		my @fixtures_saved_values = split(/\|/,$db{$tables}{$id}{fixtures_saved_values}) ; 
		my @analytics_saved_values = split(/\|/,$db{$tables}{$id}{analytics_saved_values}) ; 
		
		my $row_cnt = 0 ;
		foreach (@fixtures_saved_values) {
			my $date = (substr($_,0,1) eq ';') ? substr($db{$tables}{$id}{start_date_time},0,10) : substr($_,0,10) ;
			my $time = (substr($_,0,1) eq ';') ? substr($db{$tables}{$id}{start_date_time},11,5) : substr($_,11,5) ;
			$individual_games{$date}{$time}{$id}{fixtures} .= qq~$_\|~ ; 
			$individual_games{$date}{$time}{$id}{analytics} .= qq~$analytics_saved_values[$row_cnt]\|~ ; 
			$row_cnt++ ;
		}

		foreach (@sql_col_display) {
		
			unless ($_) { next ; } # blank for the buttons column
			my $val = $db{$tables}{$id}{$_} ;
			my $align = qq~ class="dt-center"~ ; 
			my $nowrap = '' ;
			my $val_xlsx = '' ;
			
			if ($_ eq 'nr') {
				
				$nowrap = 'nowrap' ;
				$sort_val = sprintf("%06d",$id) ; 
				$sort_val = ($quote_accepted) ? qq~5~ . $sort_val : ($quote_completed) ? qq~4~ . $sort_val : ($quote_pending) ? qq~3~ . $sort_val : ($quote_rejected) ? qq~2~ . $sort_val : ($quote_cancelled) ? qq~1~ . $sort_val : qq~0~ . $sort_val  ; 
				$val = qq~<span style="display:none;">$sort_val</span>~ . &common_min_get_event_quote_button($id,$tables,"analytics-event-bookings") ;  
				$val .= qq~<span title="Event Quote : $db{$tables}{$id}{event_quote_id}" data-toggle="tooltip" data-placement="top"><a href="javascript:editMinItem('$db{$tables}{$id}{event_quote_id}','event-quotes');" style="color:black;"><i class="glyphicons glyphicons-paired icon-white"></i></a></span>~ if $db{$tables}{$id}{event_quote_id} ;
				$val_xlsx = $id ; 		
				# javascript:editMinItem('10922','event-quotes');
				if ($quote_completed) {
					&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format80) ; 
				} elsif ($quote_accepted) {
					&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format77) ;
				} elsif ($quote_created) {
					&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format78) ; # yellow
				} elsif ($quote_pending) {
					&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format79) ; # orange
				} elsif ($quote_cancelled) {
					&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format81) ; # red
				}
				
			} elsif ($_ eq 'event_start') {
				my $sort_val = $db{$tables}{$id}{start_date_time} =~ s/[\-:\s]//gr;
				$val_xlsx = &common_min_date_as_string(substr($db{$tables}{$id}{start_date_time},0,16)) ;
				$val   = qq~<span style='display:none;'>$sort_val</span>~ . $val_xlsx ;
				$nowrap = 'nowrap' ; 
			} elsif ($_ eq 'event_end') {
				
				if ($db{$tables}{$id}{end_date_time}) {
					my $sort_val = $db{$tables}{$id}{end_date_time} =~ s/[- :]//g ; 
					$val_xlsx = &common_min_date_as_string(substr($db{$tables}{$id}{end_date_time},0,16)) ;
					$val   = qq~<span style='display:none;'>$sort_val</span>~ . $val_xlsx ;					
				} elsif ($db{$tables}{$id}{fixtures_saved_values}) {
					my $latest_date = "" ; my $latest_date_val = "" ;
					foreach (split(/\|/,$db{$tables}{$id}{fixtures_saved_values})) {
						next unless $_ ; 
						my @saved_vals = split(/\;/,$_) ; 
						next unless $saved_vals[0] ;
						my $date_val = $saved_vals[0] ;
						$date_val =~ s/[- :]//g ; 
						$latest_date = $saved_vals[0] if !$latest_date_val || ($latest_date_val && $latest_date_val < $date_val) ; 
						$latest_date_val = $latest_date  ;
						$latest_date_val =~ s/[- :]//g ; 
					}
					$val = substr($latest_date,0,10) ;
					if ($val) {
						my $sort_val = $val ;
						$sort_val =~ s/[- :]//g ; 
						$val_xlsx = &common_min_date_as_string($val) ;
						$val = qq~<span style='display:none;'>$sort_val</span>~ . &common_min_date_as_string($val) ;								
					}
				}

				$nowrap = 'nowrap' ; 
			} elsif ($_ eq 'date_added') {
				my $sort_val = $db{$tables}{$id}{date_created} =~ s/[\-:\s]//gr; 
				$val_xlsx =  &common_min_date_as_string($db{$tables}{$id}{date_created}) ;
				$val =  qq~<span style='display:none;'>$sort_val</span>~ . $val_xlsx ; 
				$val_xlsx .= qq~ [Added By: $username{$db{$tables}{$id}{created_by}}]~ ; 
				$val = qq~<span title data-toggle="tooltip" data-placement="top" data-original-title="Added By: $username{$db{$tables}{$id}{created_by}}">$val</span>~ ;  
				$nowrap = 'nowrap' ; 
			} elsif ($_ eq 'event') {
				$val = $db{$tables}{$id}{event_name} ; 
				$nowrap = '' ;
			} elsif ($_ eq 'customer') {
				$nowrap = 'nowrap' ; 
			} elsif ($_ eq 'country_id') {
				$val = $db{$tables}{$id}{country} ; 
			} elsif ($_ eq 'sport') {
				$val = join("<br>", map { $sport_type{$_} } split(/\;/,$db{$tables}{$id}{sport_type_ids})) ;  
				$val_xlsx = $val ;
				$val_xlsx =~ s/\<br>/\;/g ;
			} elsif ($_ eq 'total_fixtures') {
				$val = ($db{$tables}{$id}{total_fixtures}) ? $db{$tables}{$id}{total_fixtures} : 1 ; 
			} elsif  ($_ eq 'service_type') {
				$db{$tables}{$id}{service_type_id} = ($db{$tables}{$id}{service_type_id}) ? $db{$tables}{$id}{service_type_id} : 2 ;
				$val = $service_types{$db{$tables}{$id}{service_type_id}} ; 
			}
			$print_tbody .= qq~<td $nowrap $align>$val</td>~ ;  
			
			if ($_ ne 'nr') {
				$val_xlsx = $val unless $val_xlsx ;
				&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format82) ; 
			}
			$xlsxcol++ ; 
			
		}
		
		$xlsxrow++ ;
		 
		my $quote_nr = $quote_nr ; $quote_nr =~ s/'//iog; unless ($quote_nr) { $quote_nr = $id ; }

		my $edit_butt     = qq~<a class="btn btn-info btn-xs" href="javascript:editMinItem('$id','analytics-event-bookings');"><i class="glyphicon glyphicon-edit icon-white"></i></a>~ ;	
		my $delete_butt   = qq~<a class="btn btn-danger btn-xs" href="javascript:deleteMinItem_custom('$quote_nr','$id')"><i class="glyphicon glyphicon-trash icon-white"></i></a>~ ;
		 # ($glod_user_level < 3 || $quote_accepted || $quote_completed || $quote_rejected || $quote_pending) ? '' :
		my $copy_butt = qq~<a class="btn btn-success btn-xs" href="javascript:copyMinItem('$id');" title="Copy" data-toggle="tooltip" data-placement="top"><i class="glyphicon glyphicon-retweet icon-white"></i></a>~ ;

		$edit_butt 		= qq~$edit_butt&nbsp;~ 		if $edit_butt ; 
		$copy_butt 		= qq~$copy_butt&nbsp;~ 		if $copy_butt ; 
		$delete_butt    = qq~$delete_butt&nbsp;~ 	if $delete_butt ; 

		$print_tbody   .= qq~<td nowrap class="dt-center">&nbsp;$edit_butt$copy_butt$delete_butt</td></tr>~ ;
	}
	  
	my @day_name = ("","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday") ;  
	my @month_name = ("","January","February","March","April","May","June","July","August","September","October","November","December") ; 
	
	my $xlsxrow2 = 0 ; my $xlsxcol2 = 0 ; 
	
	my %team_ids = () ; 
	
	foreach my $a (keys %individual_games) {
		foreach my $b (keys %{$individual_games{$a}}) {
			foreach my $c (keys %{$individual_games{$a}{$b}}) {
				my @abc = split(/\|/,$individual_games{$a}{$b}{$c}{fixtures}) ;
				foreach (@abc) {
					my @abcd = split(/\;/,$_) ; 
					$team_ids{$abcd[4]} = 1 ;
					$team_ids{$abcd[6]} = 1 ;
				}
			}
		}
	}
	
	my $team_sql = join(" OR ", map{ "id='$_'" } keys %team_ids) ; 
	
	&db_switch_conn('sss') ;
	
	&db_min_ro('teams','id,name',$team_sql,'','') ; 
	
	&db_switch_conn('aisa') ;
	
	my $heading_count = 0 ; my %seen_event_sport = () ; 
	
	foreach my $date (sort {$a cmp $b} keys %individual_games) {
		
		my ($year,$month,$day) = split(/\-/,$date) ; 
		my $day_of_week = Day_of_Week($year,$month,$day) ; 
		my $day_add = ($day eq '1') ? "st" : ($day eq '2') ? "nd" : ($day eq '3') ? "rd" : "th" ;
		my $date_name = "$day_name[$day_of_week] $day$day_add $month_name[$month]" ;

		&xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2,"$date_name",$format109) ; 

		my $first_game = 1 ; 
		
		my $contain_tbc_events = 0 ;  
		my $contain_confired_events = 0 ; 
		
		foreach my $time (sort {$a cmp $b} keys %{$individual_games{$date}}) {
		
			foreach my $a_id (sort { $a <=> $b } keys %{$individual_games{$date}{$time}}) {

				$individual_games{$date}{$time}{$a_id}{fixtures} =~ s/\|+$// ;
				$individual_games{$date}{$time}{$a_id}{analytics} =~ s/\|+$// ; 
				my @individual_games_fixtures = split(/\|/,$individual_games{$date}{$time}{$a_id}{fixtures}) ;
				my @individual_games_analytics= split(/\|/,$individual_games{$date}{$time}{$a_id}{analytics}) ;
				
				my $row_cnt = scalar @individual_games_fixtures ;
				$row_cnt = scalar @individual_games_analytics if scalar @individual_games_analytics > scalar @individual_games_fixtures ;
				$row_cnt = 0 unless $row_cnt ;
				 
				next unless $row_cnt ;

				my $tbc_game = 1 ;
				
				foreach my $row_nr (0 .. $row_cnt - 1) {
					
					my @data_split = split(/\;/,$individual_games_fixtures[$row_nr]) ; 
					
					my $customer_name = uc $db{customers}{$db{$tables}{$a_id}{client_id}}{name} ;
					my $sport_name = ($db{$tables}{$a_id}{sport_type_ids} && $db{$tables}{$a_id}{sport_type_ids} !~ /;/) ? $db{sport_types}{$db{$tables}{$a_id}{sport_type_ids}}{name} : $db{sport_types}{$data_split[1]}{name} ;
					$sport_name = uc $sport_name ;
					
					$heading_count++ unless $seen_cleint_sport{$db{$tables}{$a_id}{client_id}}{$sport_name}  ; 
					$heading_count = $heading_count%3 ;
					$seen_cleint_sport{$db{$tables}{$a_id}{client_id}}{$sport_name} = 1 ;
					
					my $heading_format = ($heading_count == 1) ? $format110 : ($heading_count == 2) ? $format111 : ($heading_count == 0) ? $format112 : $format112 ; 
					
					if (!$data_split[6]) {
						$tbc_games{$date}{$db{$tables}{$a_id}{client_id}}{$sport_name}++ ;
						$contain_tbc_events = 1 ;
						next ;
					} else {
						$contain_confired_events = 1 ;
						$tbc_game = 0 ; 
					}
					
					$xlsxrow2++ if $first_game ;
					$first_game = 0 ;  
					$xlsxrow2++ ;

					&xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," $customer_name $sport_name ANALYTICS",$heading_format) ; 
					$xlsxrow2++ ; 
					
					&xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2,"  $db{teams}{$data_split[4]}{name} vs $db{teams}{$data_split[6]}{name}",$format1) ; 
					$xlsxrow2++ ;
					
					if ($data_split[0]) {
						&xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2,"  " . substr($data_split[0],11,5),$format1) ; 
					} else {
						&xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2,"  " . substr($db{$tables}{$a_id}{start_date_time},11,5),$format1) ;					
					}
					 
					if ($db{$tables}{$a_id}{event_system_id_multiple}) {
						$db{$tables}{$a_id}{event_system_id_multiple} =~ s/f-//g ;
						my $systems = join(";", map { "$db{event_systems}{$_}{name} ($db{event_systems}{$_}{description})" } split(/\;/,$db{$tables}{$a_id}{event_system_id_multiple})) ;
						$systems =~ s/ ()//g ;

						foreach (split(/\;/,$systems)) {
							next unless $_ ;
							$xlsxrow2++ ; 
							&xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2,"  $_",$format115) ; 
						}
					}
					
					if ($individual_games_analytics[$row_nr]) {
						
						my @data_split_2 = split(/\;/,$individual_games_analytics[$row_nr]) ; 
						
						if ($data_split_2[0] eq '1' && $data_split_2[1]) {
							$xlsxrow2++ ; 
							&xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2,"  " . $data_split_2[1],$format1) ; 	
						}
						if ($data_split_2[0] eq '1' && $data_split_2[2]) {
							$xlsxrow2++ ; 
							&xlsxcreator_write_url($ws2,$xlsxrow2,$xlsxcol2,$data_split_2[2],"$data_split_2[2]") ; 	
						}
						
					}
					
				}
				$xlsxrow2++ unless $tbc_game ; 
			}	 
		} 
		
		my $abcbc = 0 ; 
		
		$xlsxrow2++ if $contain_tbc_events && !$contain_confired_events ;
		
		foreach my $client_id (sort { $a <=> $b } keys %{$tbc_games{$date}}) {
			foreach my $sport_name (sort { $a <=> $b } keys %{$tbc_games{$date}{$client_id}}) {
				$xlsxrow2++ ;
				&xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2,"$db{customers}{$client_id}{name} $sport_name ANALYTICS",$format116) ; 
				$xlsxrow2++ ;
				&xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2,"Other $tbc_games{$date}{$client_id}{$sport_name} games still to be confirmed",$format113) ; 
				$abcbc = 1 ; 
			}
		}
		
		$xlsxrow2++ if $abcbc ;
		$xlsxrow2++ ;
	}
 
	$worksheet{$ws2}->set_column(0,0,75) ; 
	$worksheet{$ws}->set_column(0,0,10) ; 
	$worksheet{$ws}->set_column(1,5,30) ; 
	$worksheet{$ws}->set_column(6,8,20) ; 
	
	&report_xlsx_export_footer('L',15,'analytics_events') ; 
	
	if ($usertype eq 'support') {
		$fnsortcol   = 1 ; # start date
		$fnsortorder =  'asc' ;
	}

	# &common_min_extra_crumb("search-$lcpage\s","Search Screen") if $glod_user_level > 3 ;
	&common_min_extra_crumb("filter-$lcpage\s","Search Screen") if $glod_user_level > 3 ;

	# 12~yBf-w0xwLJcY7rY49dFy6Fw0tohiEHDUOw.png:Screenshot_2025-10-24_082334.png:Screenshot_2025-10-24_082804.png:32482_F.jpg|134~File_-_2025-10-08T074305.322.jpg:File_-_2025-10-09T080750.400.jpg:File_-_2025-10-10T091621.052.jpg:30729_F.jpg|309~Screenshot_2025-10-24_083010.png::Screenshot_2025-10-24_083250.png:31023vF.jpg
	# 11685
	# |309~;;;08:02:50
	
	
	
	
	# 12~2025-10-08 07:59:14;2025-10-09 08:22:14;2025-10-10 09:35:18;2025-10-11 08:49:36|309~2025-10-08 08:15:26;;2025-10-10 08:56:42;2025-10-11 08:41:10|134~2025-10-08 07:43:03;2025-10-09 08:07:59;2025-10-10 09:14:17;2025-10-11 08:33:47
	# 161
	# 2025-10-24 09:29:09


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

sub thead {

	&common_min_thead ;

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

sub add_db_fields {

	&hidden_fields ;
	$hidden{id} = 2 ; 

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

sub edit_db_fields {

	&hidden_fields ;
	$hidden{id} = 1 ;
	# $readonly{ref} = 'READONLY' ;

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

sub view_db_fields {

	&hidden_fields ;
	$hidden{id}					= 1 ;
	$label{event_name}			= 1 ;
	$label{qty}					= 1 ;
	$label{start_date_time}		= 1 ;
	$label{sport_type_ids}     	= 1 ;

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

sub hidden_fields {
	
	# if ($glod_user_level < 4) {	
	if ($glod_user_level < 3) {	
		
		$ignore{type_of_system} = 1 ;
		$ignore{system_details} = 1 ;
		$ignore{system_name} 	= 1 ;
		$ignore{operators} 		= 1 ;
		# $ignore{operator_ids} = 1 ;
	}
	
	$ignore{quote_nr}					= 1 ;
	$ignore{iaction}                   	= 1 ;
	$ignore{sport_type_ids_readonly}   	= 1 ; 
	$ignore{datetime}					= 1 ; 
	$ignore{custom_selected_region}		= 1 ; 
	$ignore{custom_selected_country}	= 1 ; 
	
	# $ignore{home_teams_built_on_regions}	= 1 ; 
	
	for (1 .. 100) {
		$ignore{"changed_fixtures_date_$_"} = 1 ;
		$ignore{"changed_home_team_$_"} = 1 ;
	}
	
	$hidden{event_date}		 			= 2 ;
	$hidden{last_updated}	 			= 2 ;
	$hidden{created_by}		 			= 2 ; 
							 			
	# $required{event_to}		 			= 1 ;
	# $required{country_id}	 			= 1 ;
	# $required{region_id}	 			= 1 ;
	$required{client_id}	 			= 1 ;

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

sub add_screen {

	$selected{max_cams}{10} = 'SELECTED';
	&select_opts('') ;
	%col_name = () ;
	&db_min_ro($table,'*',"id > 1 AND id < 10",'','') ;

	$page_title  = substr($page_title,0,-1) ;
	$db{$table}{''}{quote_nr} = &db_min_get_max($table,'id') ; 
	$db{$table}{''}{quote_nr} = 1000 if $db{$table}{''}{quote_nr} < 1000 ; 
	
	# if ($username eq 'rory') { $db{$table}{''}{quote_nr} = 1000 ; }
	
	&add_db_fields ;
	
	&build_boxes('','save') ;
		
	local $all_select_ids_string = join(",",@all_select_ids) ; 
	$trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true });~ ; 

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

sub view_screen {
	
	&edit_screen ;

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

sub edit_screen {

	unless ($i{id}) { $warning = qq(NO ID) ; return ; }
	
	# my $users_cols = "id,name,user_type" ; $users_cols = "id,name,user_type,region_ids" if $glod_user_level < 4 ;
	my $users_cols = "id,name,user_type" ; $users_cols = "id,name,user_type,region_ids" if $glod_user_level < 3 ;

	&db_min_ro('users',$users_cols,"`user_type` LIKE 'casual%' OR `user_type` = 'schools_manager'",'','') ;
	foreach (keys %{$db{users}}) { 
		next if $db{users}{$_}{user_type} eq 'schools_manager' ;
		$casual_name{$_} = $db{users}{$_}{name} ; 
		$casual_type{$_} = uc substr($db{users}{$_}{user_type},-1,1) ; 
		$casuals{$_}     = 1 if substr($db{users}{$_}{user_type},0,6) eq 'casual' ; 
	}

	&db_min_ro($table,'*',"id='$i{id}'",'','') ;
	
	$db{$table}{$i{id}}{quote_nr} = $i{id} ;
	
	my $cnt_rows = 0 ;
	for (1 .. $nr_of_system_names_and_clubs) {
		$cnt_rows = $_ if $system_name_ids[$_ - 1] or $club_ids[$_ - 1] ;  
	}
	
	our @table_op_ids = () ;
	our @multi_select_op_ids = () ;
	
	for (1 .. $cnt_rows) {			
		push @table_op_ids,$op_ids[$_ - 1] if $op_ids[$_ - 1] ;
		push @table_op_ids,0 unless $op_ids[$_ - 1] ;
	}
	for ($cnt_rows+1 .. $nr_of_system_names_and_clubs) {
		push @multi_select_op_ids,$op_ids[$_ - 1] if $op_ids[$_ - 1] ;
	}		

	our $quote_completed  = $db{$table}{$i{id}}{event_completed} ;
	our $quote_accepted   = $db{$table}{$i{id}}{event_accepted} ;
	our $quote_pending    = $db{$table}{$i{id}}{event_pending} ;
	our $quote_cancelled  = $db{$table}{$i{id}}{event_cancelled} ;
	our $quote_rejected   = $db{$table}{$i{id}}{event_rejected} ;
	
	# our $cancel_butt = ($d_check[2] > $now_ccyymmddhrmnsc && $iaction eq 'edit' && ($quote_completed || $quote_accepted || $quote_pending) && ($glod_user_level > 2 || $is_schools_manager)) ? 1 : 0 ;
	our $cancel_butt = ($iaction eq 'edit' && ($quote_completed || $quote_accepted || $quote_pending) && ($glod_user_level > 2 || $is_schools_manager)) ? 1 : 0 ;

	# if ($is_schools_manager) {
	if ($is_schools_manager || $glod_user_level < 4) {
		my @ed_from = &common_split_sql_time($db{$table}{$i{id}}{start_date_time}) ;
		my @d_check = &common_add_delta_dhms($ed_from[0],$ed_from[1],$ed_from[2],$ed_from[3],$ed_from[4],$ed_from[5],0,-18,0,0) ; # go 18 hours back from event start
		
		if ($d_check[2] < $now_ccyymmddhrmnsc) {
			$cancel_butt = 0 ;
		}
	}
			
	$page_title  = substr($page_title,0,-1) ;
	$page_title .= " : $i{id}" ;
	
	$custom_back_button = qq~&nbsp;<button type="button" class="btn btn-default" onclick="window.location.assign('$useropts{domain}/list-event-quotes')">Back</button>~ ;
	# $custom_back_button = qq~<a class="btn btn-default btn" href="" style="padding: 0px 3px 0px 3px;font-size:12px;$style" $tooltip>$val</a>~ ;

	# our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab
	&common_min_footer('id',"$lcpage\s");   

	&edit_db_fields ;
	
	&select_opts($i{id}) ;

	our $saveandexit = 1 ;

	&build_boxes($i{id},'update') ;
		
	&common_min_extra_crumb("filter-$lcpage\s","Search $ucfirstpage\s") if $glod_user_level > 3 ;

	local $all_select_ids_string = join(",",@all_select_ids) ; 
	$trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true });~ ; 
	
} #------------------------------------------------------------------------------------------

sub build_boxes {

	my ($id,$action) = @_ ;
	
	our @jquery_trigger_fields = () ; 
	our @jquery_custom_vat_ids = () ;
	our @jquery_duty_ids = () ;
	our @jquery_workings_trigger_fields = () ; 

	push @jquery_trigger_fields, 'inputRoe' ;
	push @jquery_workings_trigger_fields, 'inputRoe' ;
	
	for (1 .. 15) {	
		push @jquery_workings_trigger_fields, "checkboxVat_workings_event_$_" ;	
		push @jquery_workings_trigger_fields, "checkboxExcl_workings_event_$_" ;	
		# push @jquery_workings_trigger_fields, "checkboxVat_$_\_workings_casual_users" ;	
		# push @jquery_workings_trigger_fields, "checkboxExcl_$_\_workings_casual_users" ;	
	}
	&analytics_event_bookings_tabs_curr_symbols;

	foreach $col(keys %required) {
		&common_min_forms_required ;
	}
		
	our $tab_cnt = 0 ;
	
	&analytics_event_bookings_tabs_load_vars;

	$print_box_content_rows .= &common_min_forms_start($table) ;

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

		$print_box_content_rows .= qq~
			<div class='row'>
				<div class='col-md-12'>~ ;
					&build_boxes_top($id);
		$print_box_content_rows .= qq~
				</div>
			</div>
		~ ;
		
		#--------------------------------------------------------------------------
		
		$print_box_content_rows .= qq~<div class='row'>~ ;
		
			&analytics_event_bookings_tabs_cnt ;
			
			$print_box_content_rows .= qq(<div class="box col-md-12">
			<ul class="nav nav-tabs" id="myTab">);
			
			foreach (sort {$a<=>$b} keys %cntxt) {
				my $tab_name = &analytics_event_bookings_tabs_names($_) ; my $c_actv = '' ; # if ($_==1) { $c_actv = 'class="active"' ; }
				

				$c_actv = ($_==2) ? 'class="active"' : '' ; 
				
				$print_box_content_rows .= qq(<li id="$tab_name" $c_actv><a href="#$cntxt{$_}">$tab_name</a></li>);
				
				$tab_cnt++;
				}
				
			$print_box_content_rows .= qq(</ul>
			<div id="myTabContent" class="tab-content">);
			
			our %tab_sections = () ;
			
			foreach (sort {$a <=> $b} keys %cntxt) {
				
				my $tab_name = &analytics_event_bookings_tabs_names($_) ; my $active = '' ; 
				
				$active = ($_==2) ? 'active' : '' ; 
 
				my $colsleft = 12 ; my $showright = '' ;
					
				if ($cntxt{$_} eq 'one' or $cntxt{$_} eq 'seven') {
					$colsleft = 12 ; 
					$showright = 1 ;
				}
				
				$print_box_content_rows .= qq~<div class="tab-pane $active" id="$cntxt{$_}">~;				
					$print_box_content_rows .= qq~<div class='row' style="margin: 2px 4px 0 -10px;">~ ;						
						$print_box_content_rows .= qq~<div class='col-md-$colsleft'>~ ;
							&build_boxes_left($id,$_);
						$print_box_content_rows .= qq~</div>~ ;
					
					if ($showright) {
						$print_box_content_rows .= qq~<div class='col-md-6'>~ ;
							&build_boxes_right($id,$_);
						$print_box_content_rows .= qq~</div>~ ;
						}
				
					$print_box_content_rows .= qq~</div>~ ;							
				$print_box_content_rows .= qq~</div>~ ;
				}
			
		$print_box_content_rows .= qq~			
			</div>
		</div>
		<!--/span-->~ ;
					
		$print_box_content_rows .= qq~</div>~ ;
		
		#--------------------------------------------------------------------------

		$print_box_content_rows .= qq~<div class='row'><div class='col-md-12'>~ ;
			&build_boxes_bottom($id);
		$print_box_content_rows .= qq~</div></div>~ ;
		
		#--------------------------------------------------------------------------
	
	our $skip_save_btn = ($quote_completed && $glod_user_level <= 3) ? 1 : 0 ; 
	
	$print_box_content_rows .= &common_min_forms_end($id,$table,$action,$skip) ;

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

sub build_boxes_top {

	my ($id) = @_ ;

	our ($lcol,$fcol) = &common_min_columns(3,6) ;
		
	$add_form_fields = '' ;

	$fcol=8 ;

	$add_form_fields            .= qq~<div class='col-md-3'>~ ;
	$preferred_title{quote_nr}   = "Nr" ; 
	$readonly{quote_nr} = "READONLY" ;
	$add_form_fields            .= &common_min_form_input('quote_nr',$db{$table}{$id}{quote_nr},'') ;
	$add_form_fields            .= qq~</div>~ ;
	$add_form_fields            .= qq~<div class='col-md-3'>~ ;
	
	if (($db{$table}{$id}{event_date} eq '') or ($db{$table}{$id}{event_date} eq '0000-00-00')) { 
			$db{$table}{$id}{event_date} = $now_ccyy_mm_dd  ; 
	}
	$preferred_title{event_date} = "Date" ;
	$readonly{event_date} = "READONLY" ;
	$add_form_fields            .= &common_min_form_datepicker('event_date',$db{$table}{$id}{event_date}) ;
	my $plus_n_days_ccyy_mm_dd   = &common_add_delta_days(14) ;	
	
	# $trigger_jquery_raw .= qq~\$('#datepickerEvent_date').datepicker({format:'yyyy-MM-dd'})~ ;
	# $trigger_jquery_raw .= qq~\$('#datepickerEvent_date').datepicker({language: 'pt-BR'})~ ;  
	# $trigger_jquery_raw .= qq~\$('#datepickerEvent_date_fixtures_'+i).datepicker({language: 'pt-BR'})~ ;  
	
	# $required{event_to} = 1 ;
	# $required{region_id} = 1 ;
	
	$add_form_fields .= qq~</div>~ ;
	# $add_form_fields .= qq~<div class='col-md-3'>~ ;
		# $preferred_title{event_to} = "Client" ;
		# $add_form_fields .= &common_min_form_select('event_to',$db{$table}{$id}{event_to},'') ;
	# $add_form_fields .= qq~</div>~ ;
	$add_form_fields .= qq~<div class='col-md-3'>~ ;
	# $dlg{event_to} = qq~ 
		# <div class="col-md-1">
			# <a href="javascript:dlgMdl('$useropts{'scripts'}/dialog/add_customer.pl?add&selectEvent_to','Add Customer','','max-dialog');" class="btn btn-primary btn-xs" style="padding:1px 2px 1px 3px;margin-top:0px;" title='Add Customer' data-toggle='tooltip' data-placement='right'>
				# <i class="glyphicon glyphicon-plus" style="padding:0;margin-top:0px;">
				# </i>
			# </a>
		# </div>~ ;
	$fcol = 7;
	# &common_min_select_opts('sport_type_ids','sport_types','name','','','','') ;
	
	$sql_limit_user_regions = ($is_schools_manager || $is_operator) ? join(' OR ', map { "id = '$_'" } keys %{$glob_regids{$userid}}) : '' ;
	
	# our $debug = 1 ; 
	
	$allow_deselect{region_id} = 1 ; 
	
	&common_min_select_opts('region_id','regions','name','','','code',$sql_limit_user_regions) ;
 
	$add_form_fields .= qq~<input type="hidden" name="custom_selected_region" value="$db{$table}{$id}{region_id}">~ ; 
	
	$db{$table}{$id}{country_id} = $db{regions}{$db{$table}{$id}{region_id}}{country_id} ;
	
	$add_form_fields .= qq~<input type="hidden" name="custom_selected_country" value="$db{$table}{$id}{country_id}">~ ; 
	
	# $db{$table}{$id}{country_id} = "242" unless $db{$table}{$id}{country_id} ;
	
	&common_min_select_opts('country_id','countries','name','','','','') ;

	my %home_teams = () ; 
	
	foreach my $data (split(/\|/,$db{$table}{$id}{fixtures_saved_values})) {
		my @abc = split(/\;/,$data) ;
		$home_teams{$abc[4]} = 1 ; 
	}
	
	my $home_teams_str = join(" OR ", map{ "id='$_'" } keys %home_teams) ; 
	
	if ($db{$table}{$id}{client_id} || $home_teams_str) {

		&db_switch_conn('sss') ;
		
		# my $region_filter = $db{$table}{$id}{region_id} ;
		my $region_filter = '' ;
		my $client_filter = $db{$table}{$id}{client_id} ;

		$db{$table}{$id}{home_teams_built_on_regions} = ($iaction eq 'add' || (!$region_filter && !$client_filter)) ? 1 : $db{$table}{$id}{home_teams_built_on_regions} ;

		my $home_teams_built_on_regions =  $db{$table}{$id}{home_teams_built_on_regions} ;

		my $teams_sql = ($region_filter) ? qq~(`region_id`='$region_filter' OR (`region_id`='0' AND `matched_region_id`='$region_filter'))~ : qq~(`region_id`='0' AND `matched_region_id`='0')~ ; #(`region_id`='0' AND `matched_region_id`='0')
		
		if ($client_filter && !$home_teams_built_on_regions) {
			$teams_sql .= qq~ OR ~ if $teams_sql ;
			$teams_sql .= qq~(`aisa_client_id`='$client_filter')~ ;
		}
		
		if ($home_teams_str) {
			$teams_sql .= qq~ OR ~ if $teams_sql ;
			$teams_sql .= qq~($home_teams_str)~ ;
		}

		$opts{teams_id} 		= qq~~ ;
		$opts{client_teams_id} 	= qq~~ ;

		if ($teams_sql) {
			&db_min_ro('teams','*',"$teams_sql",'','') ; 
			foreach (sort { $db{teams}{$a}{name} cmp $db{teams}{$b}{name} } keys %{$db{teams}}) {
				my $region_id 			= $db{teams}{$_}{region_id} ;
				my $matched_region_id 	= $db{teams}{$_}{matched_region_id} ;
				my $client_id 			= $db{teams}{$_}{aisa_client_id} ;
				$opts{teams_id} 		.= qq~<option value='$_'>$db{teams}{$_}{name}</option>~ if ($region_filter && (($region_id eq $region_filter) || (!$region_id && $matched_region_id eq $region_filter))) || (!$region_filter && !$client_filter && !$region_id && !$matched_region_id) ; 
				next if $home_teams_built_on_regions || !$client_filter ;
				$opts{client_teams_id} 	.= qq~<option value='$_'>$db{teams}{$_}{name}</option>~ if $client_filter eq $client_id || $home_teams{$_} ; 
			}
		}
		
		# # # &db_min_ro('teams','*',"",'','') ; 
		# # # foreach (sort { $db{teams}{$a}{name} cmp $db{teams}{$b}{name} } keys %{$db{teams}}) {
			# # # $opts{away_team} .= qq~<option value='$_'>$db{teams}{$_}{name}</option>~ ; 
		# # # }

		# &common_min_select_opts('teams_id','teams','name','','','',"`region_id`='$db{$table}{$id}{region_id}' OR (`region_id`='0' AND `matched_region_id`='$db{$table}{$id}{region_id}')") if $db{$table}{$id}{region_id} ;
		# &common_min_select_opts('client_teams_id','teams','name','','','',"`aisa_client_id`='$db{$table}{$id}{client_id}'") if $db{$table}{$id}{client_id} && !$db{$table}{$id}{home_teams_built_on_regions} ;
		
		&db_switch_conn('aisa') ;
	
	}
	
	my %away_teams = () ; my %home_teams = () ;  my %home_and_away_teams = () ; 
	
	foreach (split(/\|/,$db{$table}{$id}{fixtures_saved_values})) {
		my @abc = split(/\;/,$_) ;
		$home_teams{$abc[4]} = 1 if $abc[4] ;
		$away_teams{$abc[6]} = 1 if $abc[6] ;
		$home_and_away_teams{$abc[4]} = 1 if $abc[4] ;
		$home_and_away_teams{$abc[6]} = 1 if $abc[6] ;
	}
	
	my $away_teams_sql = qq~~ ; 
	$away_teams_sql = join (" OR ",map{"id='$_'"} keys %home_and_away_teams) ;
	if ($away_teams_sql) {
		&db_switch_conn('sss') ;
		&db_min_ro('teams','id,name',"$away_teams_sql",'','') ; 
		foreach (sort { $db{teams}{$a}{name} cmp $db{teams}{$b}{name} } keys %{$db{teams}}) {
			next if $home_teams{$_} && !$away_teams{$_} ; 
			$opts{away_team} .= qq~<option value='$_'>$db{teams}{$_}{name}</option>~ ; 
		}
		&db_switch_conn('aisa') ;
	}
	
	# $db{$table}{$id}{country_id} = 242 unless $db{$table}{$id}{country_id} ;
	$opts{region_id} =~ s/value="$db{$table}{$id}{region_id}"/value="$db{$table}{$id}{region_id}" SELECTED/g if $db{$table}{$id}{region_id} ;
	$opts{country_id} =~ s/value="$db{$table}{$id}{country_id}"/value="$db{$table}{$id}{country_id}" SELECTED/g if $db{$table}{$id}{country_id} ;
	
	# $required{country_id} = qq~data-validation="required"~ ;
	# $required{region_id} = qq~data-validation="required"~ ;
	
	$allow_deselect{country_id} = 1 ; 
	
	$add_form_fields .= &common_min_form_select('country_id',$db{$table}{$id}{country_id},'') ;	
	$add_form_fields .= qq~</div><div class='col-md-3'>~ ;
	$add_form_fields .= &common_min_form_select('region_id',$db{$table}{$id}{region_id},'') ;	
	$add_form_fields .= qq~</div>~ ;
	
	$fcol = 8;
	
	$print_box_content_rows .= &common_min_box_top('qrcode',"Quote",'BABEC2');           
	
	$print_box_content_rows .= qq~
								<div class="row">
									<div class="col-md-12">
										$add_form_fields
									</div>
								</div>
							~;  
							
	$print_box_content_rows .= qq~
								<div class='row'>
									<div class='col-md-12' style='height:6px;'>
										&nbsp;
									</div>
								</div>
							~ ;		
							
	$print_box_content_rows .= &common_min_box_foot;
	
	$print_box_content_rows .= qq~<input type="hidden" name="home_teams_built_on_regions" value="$db{$table}{$id}{home_teams_built_on_regions}">~ ;
	
} #----------------------------------------------------------------------------------------

sub build_boxes_left {

	my ($id,$tab) = @_ ;

	our ($lcol,$fcol) = &common_min_columns(3,6) ;

	&analytics_event_bookings_tabs_build_qt_left($id,$tab);

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

sub build_boxes_right {

	my ($id,$tab) = @_ ;

	our ($lcol,$fcol) = &common_min_columns(3,6) ;

	&analytics_event_bookings_tabs_build_qt_right($id,$tab);
	  
} #----------------------------------------------------------------------------------------

sub build_boxes_bottom {

	my ($id) = @_ ;

	our ($lcol,$fcol) = &common_min_columns(2,2) ;

	$add_form_fields  = '' ;

	# --------------- START GRAND TOTAL ----------------------------------------------------------------------------------------------------------------------

	# $print_box_content_rows .= &common_min_form_input('activetab',$db{$table}{$id}{activetab},'hidden') ;

	# --------------- END RAND TOTAL ------------------------------------------------------------------------------------------------------------------------

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

sub fix_options_for_javascript {
	
	my ($options) = @_ ; 
	$options =~ s/\SELECTED//g ;
	$options =~ s/\"/\'/g ;
	return $options ; 
	
} #----------------------------------------------------------------------------------------

sub q_get_val {

	my ($val) = @_ ;

	my $disp_val = $val ;

	if ($val eq '0.00') { 
		$disp_val = '' ; 
	}

	return ($disp_val);

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

sub set_check_boxes_checked {

	my ($id,$rcnt,$prefix,$suffix) = @_ ;
	
	for (1 .. $rcnt) { 

		my $ifield  = $prefix . '_' . "$_$suffix" ;
		my $val = $db{$table}{$id}{$ifield} ;	
		# &common_debug("set_check_boxes_checked: [prefix=$prefix] [suffix=$suffix] ifield=$ifield, val=$val") ;
		
		$checkit{$ifield} = $val ;
	}
	
} #----------------------------------------------------------------------------------------

sub select_opts {

	my ($id) = @_ ;
	
	our $savjqy = 1 ;

	%filter_val = () ; %filter_select_opts = () ;
	# if ($is_schools_manager) {
	# if ($glod_user_level < 4) {
	if ($glod_user_level < 3) {
		$filter_select_opts{'regions'} = 1 ;
		foreach $_reg_id (keys %{$glob_regids{$userid}}) {
			$filter_val{'regions'}{$_reg_id} = 1 ;
		}
	}
	# &common_debug("[$usertype] filter_select_opts = $filter_select_opts{'regions'}") ; 
	
	local $region_id_where = qq~~ ; local @abcd = () ;

	# if ($is_schools_manager) {
	# if ($glod_user_level < 4) {
	if ($glod_user_level < 3) {
		foreach (split(",",$db{users}{$userid}{region_ids})) {
			push @abcd , "`id` = '$_'" ;
		}
	}
	
	$preferred_title{sport_type_ids} = "Sport Types" ; 
	%selected_multi = () ;
	$multiple{sport_type_ids} = 1; 
	my @sport_type_ids = split(/\;/,$db{$table}{$id}{sport_type_ids});
	foreach (@sport_type_ids) { 
		$selected_multi{$_} = 'SELECTED' ; 
	}

	&common_min_select_opts('sport_type_ids','sport_types','name',$db{$table}{$id}{sport_type_ids},'','','','','name') ;
 
	$extra_form_fields .= qq~<input type="hidden" name="sporttypeids" id="sport-type-ids" value="">~;
	
	foreach (@multi_select_op_ids) { 
		$selected_multi{$_} = 'SELECTED' ; # &common_debug("SELECTED operator_ids [$_] : [selected=$selected_multi{$_}]") ;
	}

	&db_min_ro('users',"id,name,region_ids","user_type LIKE 'casual%' AND block <> 1 AND inactive <> 1",'','') ; 
	
	foreach my $op_id (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) {	
		my $regions = "" ; 
		foreach (split(",",$db{users}{$op_id}{region_ids})) {
			$regions .= "$db{regions}{$_}{code}," ;
		}
		chop $regions if $regions ;
		my $user_names = $db{users}{$op_id}{name} ;
		$user_names = "$db{users}{$op_id}{name} [$regions]" if $regions ;
		$opts{operator_ids} .= qq~<option value = "$op_id" $selected_multi{$op_id}>$user_names</option>~ ; 	
		# for (1 .. $nr_of_system_names_and_clubs) {
			# $opts{"operator_ids_$_"} .= qq~<option value = "$op_id" $selected_table{$_}{$op_id}>$user_names</option>~ ; 	
	}
	
	# &common_min_select_opts('operator_ids','users','name',$db{$table}{$i{id}}{operator_ids},'','',"user_type LIKE 'casual%'") ;
	 
	$trigger_jquery .= qq~\$("#selectType\_chosen").css("width","80%");~ ;

	%selected_multi = () ;

	# $db{event_quotes}{''}{event_to} = 5 if $iaction eq 'add' ; # SuperSport Schools (Pty) Ltd 
	 		
	$extra_css .= qq(<style>
	.checkbox_checked label {
		position: absolute;
		width: 20px;
		height: 20px;
		background-color: green;
		-webkit-transition: background-color 1s ease-out 1s;
		-moz-transition: background-color 1s ease-out 1s;
		-o-transition: background-color 1s ease-out 1s;
		transition: background-color 1s ease-out 1s;
		margin:0;
	}

	.checkbox_checked input[type=checkbox]:checked + label {
		background-color:red;
		-webkit-transition: background-color 1s ease-out 1s;
		-moz-transition: background-color 1s ease-out 1s;
		-o-transition: background-color 1s ease-out 1s;
		transition: background-color 1s ease-out 1s;
	}

	.checkbox_checked label:after {
		position: absolute ;
		bottom: 8px ;
		width: 18px ;
		height: 10px ;
		opacity: 0 ;
		content: '' ;
		background: transparent ;
		border: 3px solid #000 ;
		border-top: none ;
		border-right: none ;
		-webkit-transform: rotate(-50deg) ;
		-moz-transform: rotate(-50deg) ;
		-ms-transform: rotate(-50deg) ;
		-o-transform: rotate(-50deg) ;
		transform: rotate(-50deg) ;
		-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
		filter: alpha(opacity=0) ;
	}
	.checkbox_checked input[type=checkbox] {
		visibility: hidden ;
	}
	.checkbox_checked input[type=checkbox]:checked + label:after {
		opacity: 1 ;
		-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)" ;
		filter: alpha(opacity=100) ;    
	}
	</style>) ;

	$trigger_jquery .= qq~\$("#selectSport_type_ids_chosen").css("width","100%");~ ;
		
	$trigger_jquery_raw .= qq~
	
	\$("#savebutt").click( async function() {

		let buttonClass = \$(this).attr("class") ;
		if (buttonClass == "btn btn-custom") {
			return ;
		}

		var we_can_save_form = check_before_saving() ;

		let end_date = new Date(\$("input[name='end_date_time']").val()) ;
		let start_date = new Date(\$("input[name='start_date_time']").val()) ;

		start_date   = new Date(start_date.getTime() + 2 * 60 * 60 * 1000) ; // Add 2 hours
		end_date   = new Date(end_date.getTime() + 2 * 60 * 60 * 1000) ; // Add 2 hours

		let earliest_latest = find_latest_and_earliest_date_in_fixtures() ;
		
		if (start_date > earliest_latest.earliest_date) {
			noty({text:'Please Select an Event Start Date that is before the earliest date on the Fixtures tab!',layout:"center",type:"error",timeout:3000}) ;
			we_can_save_form = 0 ;
		}
		
		if (end_date < earliest_latest.latest_date) {
			noty({text:'Please Select an Event Start Date that is before the earliest date on the Fixtures tab!',layout:"center",type:"error",timeout:3000}) ;
			we_can_save_form = 0 ; 
		}
		
		for (let i=1;i<=100;i++) {
			
			if (!\$("#fixtures_"+i).html() || \$("#fixtures_"+i).css("display") === 'none') {
				break ;
			}
			if (\$("#selectHome_team_fixtures_"+i).val() && !\$("#selectAway_team_fixtures_"+i).val()) {
				we_can_save_form = 0 ;
				noty({text:'Please Select an Away team when selecting a Home Team on the Fixtures tab!',layout:"center",type:"error",timeout:3000}) ;
				break ;
			} else if (!\$("#selectHome_team_fixtures_"+i).val() && \$("#selectAway_team_fixtures_"+i).val()) {
				we_can_save_form = 0 ;
				noty({text:'Please Select an Home team when selecting a Away Team on the Fixtures tab!',layout:"center",type:"error",timeout:3000}) ;
				break ;
			}
		}
		
		if (\$("#selectEvent_quote_id").val() && we_can_save_form) {
		
			let date_url = "$useropts{scripts}/get/get_dates_from_event_quote.pl?event_quote_id="+\$("#selectEvent_quote_id").val()+"&start_date_time="+\$("input[name='start_date_time']").val()+"&end_date_time="+\$("input[name='end_date_time']").val() ;
			
			let dates_json = await fetchJSON(date_url);
			
			for (const key in dates_json) {
				const data = dates_json[key];
				noty({text:'The Start and End date of this Event is from '+data.start_date_time+' to '+data.end_date_time+' Compared to '+data.date_from+' to '+data.date_to+' for the Event Quote.<br>Please Ensure the Dates Correspond!',layout:"center",type:"warning",timeout:7500}) ;
				await sleep(7500);
			}
			
			// await \$.get(date_url, function(json) { 
			// 	\$.each(json, function(key, data) {  
			// 		noty({text:'The Start and End date of this Event is from '+data.start_date_time+' to '+data.end_date_time+' Compared to '+data.date_from+' to '+data.date_to+' for the Event Quote',layout:"center",type:"error",timeout:7500}) ;
			// 		// await sleep(10000);
			// 	});
			// }
			// ,'json') ; 
			
		}
		
		if (we_can_save_form) {
			\$('#analytics_event_bookings-form').submit() ;
		} else {
			return ;
		}
	}) ;
	
	function sleep(ms) {
		return new Promise(resolve => setTimeout(resolve, ms));
	}
	
	\$("#cancelbutt").click( function() {
		
		let buttonClass = \$(this).attr("class") ;
		if (buttonClass == "btn btn-custom") {
			return ;
		}
		
		var we_can_save_form = check_before_saving() ;
		
		if (we_can_save_form) {
			cancel_quote() ;
		} else {
			return ;
		}
		
	}) ;
	
	function cancel_quote () {

		BootstrapDialog.confirm({
			title: 'Confirm Cancellation',
			message: 'Are you sure you want to cancel this event?',
			type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING
			callback: function(result) {            
				if (result) {
					\$("#checkboxQuote_completed").prop("checked", false) ;
					\$("#checkboxQuote_accepted").prop("checked", false) ;
					\$("#checkboxQuote_pending").prop("checked", false) ;
					\$("#checkboxQuote_rejected").prop("checked", false) ;
					\$("#checkboxQuote_cancelled").prop("checked", true) ;
					\$('#event_quotes-form').submit() ;
				}
			}
		});
	}
		
	function check_before_saving () {

		$jquery_chosen_sel

		let st_val = \$("#selectSport_type_ids").chosen().val() ;
		\$('#sport-type-ids').val(st_val) ;
		
		return 1 ;
	}
	
	~ ;

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

sub page_opts {

	our $glyphicon     = 'global' ;
	our $lcpage        = 'analytics-event-booking' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ;
	our $table         = 'analytics_event_bookings' ;
	
	our $cust_cols     = 1 ; # display _blank_3.pm
	our $savjqy        = 1 ; 
	our $max_cams      = 10 ;

	&common_min_add_box_icon ;
	
	our %casuals       = (); 

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

sub report_ifields {
		
	if ($i{start_date_from} && $i{start_date_to}) {
		push @report_sql, "	(('$i{start_date_from}' <= start_date_time AND start_date_time <= '$i{start_date_to}') OR ('$i{start_date_from}' <= end_date_time AND end_date_time <= '$i{start_date_to}' AND end_date_time IS NOT NULL)) " ; 
		our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; 
		my $start_date_from = &common_min_date_as_string($i{start_date_from}) ; 
		my $start_date_to = &common_min_date_as_string($i{start_date_to}) ; 
		push @report_results, " (START DATE BETWEEN '$start_date_from' AND '$start_date_to') OR (END DATE BETWEEN '$start_date_from' AND '$start_date_to')" ;
	} 
	
	if ($i{country}) {
		push @report_sql, "(q.country_id = '$i{country}')" ;
		push @report_results, "country_id = `$i{country}`" ;
	}
	
	if ($i{customer_name} && $i{customer_name} ne 'all') {
		push @report_sql, "(q.client_id = '$i{customer_name}')" ;
		&db_min_ro('customers','id,name',"`id`='$i{customer_name}'",'','') ;
		push @report_results, "customer = `$db{customers}{$i{customer_name}}{name}`" ;
	}
	                                  
	if ($i{accepted} || $i{options} eq 'accepted') {
		push @report_sql, "(q.event_accepted='1' AND q.event_completed<>'1')" ;
		push @report_results, "event_accepted = `Yes`" ;
	}
	
	if ($i{options} eq 'accepted') {
		push @report_sql, "(q.event_accepted='1')" ;
		push @report_results, "Event is Accepted" ;		
	} elsif ($i{options} eq 'completed') {
		push @report_sql, "(q.event_completed='1')" ;
		push @report_results, "Event is Completing" ;		
	} elsif ($i{options} eq 'pending') {
		push @report_sql, "(q.event_pending='1')" ;
		push @report_results, "Event is Pending" ;		
	} elsif ($i{options} eq 'cancelled') {
		push @report_sql, "(q.event_cancelled='1' OR (q.event_expiry IS NOT NULL AND q.event_expiry<'$now_year-$now_mm-$now_dd' AND q.event_accepted<>'1'))" ;
		push @report_results, "Event is Cancelled" ;		
	} elsif ($i{options} eq 'rejected') {
		push @report_sql, "(q.event_rejected='1')" ;
		push @report_results, "Event is Rejecting" ;		
	}
	
	$preferred_title{region_id} = "Region" ;
	$preferred_title{city_id} = "City" ;
	$preferred_title{organisation_ids} = "Venue" ;
	$preferred_title{sport_type_ids} = "Sport Type" ;	
	
	if ($i{sport_type_ids} && $i{sport_type_ids} ne 'all') {
		&db_min_ro('sport_types',"id,name","id='$i{sport_type_ids}'",'','') ;
		push @report_sql, "FIND_IN_SET($i{sport_type_ids},REPLACE(q.sport_type_ids,';',','))" ; 
		push @report_results, "sport_types INCLUDE `$db{sport_types}{$i{sport_type_ids}}{name}`" ;
	}
	
	if ($usertype eq 'analytics_client') {
		push @report_sql, "(q.client_id='$userid')" ;
	}
	
	$report_results_msg = uc join(', ', @report_results) ;

	unless ($report_results_msg) { 
		$error = qq(ENTER AT LEAST ONE SEARCH PARAMETER) ; 
		&report_screen ; 
	} else { 
		$isaved = qq(SELECT WHERE $report_results_msg) ; 
	}
	 
} #------------------------------------------------------------------------------------------

sub report_screen {
		
	&filter_screen  ;

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

sub filter_screen {

	our $lcol = 2 ;
	our $fcol = 5 ;

	my ($set_year,$set_month,$set_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,-42) ; # 6 weeks back

	$set_month  = sprintf("%02s", $set_month) ;
	$set_day    = sprintf("%02s", $set_day) ;

	my $set_ccyy_dd_mm = $set_year . '-' . $set_month . '-' . $set_day ;

	$print_box_content_rows .= &common_min_forms_start('report') ;
    
	# $allow_deselect{customer_name} = 1 ;
	$allow_deselect{options} = 1 ;
	$allow_deselect{sport_type_ids} = 1 ;
	
	my $defualt_customer = 0 ; $defualt_customer = 5 if $usertype ne 'school_manager' ; 
	# &common_min_select_opts('customer_name','customers','name',$defualt_customer,'','',"events='1'") ;
	&common_min_select_opts('customer_name','customers','name','','','',"analytics='1'") ;
	$opts{customer_name} .= qq~<option value='all'>All</option>~ ;
	my $def_val = ($i{customer_name}) ? $i{customer_name} : "all" ;
	$opts{customer_name} =~ s/value='$def_val'/value='$def_val' SELECTED/g ;
	$print_box_content_rows .= &common_min_form_select('customer_name','') ;
	
	$preferred_title{event_from} = 'Event Date From' ;
	
	my $day_of_week = Day_of_Week($now_year,$now_mm,$now_dd) ; 
	
	my ($def_s_year,$def_s_mm,$def_s_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,1-$day_of_week) ;
	my ($def_e_year,$def_e_mm,$def_e_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,7-$day_of_week) ;
	
	$def_s_mm = sprintf("%02d",$def_s_mm) ;
	$def_s_day = sprintf("%02d",$def_s_day) ;
	$def_e_mm = sprintf("%02d",$def_e_mm) ;
	$def_e_day = sprintf("%02d",$def_e_day) ;
	
	$i{start_date_from} = qq~$def_s_year-$def_s_mm-$def_s_day 00:00:00~ unless $i{start_date_from} ;
	$i{start_date_to} = qq~$def_e_year-$def_e_mm-$def_e_day 23:59:59~ unless $i{start_date_to} ;
	
	$preferred_title{start_date_from} = "Event Date/Time From" ;
	$preferred_title{start_date_to} = "Event Date/Time To" ;
	
	$print_box_content_rows .= &common_min_form_datetimepicker('start_date_from',$i{start_date_from},720) ;
	$print_box_content_rows .= &common_min_form_datetimepicker('start_date_to',$i{start_date_to},720) ;
	
	$opts{options} = qq~
		<option value="all">All</option>
		<option SELECTED value="accepted">Accepted</option>
		<option value="completed">Completed</option>
		<option value="pending">Pending</option>
		<option value="cancelled">Cancelled</option>
		<option value="rejected">Rejected</option>
	~ ;
	
	$allow_deselect{options} = 0 ; 
	
	$print_box_content_rows .= &common_min_form_select('options','') ;
	
	&common_min_select_opts('sport_type_ids','sport_types','name','','','','') ;
	
	$preferred_title{sport_type_ids} = "Sport Type" ;
	
	$allow_deselect{sport_type_ids} = 0 ; 
	
	$opts{sport_type_ids} .= qq~<option value="all" SELECTED>All</option>~ ;
	
	$print_box_content_rows .= &common_min_form_select('sport_type_ids','') ;
	
	$print_box_content_rows .= &common_min_forms_end('','','report') ;
	
	local $all_select_ids_string = join(",",@all_select_ids) ; 
	$trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true });~ ; 
	
	&common_min_search_screen ;

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

use event_email ; 
use analytics_event_booking_tabs ;
use common ; 
use common_min ; 
use common_shared ; 
use today ;
use report ;
use xlsxcreator ; 
use csv ; 

1 ;