#!/usr/bin/perl

BEGIN { use lib '/usr/home/cfg' ; require push_inc ; }
    
require cfg ;

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

use CGI::Carp qw(fatalsToBrowser);
use CGI;

&today;

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

@ARGV   = split(/\\*\&/, $ENV{'QUERY_STRING'});
$action = $ARGV[0] ;

our ($q)                 = CGI -> new() ;
our $iaction             = $q -> param('iaction')                || $action ;
our $isaved              = $q -> param('isaved')                 || '' ;

our $debug = 1 ;

#-------- page opts --------------------------------------------------------------------------------------------------------------------------------------------------

&page_opts ;

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

print "Content-type: text/html\n\n";

our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab

&db_open_ro ;
	$db_ignore_open_close = 1 ;
		&common_min_action;
	$db_ignore_open_close = 0 ; 
&db_close_conn ;

exit;

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

sub validate {

	my $exists   = '' ;

	$i{name} = &common_fix_str($i{name}) ;

	&db_min_ro($table,'*',"name='$i{name}'",'name','') ;

	foreach my $id (keys %{$db{$table}}) { if (lc $db{$table}{$id}{name} eq lc $i{name}) { $exists = 1 ; } }

	if ($exists) {
		$alert = &common_min_alert('warning',"VENUE NAME ALREADY EXISTS!",'ok') ;
		%col_name = () ;
		&common_min_add_screen ;
		&common_min_screen1 ;
    }

# REMOVE LATER -----------------

	&db_min_ro('regions','id,code',"id='$i{region_id}'",'','') if $i{region_id} ; 
	
	$i{region_code} = $db{regions}{$i{region_id}}{code} if $i{region_id} ;

# REMOVE LATER -----------------

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

sub insert {

	&add_db_fields ;

	$i{id} = &db_min_get_max($table,'id') ;
	
	$ignore{country_id} = 1 ;
	
	&db_min_insert($table) ;

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

sub update {

	unless ($i{id}) { $error = qq(NO ID) ; return ; }

	&edit_db_fields ;

	$ignore{country_id} = 1 ;

	&db_min_upd($table,"id='$i{id}'") ;

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

sub list_screen {
	
	&db_min_ro('regions','id,name,code,country_id','','','') ; 
	
	&db_min_ro('countries','id,name','','','') ; 
	
	&db_min_ro('event_quotes',"DISTINCT organisation_ids AS 'organisation_ids'","organisation_ids <> '0'",'','') ;

	foreach my $_id (keys %{$db{event_quotes}}) {
		if ($_id =~ /,/) { ## 13,32
			foreach (split(/\,/,$_id)) {
				$venue_id_used{$_} = 1 ;
			}
		} else {
			$venue_id_used{$_id} = 1 ;
		}
	}

	&db_min_ro($table,'*','','','') ;

	foreach my $id (keys %{$db{$table}}) {
		
		my $edit_butt = qq~&nbsp;<a class="btn btn-default btn-xs" href="#" title="Request user rights in order to edit." data-toggle="tooltip"><i class="glyphicon glyphicon-edit icon-white"></i></a>~ ;   
		my $del_butt  = qq~&nbsp;<a class="btn btn-default btn-xs" href="#" title="Request user rights in order to delete." data-toggle="tooltip"><i class="glyphicon glyphicon-trash icon-white"></i></a>~ ;  
		
		if ($glod_user_level >= 3) {
			$edit_butt = qq~&nbsp;<a class="btn btn-info btn-xs" href="javascript:editMinItem('$db{$table}{$id}{id}');"><i class="glyphicon glyphicon-edit icon-white"></i></a>~ ; 
		}
		
		if ($glod_user_level >= 3) {
			$del_butt  = qq~&nbsp;<a class="btn btn-danger btn-xs" href="javascript:deleteMinItem('$db{$table}{$id}{name}','$db{$table}{$id}{id}')"><i class="glyphicon glyphicon-trash icon-white"></i></a>~ ; 
		}
			
		if ($venue_id_used{$id}) {
			# $edit_butt = qq~&nbsp;<a class="btn btn-default btn-xs" href="#" title="In system use!" data-toggle="tooltip"><i class="glyphicon glyphicon-edit icon-white"></i></a>~ ;   
			$del_butt  = qq~&nbsp;<a class="btn btn-default btn-xs" href="#" title="In system use!" data-toggle="tooltip"><i class="glyphicon glyphicon-trash icon-white"></i></a>~ ;  
		}
		
		my $region = ($db{regions}{$db{$table}{$id}{region_id}}{code}) ? qq~$db{regions}{$db{$table}{$id}{region_id}}{name} [$db{regions}{$db{$table}{$id}{region_id}}{code}]~ : qq~$db{regions}{$db{$table}{$id}{region_id}}{name}~ ;
		
		$print_tbody .= qq~
			<tr id="$id">
				<td>$id</td>
				<td>$db{$table}{$id}{name}</td>
				<td>$db{$table}{$id}{address_line_1}</td>
				<td>$db{$table}{$id}{address_line_2}</td>
				<td>$db{$table}{$id}{address_line_3}</td>
				<td>$db{$table}{$id}{address_line_4}</td>
				<td>$db{$table}{$id}{suburb}</td>
				<td>$db{$table}{$id}{postal_code}</td>
				<td>$region</td>
				<td>$db{countries}{$db{regions}{$db{$table}{$id}{region_id}}{country_id}}{name}</td>
				<td nowrap>
					$edit_butt
					$del_butt
				</td>
			</tr>
		~ ;
	}

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

sub add_db_fields {
	
	&sort_fields;
		
	&hidden_db_fields;

	# $ignore{id} = 1 ;

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

sub edit_db_fields {
	
	&hidden_db_fields;
	
	&sort_fields;

	$hidden{id} = 1 ; # 1 = bypass for db update

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

sub hidden_db_fields {
	
	$ignore{iaction}        = 1 ;
	$required{name}         = 1 ; 
	$required{region_id}  = 1 ;
	$required{address_line_1}  = 1 ;
	$required{address_line_2}  = 1 ;
	$required{address_line_3}  = 1 ;
	$required{address_line_4}  = 1 ;
	$required{suburb}  = 1 ;
	$required{postal_code}  = 1 ;
	
} #------------------------------------------------------------------------------------------

sub sort_fields {

	&db_min_ro('event_quotes',"DISTINCT organisation_ids AS 'organisation_ids'","`organisation_ids` <> 0 AND `organisation_ids` LIKE '%$i{id}%'",'','') ;

	our %venue_id_used = () ;
	
	foreach my $_id (keys %{$db{event_quotes}}) {
		if ($_id =~ /,/) { ## 13,32
			foreach (split(/,/,$_id)) {
				$venue_id_used{$_} = 1 ;
			}
		} else {
			$venue_id_used{$_id} = 1 ;
		}
	}
	 
	%sort_field = () ;
	

	$sort_field{3}  = 'name' ; 			$preferred_title{name} 		= 'Name' ;
	$sort_field{4}  = 'address_line_1' ; 
	$sort_field{5}  = 'address_line_2' ; 
	$sort_field{6}  = 'address_line_3' ; 
	$sort_field{7}  = 'address_line_4' ; 
	$sort_field{8}  = 'suburb' ; 
	$sort_field{9}  = 'postal_code' ; 
	$sort_field{10}  = 'region_id' ; 	$preferred_title{region_id} = 'Region' ;
	$sort_field{11}  = 'country_id' ; 	 
	
	if ($venue_id_used{$i{id}}) {	 
		# &db_min_ro('regions',"code,name","",'','') ;
		$required{name}			= 0 ; 
		$required{region_id}	= 0 ;
		$input{region_id} 		= 1 ;			
		$readonly{region_id} 	= "READONLY" ;		
		$readonly{name} 		= "READONLY" ;	
		&db_min_ro('regions','id,code',"id='$db{$table}{$i{id}}{region_id}'",'','') if $i{id} ; 
	
		$db{$table}{$i{id}}{region_id} = $db{regions}{$db{$table}{$i{id}}{region_id}}{code} if $i{id} ;
		
		$preferred_title{region_id} = 'Region Code' ;
		
	} else {
		$select{region_id} 		= 1 ;		
	}
	 
} #-------------------------------------------------------------------------------

sub add_screen {

	# called from common_add_screen

	&select_opts ;

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

sub edit_screen {
 
	&select_opts ;

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

sub select_opts {

	# $required{based_in} = 1 ;
	# $select{based_in} = 1 ;
	# $opts{based_in} = qq~<option value="JNB" $selected{based_in}{'JNB'}>Johannesburg</option><option value="CPT" $selected{based_in}{'CPT'}>Cape Town</option>~ ;
	
	return if $venue_id_used{$i{id}} ;
	
	my $sql_or = ($is_schools_manager || $is_operator) ? join(' OR ', map { "id = '$_'" } keys %{$glob_regids{$userid}}) : '' ;
	
	# if ($is_schools_manager || $is_operator) {
		# @report_sql_or = () ;
		# foreach $_reg_id (keys %{$glob_regids{$userid}}) {
			# push @report_sql_or, "id = '$_reg_id'"
		# }{
	# }
	
	if ($db{$table}{$i{id}}{country_id}) {
		$sql_or = ($sql_or) ? "`country_id` = '$db{$table}{$i{id}}{country_id}' AND ($sql_or)" : "`country_id` = '$db{$table}{$i{id}}{country_id}'" ;
	}
	
	$allow_deselect{country_id} = 1 ;
	
	&common_min_select_opts('region_id','regions','name',$db{$table}{$i{id}}{region_id},'','code',$sql_or,'','','','name') ;
	&common_min_select_opts('country_id','countries','name',$db{regions}{$db{$table}{$i{id}}{region_id}}{country_id},'','','','','','','name') ;

	$trigger_jquery_raw .= qq~
 	 			
		let map_region_to_country = {} ; 
		
		const \$countrySelect 	= \$("#selectCountry_id") ;
		const \$regionSelect  	= \$("#selectRegion_id") ;

		const updateChosen = \$el => \$el.trigger("chosen:updated");
		
		const fetchJSON = async url => {
			try {
				const res = await fetch(url);
				if (!res.ok) throw new Error(`Request failed: \${res.status}`);
				return await res.json();
			} catch (err) {
				console.error("Fetch error:", err);
				return [];
			}
		};	
		
		const populateSelect = (\$field, json_list, getLabel, defaultSelected = () => "") => {
			
			let isSelected ;

			// Determine how to handle selected logic
			if (typeof defaultSelected === "function") {
				isSelected = defaultSelected ;
			} else if (Array.isArray(defaultSelected)) {
				isSelected = data => defaultSelected.includes(data.id) ? "selected" : "" ;
			} else {
				isSelected = data => data.id == defaultSelected ? "selected" : "" ;
			}

			// Auto-select the only item if none explicitly selected
			const autoSelectOnly = json_list.length === 1 && typeof defaultSelected === "string" && defaultSelected === "" ;

			json_list.forEach(data => {
				const selected = autoSelectOnly || isSelected(data) ? "selected" : "" ;
				\$field.append(`<option value="\${data.id}" \${selected}>\${getLabel(data)}</option>`) ;
			});

			updateChosen(\$field) ;
			return json_list.length ;
		};
		
		const getInputValue = name => \$(`input[name='\${name}']`).val();

		const clearSelect = (\$el) => {
			\$el.empty();
			\$el.append(`<option value=""></option>`).trigger("chosen:updated");
		};
		
		// _______________________________________________
		
		\$countrySelect.change( async function() { 
			\$("input[name='custom_selected_country']").val("1") ;
			await update_region_drop_down_from_country(\$countrySelect.val()) ; 
		}) ;
		 
		async function update_region_drop_down_from_country (countryId) {
		 
			clearSelect(\$regionSelect) ;
			
			const regionUrl = `$useropts{scripts}/get/get_regions_from_country.pl?country_id=\${countryId}` ;
			const regions = await fetchJSON(regionUrl);
		
			for (const data of regions) {
				map_region_to_country[data.id] = countryId ;
			}
			 
			const regionCount = populateSelect(\$regionSelect, regions, r => r.code ? `\${r.name} [\${r.code}]` : r.name , "") ;			

			if (regionCount === 0 && \$countrySelect.val()) {
				\$regionSelect.append(`<option value="13" selected>Other [OT]</option>`).trigger("chosen:updated") ;
			}  
			
		}	
		
		// _______________________________________________
		
		\$regionSelect.change( async function() {
			\$("input[name='custom_selected_region']").val("1") ;
			\$("input[name='custom_selected_country']").val("1") ; 
			const regionId = \$regionSelect.val() ;   
			await update_country_from_region(regionId,1) ; 
		});
		
		async function update_country_from_region (regionId,update_country=0) {
			if (map_region_to_country[regionId] || regionId == '13') {
				\$countrySelect.val(map_region_to_country[regionId]).trigger("chosen:updated") ; 
			} else if (!\$("input[name='custom_selected_country']").val() || update_country) { 
				const lookupUrl = `$useropts{scripts}/get/get_country_from_region.pl?country_id=&region_id=\${regionId}`;
				const regionMeta = await fetchJSON(lookupUrl);
				const { country_id } = regionMeta[0] ?? {} ; 
				if (country_id) {
					map_region_to_country[regionId] = country_id;
					\$countrySelect.val(country_id).trigger("chosen:updated");
				} 					
			}		
		}
		
		// _______________________________________________
		
	~ ;
	
} #------------------------------------------------------------------------------------------

sub thead {
	
	if ($venue_id_used{$i{id}}) {	
		$ignore{region_id} = 1 ;
		$ignore{name} = 1 ;
	}
	
	$print_thead = qq~	
		<THEAD>
			<TR>
				<TH>ID</TH>
				<TH>Name</TH>
				<TH>Address Line 1</TH>
				<TH>Address Line 2</TH>
				<TH>Address Line 3</TH>
				<TH>Address Line 4</TH>
				<TH>Suburb</TH>
				<TH>Postal Code</TH>
				<TH>Region</TH>
				<TH>Country</TH>
				<TH>&nbsp;</TH>
			</TR>
		</THEAD>
	~ ;
    
} #-------------------------------------------------------------------------------

sub page_opts {

	our $glyphicon = 'map-marker' ;
	our $lcpage    = 'venue' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ;
	our $table     = 'organisations' ;
	
	$s{no}         = 1 ;

	&common_min_add_extras ;

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

use common ;
use today ;

1;