#!/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';
use DBI ;

# require cfg ;

exit unless $ENV{HTTP_REFERER} =~ m/aisadmin/iog ;

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

@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://sssadmin.co.za/cgi-bin/aisa/scripts/get/get_teams_from_typeahead.pl?query=test

# our $debug = 1 ;

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

$json = '[' ;

&db_open_ro('sss') ;
	our $db_ignore_open_close = 1 ;
	&load_json ;
$db_ignore_open_close = 0 ;
&db_close_conn ;	

$json .= ']' ;

print $json ;

exit ;

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

sub load_json {
	
	return if !$param{query} && !$param{client_id} ;
	
	my $teams_sql = ($param{exact_name}) ? "name = '$param{query}'" : "name LIKE '%$param{query}%'" ;
	
	$teams_sql = qq~($teams_sql) AND aisa_client_id='$param{client_id}'~ if $param{client_id} ;
	
	&db_min_ro('teams','id,name',$teams_sql,'','') ; 

	foreach my $id (sort {$db{teams}{$a}{name} cmp $db{teams}{$b}{name}} keys %{$db{teams}}) { 
	
		$json .= qq~{"id":"$id","team_name":"$db{teams}{$id}{name}"},~ ; 
	}

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

	$json  =~ s/\\//g ;

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

use db ;
use common ;

1;