#!/usr/bin/perl

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

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

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

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

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

&today;

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

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

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

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

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

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

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

our %fixtures_status 	= (1 => 'Coding',2 => 'Ready',3 => 'Complete') ;
# our %coding_provider	= (1 => 'SportVot',2 => 'iSport') ; 
our %footage_type 		= ("s" => "Pixellot","r" => "YouTube") ;
our %service_types	 	= (1 => "Live Coding",2 => "Individual 48 hrs",3 => "Post Coding 24 hrs") ;
our %coding_type 		= ("s" => "Standard","p" => "Premium","i" => "Individual") ;  
our @months 			= ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; 

&page_opts ;

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

# $usertype = 'coding_provider' ;

# if ($username ne 'handre' && $username ne 'rory') {
if ($glod_user_level < 5 && $usertype ne 'coding_provider') {
	print "Please Log in as a Level 5 or Coding Provider User Type!" ;
	exit ;
} 

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

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

exit;

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

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

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

sub update {
	
	my @analytics_field_keys = ("stream_forwarding","stream_key","stream_URL") ; 
	
	&db_min_ro($table,"id,start_date_time,client_id,fixtures_saved_values,analytics_saved_values,cant_charge_client_fixtures,sport_type_ids,total_fixtures,event_accepted,event_name,created_by","",'','') ; 
	
	my %seen_event_id = () ; my %ii = %i ; %i = () ; my %email = () ; 
	
	our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; 
	
	foreach my $_ (keys %ii) {
		
		# next if $_ !~ /update_/ || ($_ =~ /update_/ && !$ii{$_}) ;
		next if $_ !~ /update_/ ;
		
		my @abc = split(/\_/,$_) ;  
		
		my $event_id = $abc[-1] ; # or -2?
		 
		next if $seen_event_id{$event_id}  ;
		
		$seen_event_id{$event_id} = 1 ;
		
		$i{fixtures_saved_values} = qq~~ ;
		$i{analytics_saved_values} = qq~~ ;

		our @fixtures_saved_values_split = split(/\|/,$db{$table}{$event_id}{fixtures_saved_values}) ;
		my @cant_charge_client_split = split(/\;/,$db{$table}{$event_id}{cant_charge_client_fixtures}) ;
		
		my $nr_of_rows = $db{$table}{$event_id}{total_fixtures} ;
		$nr_of_rows = scalar @fixtures_saved_values_split if scalar @fixtures_saved_values_split > $nr_of_rows ;
		
		# my $cant_charge_field = "cant_charge_client_reasons_$event_id" ;
		# $ignore{$cant_charge_field} = 1 ;
	
		my %iii = () ;
	
		for my $row_nr (1 .. 100) {
			
			last if $row_nr > $nr_of_rows ; 
			
			my $input_vals = qq~~ ;
			
			my $upd_field 				= "update_$row_nr\_$event_id" 				;
			my $coding_provider_field 	= "coding_provider_$row_nr\_$event_id" 		;
			my $status_field 			= "status_$row_nr\_$event_id" 				;
			my $moderated_field 		= "moderated_$row_nr\_$event_id" 			;
			my $analyst_field 			= "analyst_$row_nr\_$event_id" 				;
			my $cant_charge_field		= "cant_charge_client_$row_nr\_$event_id"	;
			
			my @parts = split(/\;/,$fixtures_saved_values_split[$row_nr - 1]);

			$i{cant_charge_client_fixtures} .= ($ii{$upd_field}) ? qq~$ii{$cant_charge_field};~ : qq~$cant_charge_client_split[$row_nr-1];~ ;
			
			# $cant_charge_field
			
			# splice(@parts, -2) if @parts >= 2;

			$i{fixtures_saved_values} .= ($ii{$upd_field}) ? join(";",@parts[0..9]) . ';' . qq~$ii{$coding_provider_field};$ii{$status_field};$ii{$moderated_field};$ii{$analyst_field}~ : qq~$fixtures_saved_values_split[$row_nr - 1]~ ;

			$i{fixtures_saved_values} =~ s/;+$//g ;
			$i{fixtures_saved_values} .= qq~|~ ;

			$ignore{$upd_field} 			= 1 ;
			$ignore{$coding_provider_field} = 1 ;
			$ignore{$status_field} 			= 1 ;
			$ignore{$moderated_field} 		= 1 ;
			$ignore{$analyst_field} 		= 1 ;

			foreach (@analytics_field_keys) {
				my $field_key = "$_\_$row_nr\_$event_id" ;
				$i{$field_key} =~ s/\;/\_semi_colon_character_/g ;
				$i{$field_key} =~ s/\|/\_pipe_character_/g ;				
				$i{analytics_saved_values} .= qq~$ii{$field_key};~ ;
				$ignore{$field_key} = 1 ;  
			}
			$i{analytics_saved_values} =~ s/;+$//g ;
			$i{analytics_saved_values} .= qq~|~ ;
			
			if ((!$parts[12] || $parts[12] eq "2") && $ii{$moderated_field} eq "1" && $ii{$upd_field}) {
				$email{$event_id}{$row_nr}{date}		= ($parts[0]) ? $parts[0] : $db{$table}{$event_id}{start_date_time} ;
				$email{$event_id}{$row_nr}{date} 		= &common_min_date_as_string($email{$event_id}{$row_nr}{date}) ;
				$email{$event_id}{$row_nr}{sport}		= ($parts[1]) ? $parts[1] : ($db{$table}{$event_id}{sport_type_ids} !~ /;/) ? $db{$table}{$event_id}{sport_type_ids} : "" ;
				$email{$event_id}{$row_nr}{age_group}	= ucfirst $parts[2] ;
				$email{$event_id}{$row_nr}{coding_type}	= $coding_type{$parts[7]} ;
			}
			
		}

		$i{cant_charge_client_fixtures} =~ s/;+$//g ;
		$i{analytics_saved_values} 	=~ s/\|+$//g ;
		$i{fixtures_saved_values} 	=~ s/\|+$//g  ;

		# $i{fixtures_saved_values} =~ s/([a-zA-Z0-9;])\|+\z/$1/;
		
		$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} 	= (($i{fixtures_saved_values} && $db{$table}{$event_id}{fixtures_saved_values} && $i{fixtures_saved_values} eq $db{$table}{$event_id}{fixtures_saved_values}	) || (!$i{fixtures_saved_values} && !$db{$table}{$event_id}{fixtures_saved_values})) ? 1 : 0 ;
		$ignore{analytics_saved_values} = (($i{analytics_saved_values} && $db{$table}{$event_id}{analytics_saved_values} && $i{analytics_saved_values} eq $db{$table}{$event_id}{analytics_saved_values}) || (!$i{analytics_saved_values} && !$db{$table}{$event_id}{analytics_saved_values})) ? 1 : 0 ;
		$ignore{cant_charge_client_fixtures} = (($i{cant_charge_client_fixtures} && $db{$table}{$event_id}{cant_charge_client_fixtures} && $i{cant_charge_client_fixtures} eq $db{$table}{$event_id}{cant_charge_client_fixtures}) || (!$i{cant_charge_client_fixtures} && !$db{$table}{$event_id}{cant_charge_client_fixtures})) ? 1 : 0 ;
		
		$i{client_id} = $db{$table}{$event_id}{client_id} ;
		$ignore{client_id} = 1 ;		
		
		$i{total_fixtures} = $db{$table}{$event_id}{total_fixtures} ;
		$ignore{total_fixtures} = 1 ;
	
		$i{sport_type_ids} = $db{$table}{$event_id}{sport_type_ids} ;
		$ignore{sport_type_ids} = 1 ;
		
		$i{event_accepted} = $db{$table}{$event_id}{event_accepted} ;
		$ignore{event_accepted} = 1 ;	

		if (!$ignore{cant_charge_client_fixtures} && $i{event_accepted} && $i{client_id} && $i{sport_type_ids}) {
			&analytics_event_booking_tabs_update_credits_used($event_id,'') ;
		}

		&db_min_upd($table,"id='$event_id'") ; 
		
	}
	
	%i = %ii ; 
	
	my $client_sql = join(" OR ", map { "id='$db{$table}{$_}{client_id}'"} keys %{$db{$table}}) ;

	if ($client_sql) {
	
		&db_min_ro('customers','id,name',$client_sql,'','') ; 
	
		&db_min_ro('sport_types','id,name','','','') ; 		
		
		my $users_sql = join(" OR ", map { "id='$db{$table}{$_}{created_by}'"} keys %{$db{$table}}) ;
		
		&db_min_ro('users','id,email',$users_sql,'','') ; 		
		
	}
	
	foreach my $event_id (sort {$a cmp $b} keys %email) {
		foreach my $row_cnt (sort {$a cmp $b} keys %{$email{$event_id}}) {
			
			my $event_name 	= ($db{$table}{$event_id}{event_name}) 						  	? $db{$table}{$event_id}{event_name} 						  	: "N/A" ;
			my $sport 		= ($db{sport_types}{$email{$event_id}{$row_cnt}{sport}}{name})	? $db{sport_types}{$email{$event_id}{$row_cnt}{sport}}{name}	: "N/A" ;
			my $age_group 	= ($email{$event_id}{$row_cnt}{age_group}) 						? $email{$event_id}{$row_cnt}{age_group} 						: "N/A" ;
			my $coding_type = ($email{$event_id}{$row_cnt}{coding_type})		 			? $email{$event_id}{$row_cnt}{coding_type}		 			 	: "N/A" ;
			
			# my $subj = "" ;
			# my $message = "Hi $db{customers}{$db{$table}{$event_id}{client_id}}{name},

			# Your match analysis is now complete and ready for review in your analytics channel.

			# Match details:
			# Date: $email{$event_id}{$row_cnt}{date}
			# Event name: $event_name
			# Sport: $sport 
			# Age group: $age_group
			# Coding type: $coding_type

			# You can now log in and begin reviewing the analysis, clips, and insights with your team.

			# If you have any questions or would like feedback adjusted or expanded, please don’t hesitate to get in touch.

			# Kind regards,
			# AI Sport Africa Analytics
			# $email_analytics" ;

			my $hmsg = qq~Hi Kre8IT,<br><br>Your match analysis is now complete and ready for review in your analytics channel.~;
			my $tmsg = qq~<tr><th colspan='2'>&nbsp;Match Details&nbsp;</th></tr>
			<tr><td>&nbsp;<b>Date:</b>&nbsp;</td><td>&nbsp;$email{$event_id}{$row_cnt}{date}&nbsp;</td></tr>
			<tr><td>&nbsp;<b>Event name:</b>&nbsp;</td><td>&nbsp;$event_name&nbsp;</td></tr>
			<tr><td>&nbsp;<b>Sport:</b>&nbsp;</td><td>&nbsp;$sport&nbsp;</td></tr>
			<tr><td>&nbsp;<b>Age group:</b>&nbsp;</td><td>&nbsp;$age_group&nbsp;</td></tr>
			<tr><td>&nbsp;<b>Coding type:</b>&nbsp;</td><td>&nbsp;$coding_type&nbsp;</td></tr>
			~ ;

			our $display_notif_msg = qq~You can now log in and begin reviewing the analysis, clips, and insights with your team.
			<br><br>
			<a href='https://www.isportsanalysis.com/clubs-video-channel/'>AI Sport Africa Analytics</a>
			<br><br>
			If you have any questions or would like feedback adjusted or expanded, please don’t hesitate to get in touch.
			<br><br>
			AI Sport Africa Analytics
			<br>
			$email_analytics
			</p><p>~ ;
			
			# <a href='https://www.isportsanalysis.com/clubs-video-channel/'><img src='https://$ENV{SERVER_NAME}/img/isports.jpg'><br>AI Sport Africa Analytics</a>
			
			# &db_min_ro('users','id,email',"id='25'",'','') if $event_id eq '1001' ; 		
			
			# &common_send_smtp_mail('',$db{users}{$db{$table}{$event_id}{created_by}}{email},'','',"Match Analysis Event $event_id Fixture $row_cnt",$message) if $event_id eq '1001' ;
			# &common_send_smtp_mail('',$db{users}{$db{$table}{$event_id}{created_by}}{email},$email_analytics,'',"Match Analysis Event $event_id Fixture $row_cnt",$message) if $event_id ne '1001' ;
			&common_send_smtp_mail('',$db{users}{$db{$table}{$event_id}{created_by}}{email},$email_analytics,'',"Match Analysis Event $event_id Fixture $row_cnt",$hmsg,$tmsg,'html') ;
		} 
	}
	
