#!/usr/bin/perl

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

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

use CGI::Carp qw(fatalsToBrowser);
use Fcntl qw(:flock);
use JSON::Repair ':all';

require cfg ;

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

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

foreach $ARG (@ARGV) { ($par,$val) = split(/\=/,$ARG) ; $val  =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; $param{$par} = $val ; }
	
# my $json_type = $param{json_type} ;
	
# e.g. https://itvadmin.co.za/cgi-bin/scripts/get/get_typeahead_json.pl?json_type=additional_services

# our $debug = 1 ;

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

&db_switch_conn('sss') ;
	$json = '[' ;
	&load_json ;
	$json .= ']' ;
	$db_ignore_open_close = 0 ; 
&db_close_conn ; 

print $json ;

exit ;

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

sub load_json {
	
	# return if !$param{region_id} && !$param{country_id} ;
	
	my $regions_sql = 
		($param{region_id} && $param{region_id} ne '13') ? "`region_id` = '$param{region_id}' OR (`region_id` = '0' AND `matched_region_id` = '$param{region_id}')" : 
		($param{region_id} eq '13') ? "`region_id` = '13' OR (`region_id` = '0' AND `matched_region_id` = '13') OR (`region_id` = '0' AND `matched_region_id` = '0')" : 
		"" ;
	
	if ($param{country_id} && !$param{region_id}) {
		&db_min_ro('regions','id',"`country_id` = '$param{country_id}'") ;
		$regions_sql = join(" OR ",map { "(`region_id` = '$_' OR (`region_id` = '0' AND `matched_region_id` = '$_'))" } keys %{$db{regions}}) ; 
		$regions_sql = "`region_id` = '13' OR (`region_id` = '0' AND `matched_region_id` = '13')" if !$regions_sql ; 		
	}
	
	# if (!$param{region_id} && !$param{country_id}) {
	if ($regions_sql) {
		$regions_sql = "($regions_sql) OR (`region_id` = '0' AND `matched_region_id` = '0')" ; 		
	} else {
		$regions_sql = "(`region_id` = '0' AND `matched_region_id` = '0')" ; 		
	}

	# &db_min_ro('teams','id,name',"`region_id` = '$param{region_id}' OR (`region_id` = '0' AND `matched_region_id` = '$param{region_id}')",'','') if $param{region_id} ; 
	&db_min_ro('teams','id,name,region_id,matched_region_id',$regions_sql,'','')  ; 
	
	foreach my $id (sort {$db{teams}{$a}{name} cmp $db{teams}{$b}{name}} keys %{$db{teams}}) { 

		$json .= qq~
	{"id":"$id","name":"$db{teams}{$id}{name}","region_id":"$db{teams}{$id}{matched_region_id}"},~ ; 
	
	}

	if ($json =~ /\,/) { $json  = substr($json,0,-1) ; }

	$json  =~ s/\\//g ;
	
} #------------------------------------------------------------------------------------------       

use db ;
use common ;

1;