#!/usr/bin/perl

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

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

&today ;

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

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

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

# our $debug  = 1 ;
our $table    = 'teams' ;
our $dialog = 1 ;

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

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

&db_open_ro ;
    our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
	
		&db_switch_conn('sss') ;

		if ($iaction eq 'add'){
			&common_min_add_screen;
			&screen1;
		}
			
		if ($iaction eq 'save'){
			&common_min_load_params ;
			&validate ;
			&insert ;
			&screen2 ;
		}
			
		&common_min_action;
		  
	$db_ignore_open_close = 0 ; 
&db_close_conn ; 

  
exit ;    

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

sub insert {

	&add_db_fields ; # $i{last_edited_by} = $userid ; $i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
	
	&validate ;
	
	$ignore{sel_field} = 1 ;
	
	$i{id} = &db_min_get_max($table,'id') ;

	&db_min_insert($table) ;

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

sub validate {
	
	# called from common_min_action

	my $exists   = '' ;

	$i{name} = &common_fix_str($i{name}) ;

	&db_min_ro($table,'id,name,region_id,matched_region_id','','','') ;

	foreach my $id (keys %{$db{$table}}) {
		if (lc $db{$table}{$id}{name} eq lc $i{name}) {
			$exists = 1 ;
			if (!$db{$table}{$id}{region_id} && !$db{$table}{$id}{matched_region_id}) {
				%ii = %i ; 
				%i = () ; 
				$i{id} = $id ;
				$i{name} = $db{$table}{$id}{name} ;
				$ignore{name} = 1 ;
				$ignore{region_id} = 1 ;
				$i{matched_region_id} = $ii{region_id} ;
				$i{region_id} = $ii{region_id} ;
				&db_min_upd($table,"id='$i{id}'") ; 
				# &screen2 ;
				%i = %ii ; 
				$ignore{name} = '' ;
				$ignore{region_id} = '' ;
				$alert = &common_min_alert('warning',"'$i{name}' AS A TEAM NAME ALREADY EXISTS!",'warning-sign') ;
				%col_name = () ;
				&common_min_add_screen;
				&screen1;
				exit ;
			} 
		}
	}
	 
	if ($exists) {
		$alert = &common_min_alert('warning',"'$i{name}' AS A TEAM NAME ALREADY EXISTS!",'warning-sign') ;
		%col_name = () ;
		&common_min_add_screen;
		&screen1;
    }

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

sub add_screen {

	$box_header_title = "Add $home_or_away_team Team" ;
	$hidden_action    = 'save' ;
	$head_col_width   = 2 ;
	
} #------------------------------------------------------------------------------------------

sub add_db_fields {
	
	$ignore{iaction}    				= 1 ;
	$hidden{id}         				= 2 ; 
	$hidden{sel_field}  				= 2 ;
	$required{name}     				= 1 ;
	$required{region_id}				= 1 ;
	$required{aisa_client_id}			= 1 if $home_or_away_team eq 'Home' ;
	$select{region_id}					= 1 ;
	$sort_field{1} 						= "name" ;
	$sort_field{2} 						= "region_id" ;
	$sort_field{3} 						= "aisa_client_id" ;
	$preferred_title{region_id}			= "Region" ;
	$preferred_title{aisa_client_id}	= "Client" ;
	
	if ($i{name}) {
		$trigger_jquery_raw .= qq~
			\$("input[name='name']").val("$i{name}") ;
		~ ;
	}
	
	if ($i{region_id}) {
		$trigger_jquery_raw .= qq~
			\$("#selectRegion_id").val("$i{region_id}").trigger("chosen:updated") ;	
		~ ;			
	} else {
		$trigger_jquery_raw .= qq~
			\$("#selectRegion_id").val(parent.\$("#selectRegion_id").val()).trigger("chosen:updated") ;			
		~ ;
	}
	if ($i{aisa_client_id}) {
		$trigger_jquery_raw .= qq~
			\$("#selectAisa_client_id").val("$i{aisa_client_id}").trigger("chosen:updated") ;			
		~ ;
	} else {
		$trigger_jquery_raw .= qq~
			if (parent.\$("#selectClient_id").val()) {
				let parent_client = parent.\$("#selectClient_id").val() ;
				if (parent_client == null) { parent_client = "" ; }
				parent_client = parent_client.toString() ;
				parent_client = parent_client.split(":") ;	
				\$("#selectAisa_client_id").append("<option value='"+parent_client[0]+"'>"+parent.\$("#selectClient_id option:selected").text()+"</option>").trigger("chosen:updated") ; 
				\$("#selectAisa_client_id").val(parent_client[0]).trigger("chosen:updated") ; 
			}
		~ ;
	}
	
	$trigger_jquery_raw .= qq~\$("#selectRegion_id").chosen({ allow_single_deselect:false });~ ;
	
	if ($home_or_away_team eq 'Home') {
		$trigger_jquery_raw .= qq~
			\$("#selectAisa_client_id").chosen({ allow_single_deselect:false });		
		~ ;
	} elsif ($home_or_away_team eq 'Away') {
		$trigger_jquery_raw .= qq~
			\$("#selectAisa_client_id").chosen({ allow_single_deselect:true });		
		~ ;		
	}
	
	# &db_min_ro('teams',"DISTINCT aisa_client_id","aisa_client_id <> '0'",'','') ;
	
	# my $exclude_client_sql = join(" AND ", map{ "id != '$_'" } keys %{$db{teams}}) ;
	&common_min_select_opts('region_id','regions','name') ; 
	&db_switch_conn('aisa') ;
	# $opts{aisa_client_id} = qq~<option></option>~ ;
	&common_min_select_opts('aisa_client_id','customers','name','','','',"") ; 
	&db_switch_conn('sss') ;
	$db{$table}{''}{sel_field} = $selectfield if $selectfield ;

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

sub thead {

	&common_min_thead ;
    
} #-------------------------------------------------------------------------------
 
sub screen1 {
	
	$trigger_jquery_raw .= qq~
		\$('#btn-close-customer').click( function (e) {
			parent.BootstrapDialog.closeAll() ;
		});
	~ ;

	&common_min_dialog_load_screen ;

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

sub screen2 {
	
	$trigger_jquery_raw = qq~
	
		let parent_client = parent.\$("#selectClient_id").val() ;
		if (parent_client == null) { parent_client = "" ; }
		parent_client = parent_client.toString() ;
		parent_client = parent_client.split(":") ;
		
		for (let i = 1; i <= 100; i++) {
			
			if (!parent.\$("#fixtures_"+i).html()) {
				break ;
			}
			
			if ((!parent_client[0] && parent.\$("#selectRegion_id").val() == "$i{region_id}") || (parent_client[0] && parent_client[0] == "$i{aisa_client_id}") || (!parent_client[0] && !parent.\$("#selectRegion_id").val())) {
				parent.\$("#selectHome_team_fixtures_"+i).append("<option value='$i{id}'>$i{name}</option>").trigger("chosen:updated") ;
				if (!parent.\$("input[name='changed_home_team_"+i+"']").val()) {
					parent.\$("#selectHome_team_fixtures_"+i).val("$i{id}").trigger("chosen:updated") ;
				}
			}
			
			// if (parent.\$("#selectRegion_id").val() == "$i{region_id}") {
				parent.\$("#selectAway_team_fixtures_"+i).append("<option value='$i{id}'>$i{name}</option>").trigger("chosen:updated") ;
			// }
			
		}
		
		parent.BootstrapDialog.closeAll() ;
	
	~ ;
	
	&common_min_dialog_save_screen ;

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

use today ;
use dialog ;
use common ;

1;