#!/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_open_upd ;
	$db_ignore_open_close = 1 ; 
		&load_json ;
	$db_ignore_open_close = 0 ; 
&db_close_conn ; 

print $json ;

exit ;

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

sub load_json {
	
	my $sql_or = ($is_schools_manager || $is_operator) ? join(' OR ', map { "id = '$_'" } keys %{$glob_regids{$userid}}) : '' ;
	
	$sql_or = ($param{country_id} && $sql_or) ? "`country_id` = '$param{country_id}' AND ($sql_or)" : ($param{country_id}) ? "`country_id` = '$param{country_id}'" : $sql_or ;
	
	my $user_extra = ($is_schools_manager || $is_operator) ? join(' OR ', map { "region_id = '$_'" } keys %{$glob_regids{$userid}}) : '' ;
	
	$sql_or = ($city_sql && $user_extra) ? "($sql_or) AND ($user_extra)" : (!$sql_or && $user_extra) ? $user_extra : $sql_or  ;
	
	&db_min_ro('regions','id,name,code',"$sql_or",'','') ; 
	
	# &db_min_ro('regions','id,name,code',"`country_id` = '$param{country_id}'",'','') if $param{country_id} ; 
	# &db_min_ro('regions','id,name,code',"",'','') if !$param{country_id} ; 
	  
	$json = '[' ;

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

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

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

use db ;
use common ;

1;