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

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

&load_json ;

print $json ;

exit ;

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

sub load_json {
	
	# return unless $param{region_id} ;
	
	# &db_min_ro('regions',"1,code","`id`='$param{region_id}'",'','') if $param{region_id} ;

	my $venue_sql = "" ;
	
	if ($param{country_id} && !$param{region_id}) {
		&db_min_ro('regions','id',"`country_id` = '$param{country_id}'") ;
		$venue_sql = join(" OR ",map { "region_id='$_'" } keys %{$db{regions}}) ; 
		$venue_sql = "region_id='13'" if !$venue_sql ; 		
	} elsif ($param{region_id}) {
		$venue_sql = "region_id='$param{region_id}'" ; 		
	}

	
	# my $venue_sql = "" ;
	# $venue_sql .= qq~`country_id`='$param{country_id}'~ if $param{country_id} ;
	# $venue_sql .= qq~ AND ~ if $param{country_id} && $param{region_id}   ;
	
	# if ($param{region_id} eq '13') { ## OTHER
		# my $abc = ($param{country_id}) ? "" : qq~country_id='0' OR ~ ;
		# $venue_sql .= qq~($abc `region_id`='0' OR `region_id`='13')~ ;
	# } elsif ($param{region_id}) {
		# $venue_sql .= qq~`region_id`='$param{region_id}'~ ;
	# }
	
	&db_min_ro('organisations','id,name',"$venue_sql",'','') ; 
	
	# &db_min_ro('organisations','id,name',"`region_id` = '$param{region_id}'",'','') if $param{region_id} ; 
	
	# &db_min_ro('organisations','id,name','','','') unless $param{region_id} ; 
	
	$json = '[' ;

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

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

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

use db ;
use common ;

1;