#!/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 ;
# our $testing = 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}) ;
	
	## REMOVE LATER ---------------------------------
	
	$i{city} = $i{name} ; 
	
	## REMOVE LATER ---------------------------------
	
	&db_min_ro($table,'*',"name='$i{name}'",'name','') ;

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

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

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

sub insert {

	&add_db_fields ;
	
	&set_default_vals ;
	
	$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 ;
	
	&set_default_vals ;
	
	$ignore{country_id} = 1 ;
	
	&db_min_upd($table,"id='$i{id}'") ;

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

sub set_default_vals {
	
	&db_min_ro('regions','id,name',"id = $i{region_id}",'','') ;
	$i{province} = $db{regions}{$i{region_id}}{name};
	
} #------------------------------------------------------------------------------------------

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

	foreach my $_id (keys %{$db{event_quotes}}) {
		$type_id_used{$_} = 1 ;
		my @city_ids = split(/\,/,$db{event_quotes}{$_id}{city_id});
		foreach my $_cid (@city_ids) { 
			$type_id_used{$_cid} = 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 ($type_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>~ ;  
		}
		
		$print_tbody .= qq~<tr id="$id">
			<td>$id</td>
			<td>$db{$table}{$id}{name}</td>
			<td>$db{$table}{$id}{city_short}</td> 
			<td>$db{$table}{$id}{lat}</td>
			<td>$db{$table}{$id}{lng}</td>
			<td>$db{regions}{$db{$table}{$id}{region_id}}{name}</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 {
	
	&sort_fields;
		
	&hidden_db_fields;

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

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

sub hidden_db_fields {
	
	$ignore{iaction}        = 1 ;
	$required{name}         = 1 ;
	# $required{province}     = 1 ;
	$required{region_id}     = 1 ;
	
	# $ignore{country_id} = 1 ;
	
} #------------------------------------------------------------------------------------------

sub sort_fields {
	
	%sort_field = () ;
	
	# $ignore{country_id} = '' ;
	

	$sort_field{3}  = 'name' ; $preferred_title{city_short} = "City Name" ;
	$sort_field{4}  = 'city_short' ; $preferred_title{city_short} = "City Acronym" ;
	# $sort_field{3}  = 'province' ; $preferred_title{province} = 'Region' ;
	$sort_field{5}  = 'lat' ; $preferred_title{lat} = 'Latitude' ;
	$sort_field{6}  = 'lng' ; $preferred_title{lng} = 'Longitude' ; 
	$sort_field{7}  = 'region_id' ;
	$sort_field{8}  = 'country_id' ;

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

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>~ ;
	
	# my $sql_or = '' ;
	
	# if ($is_schools_manager || $is_operator) {
		# @report_sql_or = () ;
		# foreach $_reg_id (keys %{$glob_regids{$userid}}) {
			# push @report_sql_or, "id = '$_reg_id'"
		# }
		# $sql_or = join(' OR ',@report_sql_or) ;
	# }
	
	my $sql_or = ($is_schools_manager || $is_operator) ? join(' OR ', map { "id = '$_'" } keys %{$glob_regids{$userid}}) : '' ;
	
	$allow_deselect{country_id} = 1 ;
	
	# &common_min_select_opts('province','regions','name',$db{$table}{$i{id}}{province},'','',$sql_or,'name');
	
	&common_min_select_opts('region_id','regions','name',$db{$table}{$i{id}}{region_id},'','code',$sql_or,'');

	&common_min_select_opts('country_id','countries','name',$db{regions}{$db{$table}{$i{id}}{region_id}}{country_id},'','','','');

	$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 {

	$print_thead = qq~<THEAD><TR><TH>ID</TH><TH>CITY NAME</TH><TH>CITY ACRONYM</TH><TH>LAT</TH><TH>LNG</TH><TH>REGION</TH><TH>COUNTRY</TH><TH>&nbsp;</TH></TR></THEAD>~ ;
    
} #-------------------------------------------------------------------------------

sub page_opts {

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

	&common_min_add_extras ;

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

use common ;
use today ;

1;