# &common_send_smtp_mail('','handre@kre8it.co.za','','',"Hello OWrld",'Hello World!') ;

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

# sub analytics_event_booking_tabs_update_credits_used {
	
	# my ($id,$id2) = @_ ; 

	# my %credits_used = () ; my $row_cnt = 0 ;	
	
	# my @cnt_charge = split(/\;/,$db{$table}{$id}{cant_charge_client_fixtures}) ;

	# if ($db{$table}{$id}{client_id}) {
		# foreach my $fixture_row (@fixtures_saved_values_split) {
			# $row_cnt++ ;
			# last if $row_cnt > $db{$table}{$id}{total_fixtures} ;
			# my @fixtures_saved_values_split_2 = split(/\;/,$fixture_row) ;
			# my $sport_id = ($db{$table}{$id}{sport_type_ids} !~ /;/) ? $db{$table}{$id}{sport_type_ids} : $fixtures_saved_values_split_2[1] ;

			# next unless $sport_id ;
			
			# $credits_used{previous}{premium}{$db{$table}{$id}{client_id}}{$sport_id} 	+= 1 if $fixtures_saved_values_split_2[7] eq 'p' && !$cnt_charge[$row_cnt-1] ;
			# $credits_used{previous}{standard}{$db{$table}{$id}{client_id}}{$sport_id} 	+= 1 if $fixtures_saved_values_split_2[7] eq 's' && !$cnt_charge[$row_cnt-1] ;
			# $credits_used{previous}{individual}{$db{$table}{$id}{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 'i' && !$cnt_charge[$row_cnt-1] ;
		# }
	# }

	# if ($i{client_id}) {

		# @fixtures_saved_values_split = split(/\|/,$i{fixtures_saved_values}) ;
		# $row_cnt = 0 ;
		# @cnt_charge = split(/\;/,$i{cant_charge_client_fixtures}) ;
		
		# foreach my $fixture_row (@fixtures_saved_values_split) {

			# $row_cnt++ ;
			# last if $row_cnt > $i{total_fixtures} ;
			# my @fixtures_saved_values_split_2 = split(/\;/,$fixture_row) ;
			
			# my $sport_id = ($i{sport_type_ids} !~ /;/) ? $db{$table}{$id}{sport_type_ids} : $fixtures_saved_values_split_2[1] ;

			# next unless $sport_id ;

			# $credits_used{new}{premium}{$i{client_id}}{$sport_id} 		+= 1 if $fixtures_saved_values_split_2[7] eq 'p'	&& !$cnt_charge[$row_cnt-1] ;
			# $credits_used{new}{standard}{$i{client_id}}{$sport_id} 		+= 1 if $fixtures_saved_values_split_2[7] eq 's'	&& !$cnt_charge[$row_cnt-1] ;
			# $credits_used{new}{individual}{$i{client_id}}{$sport_id} 	+= 1 if $fixtures_saved_values_split_2[7] eq 'i'	&& !$cnt_charge[$row_cnt-1] ;

		# }
		
		# my %seen = () ; 
	
	# }
	
	# $seen{client}{$i{client_id}} = 1 if $i{client_id} ; 
	# $seen{client}{$db{$table}{$id}{client_id}} = 1 if $db{$table}{$id}{client_id} ; 

	# foreach (split(/\;/,$db{$table}{$id}{sport_type_ids})) {
		# $seen{sport}{$_} = 1 if $_ ; 
	# }
	
	# if ($i{sport_type_ids}) {
		# foreach (split(/\;/,$i{sport_type_ids})) {
			# $seen{sport}{$_} = 1 if $_ ; 
		# }
	# }
	
	# my $sport_sql 	= join(" OR ",map{"sport_type_id='$_'"} keys %{$seen{sport}}) ; 
	# my $client_sql 	= join(" OR ",map{"client_id='$_'"} keys %{$seen{client}}) ; 
	# my $id_sql 		= ($id2) ? "analytics_event_id='$id2'" : ($id) ? "analytics_event_id='$id'" : "" ; 
	
	# my @sql_where_arr = () ; 
	# push @sql_where_arr,"($sport_sql)" 	if $sport_sql ;
	# push @sql_where_arr,"($client_sql)" if $client_sql ;
	# push @sql_where_arr,$id_sql 	if $id_sql ;
	
	# my $sql_where = join(" AND ",@sql_where_arr) ;

	# &db_min_ro('credits_used','*',$sql_where,'','') ; my %exists = () ; 

	# my %db_credits_used = %db ; 

	# foreach my $_id (keys %{$db{credits_used}}) {
		# $exists{$db{credits_used}{$_id}{sport_type_id}}{$db{credits_used}{$_id}{client_id}} = 1 ; 
	# }
	
	# my $new_id = 0 ; 
	
	# foreach my $client_id (sort {$a <=> $b} keys %{$seen{client}}) {
		# foreach my $sport_id (sort {$a <=> $b} keys %{$seen{sport}}) {
			# unless ($exists{$sport_id}{$client_id}) {
				# if ($new_id) {
					# $new_id++ ;
				# } else {
					# $new_id = &db_min_get_max('credits_used','id') ; 
				# }

				# $db_credits_used{credits_used}{$new_id}{sport_type_id} = $sport_id ;
				# $db_credits_used{credits_used}{$new_id}{client_id} = $client_id ;
				
			# }
		# }
	# } 

	# my %hidden_old = %hidden ; 
	# %hidden = () ; 
	# my %ignore_old = %ignore ; 
	# %ignore = () ;
	# my %ij = %i ;
	
	# # cant_charge_client_fixtures_1
	# foreach my $_id (keys %{$db_credits_used{credits_used}}) {

		# my $premium_credits 	= ($db_credits_used{credits_used}{$_id}{premium_credits_used}) 		? $db_credits_used{credits_used}{$_id}{premium_credits_used} 	: 0 ;
		# my $standard_credits 	= ($db_credits_used{credits_used}{$_id}{standard_credits_used})  	? $db_credits_used{credits_used}{$_id}{standard_credits_used}  	: 0 ;
		# my $individual_credits 	= ($db_credits_used{credits_used}{$_id}{individual_credits_used}) 	? $db_credits_used{credits_used}{$_id}{individual_credits_used} : 0 ;
		
		# my $sport_id			= $db_credits_used{credits_used}{$_id}{sport_type_id} ;
		# my $client_id			= $db_credits_used{credits_used}{$_id}{client_id} ;
		
		# %i = () ; 

		# $i{premium_credits_used} 	= $credits_used{new}{premium}{$client_id}{$sport_id} ;
		# $i{standard_credits_used}	= $credits_used{new}{standard}{$client_id}{$sport_id} ;
		# $i{individual_credits_used} = $credits_used{new}{individual}{$client_id}{$sport_id} ;
		
		# $i{premium_credits_used} 	= 0 unless $i{premium_credits_used} ; 
		# $i{standard_credits_used} 	= 0 unless $i{standard_credits_used} ; 
		# $i{individual_credits_used} = 0 unless $i{individual_credits_used} ; 
		
		# $ignore{premium_credits_used} 		= ($credits_used{new}{premium}{$client_id}{$sport_id} 		ne $premium_credits) 	? 0 : 1 ; 
		# $ignore{standard_credits_used} 		= ($credits_used{new}{standard}{$client_id}{$sport_id} 		ne $standard_credits) 	? 0 : 1 ; 
		# $ignore{individual_credits_used} 	= ($credits_used{new}{individual}{$client_id}{$sport_id}	ne $individual_credits) ? 0 : 1 ; 

		# if (!$exists{$sport_id}{$client_id} && ($i{premium_credits_used} || $i{standard_credits_used} || $i{individual_credits_used}) && $ij{event_accepted}) {
			# $i{id} = "$_id" ;
			# $i{sport_type_id} = "$sport_id" ;
			# $i{client_id} = "$client_id" ;
			# $i{analytics_event_id} = ($id2) ? "$id2" : ($id) ? "$id" : "0" ; 
			# &db_min_insert('credits_used') ; 
		# } elsif ($exists{$sport_id}{$client_id} && ($i{premium_credits_used} || $i{standard_credits_used} || $i{individual_credits_used}) && $ij{event_accepted}) {
			# &db_min_upd('credits_used',"id='$_id'") ; 
		# } elsif ($exists{$sport_id}{$client_id} && ((!$i{premium_credits_used} && !$i{standard_credits_used} && !$i{individual_credits_used}) || !$ij{event_accepted})) {
			# &db_min_delete('credits_used',"id='$_id'") ; 
		# }
	# }
	
	# %ignore = %ignore_old ;
	# %hidden = %hidden ;
	# %i = %ij ; 

