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

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

$json = '[' ;

&load_json ;

$json .= ']' ;

print $json ;

exit ;

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

sub load_json {
	
	if ($param{region_id} && $param{country_id}) {
		$json .= qq~{"country_id":"$param{country_id}","region_id":"$param{region_id}"}~ ;
		return ;
	} elsif (!$param{city_id}) {
		return ;
	}

	my $country_id = ($param{country_id}) ? $param{country_id} : 0 ; 
	my $region_id = ($param{region_id}) ? $param{region_id} : 0 ;
	
	if (!$region_id) { ## IF WE DONT KNOW THE REGION
		&db_min_ro('cities',"1,region_id","`id`='$param{city_id}'",'','') ; 
		$region_id = $db{cities}{1}{region_id} ;		
	}
	
	if (!$country_id) {
		&db_min_ro('regions','1,country_id',"`id`='$region_id'",'','') ; ## IF WE DONT KNOW THE COUNTRY 
		$country_id = $db{regions}{1}{country_id} ;
	}
	
	$json .= qq~{~ 							if $country_id || $region_id ; 
	$json .= qq~"country_id":"$country_id"~ if $country_id ; 
	$json .= qq~,~ 							if $country_id && $region_id ;
	$json .= qq~"region_id":"$region_id"~ 	if $region_id ;
	$json .= qq~}~ 							if $country_id || $region_id ;	
	$json  =~ s/\\//g ;
	
} #------------------------------------------------------------------------------------------       

use db ;
use common ;

1;