#!/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 $regions_sql = "" ;
	
	if ($param{country_id} && !$param{region_id}) {
		&db_min_ro('regions','id',"`country_id` = '$param{country_id}'") ;
		$regions_sql = join(" OR ",map { "region_id='$_'" } keys %{$db{regions}}) ; 
		$regions_sql = "region_id='13'" if !$regions_sql ; 		
	} elsif ($param{region_id}) {
		$regions_sql = "region_id='$param{region_id}'" ; 		
	}

	&db_min_ro('cities','id,name,region_id,country_id',$regions_sql,'','') ; 
	
	# &db_min_ro('cities','id,name,region_id,country_id',"`country_id` = '$param{country_id}' OR `country_id` = '0'",'','') if $param{country_id} ; 
	# &db_min_ro('cities','id,name,region_id,country_id',"",'','') if !$param{country_id} ; 
	
	# my $unknown_country_id_exists = 0 ; 
	# foreach (keys %{$db{cities}}) {
		# unless ($db{cities}{$_}{country_id}) {
			# $unknown_country_id_exists  = 1 ; 
			# last ;
		# }
	# }
	
	# &db_min_ro('regions','id',"`country_id` = '$param{country_id}'",'','') ; 
	 
	$json = '[' ;

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

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

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

use db ;
use common ;

1;