# }

sub report_ifields {
		
	if ($i{start_date_from} && $i{start_date_to}) {
		push @report_sql, "	(('$i{start_date_from}' <= q.start_date_time AND q.start_date_time <= '$i{start_date_to}') OR ('$i{start_date_from}' <= q.end_date_time AND q.end_date_time <= '$i{start_date_to}' AND q.end_date_time IS NOT NULL) OR (q.start_date_time <= '$i{start_date_from}' AND '$i{start_date_to}' <= q.end_date_time AND q.end_date_time IS NOT NULL) OR (q.start_date_time <= '$i{start_date_from}' AND q.end_date_time IS 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, " (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 ($i{service_type_id} && $i{service_type_id} ne 'all') {
		# push @report_sql, "(service_type_id = '$i{service_type_id}')" ;
		push @report_results, "Service Type is `$service_types{$i{service_type_id}}`" ;		
	}
	
	if ($i{coding_provider_id} && $i{coding_provider_id} ne 'all') {
		# push @report_sql, "(fixtures_saved_values REGEXP ';$i{coding_provider_id};[0-9a-z]+\\|' OR fixtures_saved_values REGEXP ';$i{coding_provider_id};[0-9a-z]+\$')" ;
		# fixtures_saved_values REGEXP '(^|\\|)([0-9a-z]+;){9}$i{coding_provider_id}(;[0-9]+;[0-9]+|;;[0-9]+|;[0-9]+)(\\||\$)'
		# push @report_sql, "
			# (fixtures_saved_values REGEXP '(^|\\|)([0-9a-z]+;|;){9}')
		# " ;
		
		push @report_results, "Coding Provider is `$coding_type{$i{coding_provider_id}}`" ;		
	}
	
	if ($usertype eq 'analytics_client') {
		push @report_sql, "(q.client_id='$userid')" ;
	}
	
	our $srch_where_sql = join(" AND ",@report_sql) ;

	$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 load_search_vars {
	
	
	
} #------------------------------------------------------------------------------------------

sub list_screen {
	
	$print_box_content_rows .= &common_min_forms_start("$lcpage") ;
	
	our $set_up_groups = 1 ; 
	
	&load_list_vars("$srch_where_sql") ;

	$fcol = 12 ; 
	
	my $report = 1 ; 
	
	our $xlsxdir = "fixtures_report" ; 
	
	our $xlsxreportname = "Fixtures_Report" ; 
 
	my $date = &common_write_date_interval($i{date_from},$i{date_to}) ;
	
	our $xlsx_title_heading = "Fixtures Report $date" ;
	
	&build_table_and_or_excel(1) ; 

	$fnsortorder = 'asc' ;
	
	&common_min_extra_crumb("$lcpage","Search Screen") ;
 
	$trigger_jquery_raw .= qq~
		\$("#savebutt").click(function() {
			\$("#$lcpage-form").submit() ;
		}) ;
	~ ;
	
} #------------------------------------------------------------------------------------------

sub build_table_and_or_excel {
	
	my ($report) = @_ ;
	# $custom_header{$headers[13]} .= qq~<a href="#" class='btn btn-primary btn-xs' style='position:relative;padding:20px 20px 0px 0px;' title=\"Can't Charge Client!\" data-toggle='tooltip' data-placement='left'><i class='glyphicon glyphicon-info-sign' style='position:absolute;margin-top:2.5px;right:3.5px;'></i></a>~ ;
	
	our @sql_col_display = ("nr","start_date_time","sport","age_group","team","home_team","ht_colour","away_team","coding_type","footage_type","service_type","stream_forwarding","stream_key","stream_URL","coding_provider","status","moderated") ; 
	
	# push @sql_col_display,"analyst" if $usertype eq 'coding_provider' ;
	push @sql_col_display,"analyst" ;
	
	$custom_header{"analyst"} = qq~ANALYST&nbsp;&nbsp;<a href=javascript:dlgMdl('$useropts{'scripts'}/dialog/add_fixtures_analyst.pl?add&&Home','Add&nbsp;Fixtures&nbsp;Analyst','','medium-dialog'); class='btn btn-primary btn-xs' style='padding:0px 2px 0px 3px;margin-top:0px;position:absolute;' title='Add Fixtures Analyst' data-toggle='tooltip' data-placement='top'><i class='glyphicon glyphicon-plus' style='padding:0;margin-top:0px;top:0px;'></i></a>~ ;
	
	$custom_header{"cant_charge_client"} = qq~<a href="#" class='btn btn-primary btn-xs' style='position:relative;padding:20px 20px 0px 0px;' title=\"Can't Charge Client!\" data-toggle='tooltip' data-placement='left'><i class='glyphicon glyphicon-info-sign' style='position:absolute;margin-top:2.5px;right:3.5px;'></i></a>~ ;
	
	&report_xlsx_export_header("$xlsxreportname",$xlsxdir,'',$xlsx_title_heading) ;
	
	push @sql_col_display,"cant_charge_client" ;
	
	push @sql_col_display,"update" ;
	
	my $nr_of_cols = scalar @sql_col_display ;
	 
	my @rev_sql_col_display = reverse @sql_col_display ;
	
	foreach (@rev_sql_col_display) { $lastchild++ ; $last_child{$_} = $lastchild ; } # &common_debug("last-child : $_ [$last_child{$_}]");	
	
	$xlsxrow-- ;
	
	my $cali_cnt = 0 ;  my $found_editable = 0 ; my @all_select_ids = () ; 
	
	$format84 -> set_align("center") ; 
 
	my $start_date_input = $i{start_date_from} ;
	
	$start_date_input =~ s/://g ;
	$start_date_input =~ s/-//g ;
	$start_date_input =~ s/ //g ; 
	
	my $end_date_input = $i{start_date_to} ;
	
	$end_date_input =~ s/://g ;
	$end_date_input =~ s/-//g ;
	$end_date_input =~ s/ //g ;
 
	my %seen_analytics_id = () ; 
 
	# foreach my $id (sort {$db{$table}{$a}{date_from} cmp $db{$table}{$b}{date_from}} keys %{$db{$table}}) {
	use URI::Escape;
	
	foreach my $id (sort { $b <=> $a } keys %{$db{$table}}) {
		
		my @fixtures_split = split(/\|/,$db{$table}{$id}{fixtures_saved_values}) ; 
		
		my @analytics_split = split(/\|/,$db{$table}{$id}{analytics_saved_values}) ; 
		
		my @sport_type_ids = split(/\;/,$db{$table}{$id}{sport_type_ids}) ;
		
		my @cant_charge_client_fixtures_arr = split(/\;/,$db{$table}{$id}{cant_charge_client_fixtures}) ;
		
		my @cant_charge_client_reasons_arr = split(/\:\|;/,$db{$table}{$id}{cant_charge_client_reasons}) ;
		
		my $row_cnt = - 1 ; 
		
		# foreach my $row (@fixtures_split) {
		foreach my $row_nr (1 .. $db{$table}{$id}{total_fixtures}) {
			
			my @fixtures_split_2 = split(/\;/,$fixtures_split[$row_nr - 1]) ; 
			
			my @analytics_split_2 = split(/\;/,$analytics_split[$row_nr - 1]) ; 
			 
			$row_cnt++ ;
				
			next if $i{coding_provider_id} 	&& $i{coding_provider_id} 	ne 'all' && $fixtures_split_2[10] ne $i{coding_provider_id} ;
			next if $i{service_type_id} 	&& $i{service_type_id} 		ne 'all' && (($fixtures_split_2[9] && $fixtures_split_2[9] ne $i{service_type_id}) || (!$fixtures_split_2[9] && $db{$table}{$id}{service_type_id} ne $i{service_type_id})) ;
			
			my $date_val = ($fixtures_split_2[0]) ? $fixtures_split_2[0] : $db{$table}{$id}{start_date_time} ;
			
			$date_val =~ s/://g ;
			$date_val =~ s/-//g ;
			$date_val =~ s/ //g ;			
			
			next if $date_val < $start_date_input || $date_val > $end_date_input ;
			
			$cali_cnt++ ;
			
			my $col_cnt = -2 ; 
			
			# last if $db{$table}{$id}{total_fixtures} eq $row_cnt ;
			
			$xlsxcol = 0 ;
			
			our $default_javascript = qq~~ ;
			
			$seen_analytics_id{$id} = 1 ;
			
			foreach (@sql_col_display) { 
				
				# &common_debug("1. XLSX >>> $_") if !$report ;
				
				$nr_of_cols_cnt-- ; 
				
				next unless $_ ; # blank for the buttons column
				
				my $formatting 	= $format84 ;
				my $val        	= $db{$table}{$id}{$_} ;
				my $val_xlsx	= 'MUSTBEBLANK'  ;
				my $align      	= qq~ class="dt-center"~ ; 
				my $nowrap     	= '' ;
				my $cell_id 	= '' ;
				
				# &common_debug("2. XLSX >>> val_min=$val_min") if !$report ;
				
				my $sys_day_cnt = $cnt{$event_sys_id}{$id} ;
				
				$col_cnt++ ;
				
				my $field = "" ; my $default_val = ($_ eq 'stream_forwarding') ? $analytics_split_2[0] : ($_ eq 'stream_key') ? $analytics_split_2[1] : ($_ eq 'stream_URL') ? $analytics_split_2[2] : $fixtures_split_2[$col_cnt] ; my $only_display_val = 0 ; my $background_color = "#424949" ; 	my $default_val_is_saved = ($default_val) ? 1 : 0 ;
				
# our %fixtures_status 	= (1 => 'Pending',2 => 'Booked',3 => 'Completed') ;
# our %coding_provider	= (1 => 'SportVot',2 => 'iSport') ; 
# our %footage_type 		= ("s" => "SSS","r" => "Raw") ;
# our %service_types	 	= (1 => "Live Coding",2 => "Post Coding 12 hrs",3 => "Post Coding 24 hrs") ;
# our %coding_type 		= ("s" => "Standard","p" => "Premium") ;  
# our @months 			= ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; 
				 
				if ($_ eq 'nr') {
					$val = &common_min_get_event_quote_button($id,$table,'analytics-event-bookings') ;  
					$val .= qq~<span title="Event Quote : $db{$table}{$id}{event_quote_id}" data-toggle="tooltip" data-placement="top"><a href="javascript:editMinItem('$db{$table}{$id}{event_quote_id}','event-quotes');" style="color:black;"><i class="glyphicons glyphicons-paired icon-white"></i></a></span>~ if $db{$table}{$id}{event_quote_id} > 0 && $db{$table}{$id}{event_quote_id} ;
					$val_xlsx = $id ;
					$nowrap = 'nowrap' ;
				} elsif ($_ eq "start_date_time") {
					$val = ($fixtures_split_2[0]) ? &common_min_date_as_string($fixtures_split_2[0]) : &common_min_date_as_string($db{$table}{$id}{start_date_time}) ; 
					$nowrap = 'nowrap' ;
				} elsif ($_ eq "sport") {
					$val = ($fixtures_split_2[1] && $db{$table}{$id}{sport_type_ids} =~ /\b$fixtures_split_2[1]\b/) ? $db{sport_types}{$fixtures_split_2[1]}{name} : ($db{$table}{$id}{sport_type_ids} !~ /;/ && !$fixtures_split_2[1]) ? $db{sport_types}{$db{$table}{$id}{sport_type_ids}}{name} : "" ;
				} elsif ($_ eq "age_group") {
					$val = ucfirst $fixtures_split_2[2] ;
				} elsif ($_ eq "team") {
					$val = uc $fixtures_split_2[3] ;
				} elsif ($_ eq "home_team") {
					$val = $db{teams}{$fixtures_split_2[4]}{name} ; 
				} elsif ($_ eq "ht_colour") {
					$val = $db{analytics_ht_colors}{$fixtures_split_2[5]}{name} ; 
				} elsif ($_ eq "away_team") {
					$val = $db{teams}{$fixtures_split_2[6]}{name} ; 
				} elsif ($_ eq "coding_type") {
					$val = $coding_type{$fixtures_split_2[7]} ;
				} elsif ($_ eq "footage_type") {
					$val = $footage_type{$fixtures_split_2[8]} ;
				} elsif ($_ eq "service_type") {
					$val = ($fixtures_split_2[9]) ? $service_types{$fixtures_split_2[9]} : $service_types{$db{$table}{$id}{service_type_id}} ;
					$nowrap = 'nowrap' ;
				} elsif ($_ eq 'stream_forwarding') {
					$col_cnt-- ;
					$background_color = ($default_val eq '1') ? "rgb(46,204,113)" : ($default_val eq '2') ? "rgb(249,13,13)" : "" ;
					$opts{"stream_forwarding_$row_nr\_$id"} = qq~<option value='1'>Yes</option><option value='2'>No</option>~ ;
					$val = &common_min_table_select("stream_forwarding_$row_nr\_$id",$default_val,$only_display_val,$cali_cnt,$last_child{$_},$background_color,$default_val,$_) ; 
					$val_xlsx = ($default_val eq '1') ? 'Yes' : ($default_val eq '2') ? 'No' : '' ;
					$val = qq~<span style='display:none;'>Do not edit this hidden input below!</span><input type='hidden' name='stream_forwarding_$row_nr\_$id' value='$default_val'>~ . $val_xlsx if $usertype eq 'coding_provider' ;
				} elsif ($_ eq 'stream_key') {
					$col_cnt-- ;
					my $hide_text = ($analytics_split_2[0] eq '2') ? 1 : 0 ;
					$default_val =~ s/\_semi_colon_character_/\;/g ; 
					$default_val =~ s/\_pipe_character_/\|/g ; 
					my $default_is_saved = ($default_val && $analytics_split_2[0] ne '2') ? 1 : 0 ;
					$readonly{"stream_key_$row_nr\_$id"} = "READONLY" if $usertype eq 'coding_provider' ;
					$val = qq~<span style='display:none;'>Do not edit this teaxtarea below if readonly!</span>~ . &common_min_table_textarea("stream_key_$row_nr\_$id",$default_val,'',$cali_cnt,$last_child{$_},$background_color,$default_is_saved,'','',$hide_text) ;
					$val_xlsx = $default_val ;
				} elsif ($_ eq 'stream_URL') {
					$col_cnt-- ;
					my $hide_text = ($analytics_split_2[0] eq '2') ? 1 : 0 ;
					$default_val =~ s/\_semi_colon_character_/\;/g ; 
					$default_val =~ s/\_pipe_character_/\|/g ; 
					my $default_is_saved = ($default_val && $analytics_split_2[0] ne '2') ? 1 : 0 ;
					$readonly{"stream_URL_$row_nr\_$id"} = "READONLY" if $usertype eq 'coding_provider' ;
					$val = qq~<span style='display:none;'>Do not edit this teaxtarea below if readonly!</span>~ . &common_min_table_textarea("stream_URL_$row_nr\_$id",$default_val,'',$cali_cnt,$last_child{$_},$background_color,$default_is_saved,'','',$hide_text) ;
					$val_xlsx = $default_val ;
				} elsif ($_ eq 'coding_provider') {
					$field = "coding_provider_$row_nr\_$id" ; 
					$opts{$field} = ($default_val) ? qq~<option value='$default_val' SELECTED>$db{users}{$default_val}{name} [$db{users}{$default_val}{username}]</option>~ : $opts{coding_provider_id} ;
					$dont_allow_deselect_in_table{$field} = 1 if $usertype eq 'coding_provider' || $default_val ;
					$val = &common_min_table_select($field,$default_val,$only_display_val,$cali_cnt,$last_child{$_},$background_color,$default_val) ; 
					$val_xlsx = "$db{users}{$default_val}{name} [$db{users}{$default_val}{username}]" ;
				} elsif ($_ eq 'status') {
					
					# if ($default_val eq '1') { #calibrating
						# $background_color = "#FFA500" ; orange
						# $formatting = $format89 ;											
					# } elsif ($default_val eq '2') { #cancelled
						# $background_color = "#AD0502" ;		red
						# $formatting = $format90 ;
					# } elsif ($default_val  eq '3') { #done
						# $background_color = "#2ECC71" ;		greeen
						# $formatting = $format88 ;											
					# } elsif ($default_val eq '4') { 
						# $background_color = "#424949" ;											
					# }
					
					# rgb(81, 203, 242) blue

					if ($default_val eq '1') {
						$background_color = "#FFA500" ;									
					} elsif ($default_val eq '2') { # 
						$background_color = "rgb(81, 203, 242)" ;		
					} elsif ($default_val eq '3') { 
						$background_color = "#2ECC71" ;											
					}
					$field = "status_$row_nr\_$id" ; 
					$opts{$field} = $opts{status_id} ;	 
					
					# 1;;;open;a;7495;1;6684;s;s;s;s|2;;;u19;b;845;1;778;p;r;p;r|3;2025-06-18 06:00:00;8;u17;c;54;1;3975;s;s;s;s
					$val = &common_min_table_select($field,$default_val,$only_display_val,$cali_cnt,$last_child{$_},$background_color,$default_val,$_) ; 
					$val_xlsx = $fixtures_status{$default_val} ;
				} elsif ($_ eq 'analyst') {
					
					# $opts{"analyst_$row_nr\_$id"} = $opts{analyst} ;
					# if ($usertype ne 'coding_provider') {
						 
					if ($fixtures_split_2[10]) {
						$opts{"analyst_$row_nr\_$id"} = $opts{$fixtures_split_2[10]}{analyst} ;
					} else {
						$opts{"analyst_$row_nr\_$id"} = qq~~ ;
					}
					
					$opts{"analyst_$row_nr\_$id"} =~ s/value='$default_val'/value='$default_val' SELECTED/g if $default_val ;
					
					my $ab = "analyst_$row_nr\_$id" ;

					$val = &common_min_table_select("analyst_$row_nr\_$id",$default_val,$only_display_val,$cali_cnt,$last_child{$_},$background_color,$default_val) ; 
					$val_xlsx = $db{all_fixtures_analysts}{$default_val}{name} ;
					
				} elsif ($_ eq 'moderated') {
					
				# $background_color = (($_ eq 'status' || $_ eq 'equipment_checked') && $default_vals[$col_cnt] eq '1') ? "rgb(46,204,113)" : (($_ eq 'status' || $_ eq 'equipment_checked') && $default_vals[$col_cnt] eq '2') ? "rgb(249,13,13)" : ($_ eq 'status' && $default_vals[$col_cnt] eq '3') ? "rgb(255,153,0)" : '' ;
					$background_color = ($default_val eq '1') ? "rgb(46,204,113)" : ($default_val eq '2') ? "rgb(249,13,13)" : "" ;
					$opts{"moderated_$row_nr\_$id"} = $opts{moderated} ;
					$val = &common_min_table_select("moderated_$row_nr\_$id",$default_val,$only_display_val,$cali_cnt,$last_child{$_},$background_color,$default_val,$_) ; 
					$val_xlsx = ($default_val eq '1') ? "Yes" : ($default_val eq '2') ? "No" : "" ;
				} elsif ($_ eq 'cant_charge_client') {
					# $val = &common_min_table_checkbox("cant_charge_client_$row_nr\_$id") ; 
					$nowrap = 'nowrap' ;
					# $align = "class='dt-left'" ;
					my $checked = ($cant_charge_client_fixtures_arr[$row_cnt]) ? 'CHECKED' : '' ; 
					$val = qq~<input id="checkboxCant_charge_client_$row_nr\_$id" name="cant_charge_client_$row_nr\_$id" data-no-uniform="true" type="checkbox" value="1" tabindex="$tindex" $checked>~ ;
					my $reason_url = $cant_charge_client_reasons_arr[$row_cnt] ;
					$reason_url =~ s/\R/\_new_line_character_/g ;
					$reason_url =~ s/ /\&nbsp;/g ;
					
					$disp_reason = ($cant_charge_client_fixtures_arr[$row_cnt]) ? "" : "display:none;" ;
					$val .= qq~&nbsp;&nbsp;<a href=javascript:dlgMdl('$useropts{scripts}/dialog/add_fixtures_charge_free_table_reason.pl?add&&$id&$row_nr&$reason_url&1','Add&nbsp;Reason','','medium-dialog'); class='btn btn-primary btn-xs' style='position:relative;padding:20px 20px 0px 0px;$disp_reason' title='$cant_charge_client_reasons_arr[$row_cnt]' data-toggle='tooltip' data-placement='left' id='reason_icon_$row_nr\_$id'><i class='glyphicon glyphicon-question-sign' style='position:absolute;margin-top:2.5px;right:3.5px;'></i></a>~ if $cant_charge_client_reasons_arr[$row_cnt] ;	
					$default_javascript .= ($cant_charge_client_fixtures_arr[$row_cnt]) ? qq~"checkboxCant_charge_client_$row_nr\_$id":"true",~ : qq~"checkboxCant_charge_client_$row_nr\_$id":"false",~ ;
					$cell_id = "id='c_cant_charge_client_$row_nr\_$id'" ;
				} elsif ($_ eq 'update') {
					$val = &common_min_table_checkbox("update_$row_nr\_$id") ; 
					$default_javascript =~ s/,+$//g  ;
					if ($default_javascript) {
						push @default_javascript_by_id, qq~"$row_nr\_$id":{$default_javascript}~ ;
						my $update_ids_str = "#selectStatus_$row_nr\_$id,#selectCoding_provider_$row_nr\_$id,#selectModerated_$row_nr\_$id,#selectStream_forwarding_$row_nr\_$id,#textareaStream_key_$row_nr\_$id,#textareaStream_URL_$row_nr\_$id,#checkboxCant_charge_client_$row_nr\_$id" ;
						# $update_ids_str .= ",#selectAnalyst_$row_nr\_$id" if $usertype eq 'coding_provider'  ;
						$update_ids_str .= ",#selectAnalyst_$row_nr\_$id"    ;
						push @all_update_field_ids,$update_ids_str ;
					}
					
				}
		
				$print_tbody .= qq~<td $align $nowrap $cell_id>$val</td>~ if $report ; 
				
				$val_xlsx = $val if $val_xlsx eq 'MUSTBEBLANK' ;
				
				&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$formatting) if $val_xlsx && $_ ne 'update' ;
				$xlsxcol++ ;
			}
				
			$print_tbody .= qq~</tr>~ if $report ;

			$xlsxrow++ ; 	
	
		}
	}
	
	&common_shared_build_select_primary_jquery ;
	
	foreach my $id (%seen_analytics_id) {
		next if $id eq '1' ;	
		$db{$table}{$id}{cant_charge_client_reasons} =~ s/\R/\_new_line_character_/g ;
		$db{$table}{$id}{cant_charge_client_reasons} =~ s/ /\&nbsp;/g ; 
		$print_box_content_rows .= qq~<input name='cant_charge_client_reasons_$id' value='$db{$table}{$id}{cant_charge_client_reasons}' type='hidden'>~ ;
	}
	
	$trigger_jquery_raw .= qq~
	
		\$("#$useropts{table_id}").on("change","[id^='selectCoding_provider_']", async function (event) {
			
			let row_nr = get_row_nr (this.id,2) ;  
			let analysts = "[]" ;
			console.log("row_nr : "+row_nr) ; 
			
			if (!\$("#selectCoding_provider_"+row_nr).val()) {
				\$("#selectAnalyst_"+row_nr).val('').trigger("chosen:updated") ;
				clearSelect(\$("#selectAnalyst_"+row_nr));				
			} else {
				let url_get_analysts = "$useropts{scripts}/get/get_analyst_from_coding_provider.pl?coding_provider_id="+\$("#selectCoding_provider_"+row_nr).val() ; 
				console.log("url_get_analysts : "+url_get_analysts) ; 
				analysts = await fetchJSON(url_get_analysts) ;			
				clearSelect(\$("#selectAnalyst_"+row_nr));		
				populateSelect(\$("#selectAnalyst_"+row_nr),analysts,r => r.name);				
			}
			
		}) ; 

		\$("#$useropts{table_id}").on("click","[id^='checkboxCant_charge_client']", function () {
				let analytics_id = get_row_nr(this.id,1) ;
				let row_nr = get_row_nr(this.id,2) ;
				row_nr = row_nr.split('_')[0];
				if (\$("#"+this.id).is(":checked")) {
					if (\$("#reason_icon_"+row_nr+"_"+analytics_id).html()) {
						\$("#reason_icon_"+row_nr+"_"+analytics_id).css("display","") ;
					} else {
						dlgMdl("$useropts{scripts}/dialog/add_fixtures_charge_free_table_reason.pl?add&&"+analytics_id+"&"+row_nr+"&&1","Add Reason",'','medium-dialog') ;  
					}
				} else {
					\$("#reason_icon_"+row_nr+"_"+analytics_id).hide() ;
				}
			}) ;

	~ ; 
	
			# \$("#itv-table tr th:nth-last-child(1)").css("width","0%") ;
			# \$("#itv-table tr th:nth-last-child(1)").css("display","none") ;	
		
	my $all_select_ids_string = join(",",@all_select_ids) ; 
	
	# $trigger_jquery_raw .= qq~\$('[data-toggle="tooltip"]').tooltip({ container: 'body' });~ ;
	
	$trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({allow_single_deselect:true});~ ;
	# if ($usertype eq 'coding_provider') {
		&common_min_table_select_jquery("#$useropts{table_id} td:nth-last-child($last_child{stream_forwarding}),#$useropts{table_id} td:nth-last-child($last_child{analyst}),#$useropts{table_id} td:nth-last-child($last_child{status}),#$useropts{table_id} td:nth-last-child($last_child{moderated}),#$useropts{table_id} td:nth-last-child($last_child{coding_provider})") ;		
	# } else {
		# &common_min_table_select_jquery("#$useropts{table_id} td:nth-last-child(7),#$useropts{table_id} td:nth-last-child(4),#$useropts{table_id} td:nth-last-child(3),#$useropts{table_id} td:nth-last-child(2)") ;		
	# }

	&common_min_table_update_checkbox_col("2") ;

	$worksheet{$ws}->set_column(0,0,10) ;
	$worksheet{$ws}->set_column(1,17,20) ;
	
	&report_xlsx_export_footer('L',15,$xlsxdir) ;
# "#$useropts{table_id} tr:eq(???) td:nth-last-child(6)" ;

	# my $key_col = ($usertype ne 'coding_provider') ? 6 : 7 ;
	# my $url_col = ($usertype ne 'coding_provider') ? 5 : 6 ;
	my $key_col = 7 ;
	my $url_col = 6 ;

	$trigger_jquery_raw .= qq~
	
		\$("#$useropts{table_id}").on("change","[id^='selectStream_forwarding_']", function () {
			
			let row_nr = get_row_nr (this.id,2) ;  
		
			let \$tr = \$(this).closest("tr");

			if ((\$(this).val() == '1' || !\$(this).val()) && \$("#textareaStream_key_"+row_nr).is(":hidden")) {
				\$("#textareaStream_key_"+row_nr).show() ;
				if (\$("#textareaStream_key_"+row_nr).val()) {
					\$tr.find("td:nth-last-child($key_col)").css("background-color","rgb(66,73,73)") ;
				}
				\$("#textareaStream_URL_"+row_nr).show() ;		
				if (\$("#textareaStream_URL_"+row_nr).val()) {
					\$tr.find("td:nth-last-child($url_col)").css("background-color","rgb(66,73,73)") ;
				}				
			} else if (\$(this).val() == '2' && !\$("#textareaStream_key_"+row_nr).is(":hidden")) {
				\$("#textareaStream_key_"+row_nr).hide() ;
				if (\$("#textareaStream_key_"+row_nr).val()) {
					\$tr.find("td:nth-last-child($key_col)").css("background-color","") ;
				}
				\$("#textareaStream_URL_"+row_nr).hide() ;	
				if (\$("#textareaStream_URL_"+row_nr).val()) {
					\$tr.find("td:nth-last-child($url_col)").css("background-color","") ;
				}				
			}
			
		}) ;
		
		\$("#$useropts{table_id}").on("change","[id^='textareaStream_key_'],[id^='textareaStream_URL_']", function () {
			
			let row_nr = get_row_nr (this.id,2) ;  
			if (!\$("#selectStream_forwarding_"+row_nr).val()) {
				\$("#selectStream_forwarding_"+row_nr).val("1").trigger("chosen:updated") ;
			}
			
		}) ;
			
	~ ;
	
} #-------------------------------------------------------------------------------

sub thead {
	
	# # # # # # &common_min_thead ;
	
	$print_thead  = qq~<THEAD><TR>~ ;

	foreach (@sql_col_display) { 
	
		my $coltitle = "" ;
		if ($custom_header{$_}) {
			$coltitle = $custom_header{$_} ;
		} else {
			 $coltitle = $_ ; $coltitle =~ s/\_id//g ; $coltitle =~ s/\_/ /g ; $coltitle = uc $coltitle ; $coltitle = $replace_blank_table_top_right if $coltitle eq '' and $replace_blank_table_top_right ;
		}
	
		# $custom_column_styles{$_} = qq~style="min-width:120px;"~ unless $custom_column_styles{$_} ;
		$print_thead .= qq~<TH class="dt-center" $custom_column_styles{$_}>$coltitle</TH>~ ;
	}
		
	if ($add_th_row) { $print_thead .= $add_th_row ; } # used in agent_commission_report.pl and cruiseline_commission_report.pl
		
	$print_thead .= qq~</TR></THEAD>~ ;	
	
} #-------------------------------------------------------------------------------

sub page_opts {

	our $glyphicon = 'list' ;
	our $lcpage    = 'all-fixtures-report' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ;

	&common_page_name ;
	   
	our $table     = 'analytics_event_bookings q' ;
	$page_title    = 'All Fixtures Report' ;

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

sub report_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} = "Date Time From" ;
	$preferred_title{start_date_to} = "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','') ;
	
	if ($usertype ne 'coding_provider') {
	
		&common_min_select_opts('coding_provider_id','users','name','','','username',"user_type='coding_provider'") ;
		
		$opts{coding_provider_id} .= qq~<option value="all">All</option>~ ; 
		
		$i{coding_provider_id} = 'all' unless $i{coding_provider_id};
		
		$opts{coding_provider_id} =~ s/value="$i{coding_provider_id}"/value="$i{coding_provider_id}" SELECTED/g ;	
	
	} elsif ($usertype eq 'coding_provider') {
		&db_min_ro('users','1,name,username',"id='$userid'",'','') ; 
		$opts{coding_provider_id} = qq~<option value="$userid" SELECTED>$db{users}{1}{name} [$db{users}{1}{username}]</option>~ ; 
		
	}
	
	$print_box_content_rows .= &common_min_form_select('coding_provider_id','') ;
	
	our %service_types = (1 => "Live Coding",2 => "Individual 48 hrs",3 => "Post Coding 24 hrs") ;

	foreach (keys %service_types) {
		$opts{service_type_id} .= qq~<option value="$_">$service_types{$_}</option>~ ; 
	} 
	$opts{service_type_id} .= qq~<option value="all">All</option>~ ; 
	
	$i{service_type_id} = 'all' unless $i{service_type_id};
	
	$opts{service_type_id} =~ s/value="$i{service_type_id}"/value="$i{service_type_id}" SELECTED/g ;

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

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

sub screen3 {

	$custom_column_styles{coding_provider} 		= qq~style="width:7.5%;min-width:120px;"~ ;
	$custom_column_styles{status} 				= qq~style="width:7.5%;min-width:120px;"~ ;
	$custom_column_styles{moderated} 			= qq~style="width:7.5%;min-width:120px;"~ ;
	$custom_column_styles{stream_forwarding}	= qq~style="width:7.5%;min-width:120px;"~ ;
	$custom_column_styles{stream_key} 			= qq~style="width:7.5%;min-width:120px;"~ ;
	$custom_column_styles{stream_URL} 			= qq~style="width:7.5%;min-width:120px;"~ ;
	$custom_column_styles{analyst} 				= qq~style="width:7.5%;min-width:120px;position:relative;"~ ;
	# stream_forwarding","stream_key","stream_URL
	&thead;

	if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; }

	# my $page = "$lcpage\s" ;

	my $page = "analytics-event-bookings" ;

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

	&common_min_table('id',$page,'list') ;

	our $savjqy = 1 ;

	# &common_min_extra_crumb("manage-$lcpage\s","Manage $ucfirstpage\s") ;

	$extra_form_fields .= qq~
		<input type="hidden" name="customer_name" 			value="$i{customer_name}"> 
		<input type="hidden" name="start_date_from"		value="$i{start_date_from}"> 
		<input type="hidden" name="start_date_to"		value="$i{start_date_to}"> 
		<input type="hidden" name="options" 			value="$i{options}">  
		<input type="hidden" name="sport_type_ids" 			value="$i{sport_type_ids}">  
		<input type="hidden" name="coding_provider_id" 	value="$i{coding_provider_id}"> 
		<input type="hidden" name="service_type_id" 	value="$i{service_type_id}"> 
	~;
	
	# $skip_save_btn = 1 if $usertype eq 'coding_provider' ;
	
	$print_box_content_rows .= &common_min_forms_end('','','save') ;
	
	# $trigger_jquery_raw .= qq~\$("#selectCoding_provider_1_1020_chosen").~ ;
	
	require _blank ;

	exit ;

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

sub redirect_screen {
	
&common_min_alert_type ;

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

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

</script>
</body>

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

</html>
ENDOFTEXT
#

exit ;

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

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

	&db_min_ro($table,'id,event_quote_id,fixtures_saved_values,analytics_saved_values,event_completed,event_accepted,event_pending,event_cancelled,event_rejected,sport_type_ids,start_date_time,region_id,client_id,total_fixtures,service_type_id,cant_charge_client_fixtures,cant_charge_client_reasons',$where,'','') ;
	my %seen_region = () ; my %seen_client = () ; my $cnt_client = 0 ; 
	foreach (keys %{$db{$table}}) {
		$seen_region{$db{$table}{$_}{region_id}} = 1 ;
		$seen_client{$db{$table}{$_}{client_id}} = 1 ;
		$cnt_client++ ;
	}
	&db_min_ro('sport_types','id,name','','','') ;
	&db_min_ro('analytics_ht_colors','id,name','','','') ;
	
	
	if ($usertype eq 'coding_provider') {
		
		&db_min_ro('users','id,name,username',"id='$userid'",'','') ;
		
		&db_min_ro('all_fixtures_analysts','id,name',"coding_provider_id='$userid'",'','') ; 
		
		foreach (sort {$db{all_fixtures_analysts}{$a}{name} cmp $db{all_fixtures_analysts}{$b}{name}} keys %{$db{all_fixtures_analysts}}) {
			$opts{$userid}{analyst} .= qq~<option value='$_'>$db{all_fixtures_analysts}{$_}{name}</option>~ ; 
		}

	} else {
		
		&db_min_ro('users','id,name,username',"user_type='coding_provider'",'','') ;
		
		&db_min_ro('all_fixtures_analysts','id,name,coding_provider_id',"",'','') ; 
		
		foreach (sort {$db{all_fixtures_analysts}{$a}{name} cmp $db{all_fixtures_analysts}{$b}{name}} keys %{$db{all_fixtures_analysts}}) {
			$opts{$db{all_fixtures_analysts}{$_}{coding_provider_id}}{analyst} .= qq~<option value='$_'>$db{all_fixtures_analysts}{$_}{name}</option>~ ; 
		}
		
	}
	
	# my $teams_sql_where = join (" OR ", map { "region_id='$_' OR (region_id='0' AND matched_region_id ='$_')" } keys %seen_region) ;
	# $teams_sql_where .= qq~ OR ~ if $cnt_client && $teams_sql_where ;
	# my $teams_sql_where .= join (" OR ", map { "aisa_client_id='$_'" } keys %seen_client)  ;
	
	&db_switch_conn('sss') ;
	&db_min_ro('teams','id,name',"",'','') ;
	&db_switch_conn('aisa') ;
	
	foreach (keys %{$db{users}}) {
		$opts{coding_provider_id} .= qq~<option value="$_">$db{users}{$_}{name} [$db{users}{$_}{username}]</option>~ ;
	}
	
	# # our %coding_provider	= (1 => 'SportVot',2 => 'iSport') ; 
	
	# foreach (keys %coding_provider) {
		
	foreach (keys %fixtures_status) {
		$opts{status_id} .= qq~<option value="$_">$fixtures_status{$_}</option>~ ;
	}
	
	$opts{moderated} = qq~<option value='1'>Yes</option><option value='2'>No</option>~ ;
	
} #------------------------------------------------------------------------------------------

use common ;
use common_shared ;
use report ;
use xlsxcreator ;
use today ; 
use analytics_event_booking_tabs ;

1;