#!/usr/bin/perl

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

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

use CGI::Carp qw(fatalsToBrowser);
use CGI;
use Mail::Sendmail;
use Fcntl qw(:flock);
use File::Copy;
use File::Basename;
use Excel::Writer::XLSX;

&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 ;
# our $double_box_layout = 1 ; # box on the right layout included

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

# our $allow_add_override = 0 ; if ($user_type eq 'ops_users') { $allow_add_override = 1 ; }

&page_opts ;

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

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

our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab
our $srchscr   = 0 ;
our $fnsortcol = 0 ;
our $redirtype = 'list' ; # $redirtype = 'search' ;

&common_min_action;

exit;

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

sub validate {

# called from common_min_action

my $exists   = '' ;

&db_min_ro($table,'*',"name='$i{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',"'$i{name}' AS A CUSTOMER NAME ALREADY EXISTS!",'ok') ;
	%col_name = ();
    # &add_screen;
    # &screen1;
	&common_min_add_screen;
    &common_min_screen1;
}

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

sub insert {

&add_db_fields ;

$i{last_edited_by} = $userid ; 
$i{user_id} = $userid ;

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

$i{date_time}    = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
$i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;

# &common_upload_files("trackusers/$i{id}") ;
# &process_upload_ifields;

# $ignore{country_id} = 1 ;

&default_values ;

&db_min_insert($table) ;

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

sub update {

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

&edit_db_fields ;

if ($userid) { $i{last_edited_by} = $userid ; }

unless ($i{active})  { $i{active} = '0' ; }

$i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;

# &common_upload_files("trackusers/$i{id}") ;
# &process_upload_ifields;

# $ignore{country_id} = 1 ;

&default_values ;

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

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

sub default_values {
	
	$i{country_id} 	= '0' unless $i{country_id} ;
	$i{region_id} 	= '0' unless $i{region_id} 	;
	$i{city_id} 	= '0' unless $i{city_id}	;
	
} #------------------------------------------------------------------------------------------

sub report_ifields {
	
&db_open_ro ;
    our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
	&load_search_vars ;
	$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
&db_close_conn ;
	
if ($i{customer_id}) {
    push @report_sql, "(`id` = '$i{customer_id}')" ;
    push @report_results, "customer = $customer_name{$i{customer_id}}" ;
    $xlsreportname .= '-' . $i{customer_id} ;
	our $acc_id_sql_where = "`customer_id`='$i{customer_id}'"
	}
	
# if ($i{company_id}) {
    # push @report_sql, "(`company_id` = '$i{company_id}')" ;
    # push @report_results, "company = $company_name{$i{company_id}}" ;
    # $xlsreportname .= '-' . $i{company_id} ;
	# }
	
# if ($i{asset_insurer_id}) {
    # push @report_sql, "(`asset_insurer_id` = '$i{asset_insurer_id}')" ;
    # push @report_results, "asset insurer = $asset_insurer_name{$i{asset_insurer_id}}" ;
    # $xlsreportname .= '-' . $i{asset_insurer_id} ;
	# }
	
if ($i{active}) {
    my $active = '' ; if ($i{active} eq 'active') { $active = '1' ; } elsif ($i{active} eq 'inactive') { $active = '0' ; }
    push @report_sql, "(`active` = '$active')" ;
    push @report_results, "active = $i{active}" ;
}
	
$report_results_msg = uc join(', ', @report_results) ;

unless ($report_results_msg) { $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); &report_screen; } else { $isaved = qq(SELECT WHERE $report_results_msg) ; }
 
} #------------------------------------------------------------------------------------------

sub load_search_vars {

# &db_min_ro('customer','id,name','','','') ;
# foreach my $id (keys %{$db{customer}}) { $customer_name{$id} = $db{customer}{$id}{name} ; }
	
# &db_min_ro('company','id,name','','','') ;
# foreach my $id (keys %{$db{company}}) { $company_name{$id} = $db{company}{$id}{name} ; }
	
&db_min_ro('users','id,name','','','') ;
foreach my $id (keys %{$db{users}}) { $user{$id} = $db{users}{$id}{name} ; }

our $done_load_search_vars = 1 ;

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

# sub process_upload_ifields {

# foreach (keys %uploads_file) { $i{$_} = $uploads_file{$_} ; $ignore{$_} = '' ; }

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

sub list_screen {
	
my %seen_customer  = () ; 
my $delete_button = "" ;	

my $srch_where_sql = join(' AND ', @report_sql) ;

my $add_sql_where = '' ;

unless ($done_load_search_vars) { &load_search_vars ; }
    
# our @sql_col_display = ("id","customer_nr","name","contact_email","vat_nr","physical_address","postal_address","date_time","last_edited_by","user_id","active","last_updated","phone","company_email") ;
our @sql_col_display = ("id","name","contact_email","vat_nr","physical_address","postal_address","active","events","analytics","phone","company_email","last_updated","last_edited_by") ;

if ($iaction eq 'report') { push @sql_col_display, "company_id" ; }
	
push @sql_col_display, "" ;

&report_xlsx_export_header("Customers$xlsreportname",'customers') ;

&db_open_ro ;
    our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
	
		&db_min_ro('event_quotes','id, quote_to','','','') ; 

		foreach my $id (keys %{$db{'event_quotes'}}) {
			next if $seen_customer{$db{'event_quotes'}{$id}{quote_to}} ; 
			$seen_customer{$db{'event_quotes'}{$id}{quote_to}} = 1 ; 
		}	

		&db_min_ro('quotes','id, quote_to','','','') ; 

		foreach my $id (keys %{$db{'quotes'}}) {
			next if $seen_customer{$db{'quotes'}{$id}{quote_to}} ; 
			$seen_customer{$db{'quotes'}{$id}{quote_to}} = 1 ; 
		}
		
		&load_list_vars("$srch_where_sql$add_sql_where") ;
		
	$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
&db_close_conn ;

$xlsxrow = 4 ;

our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; 

foreach my $id (sort {$b <=> $a} keys %{$db{$table}}) {
    
	# if (($i{active} == 1) and ($customer_id_in_use_for_devices{$id} < 1)) { next ; } # Active with devices
	# if (($i{active} == 2) and ($customer_id_in_use_for_devices{$id} > 0)) { next ; } # Active without devices
	
	$print_tbody .= qq(<tr>) ;
	
	$xlsxcol=0;
	 
	foreach (@sql_col_display) {
		unless ($_) { next ; } # blank for the buttons column
        my $val = $db{$table}{$id}{$_} ;
		my $align = '' ;
		my $val_xlsx = '' ;
		
		# if ($_ eq 'last_edited_by') {  }
		
		# if ($_ eq 'device_types') {
			# $val = '' ; 
			# foreach $dev_nam (keys %{$cnt_dev_typ{$id}}) {
				# $val .=  "$dev_nam [$cnt_dev_typ{$id}{$dev_nam}], "; 
				# }
			# $val = substr($val,0,-2) ;
			# }
		
		# my $format = '' ; if ($_ eq 'imei') { if (length($db{$table}{$id}{imei})==5){ $format = 'imei' ; } }
		
        # &report_xlsx_export_process_cell('','',$val) ; # ------------------------------------------------------------------------- HTML AFTER$xlscol++; 
		
		# my $green_tick  = qq~<span style="display:none;">2</span><span class="label label-success"><i class="glyphicon glyphicon-ok"></i></span>~ ;
		# my $orange_tick = qq~<span style="display:none;">1</span><span class="label label-warning"><i class="glyphicon glyphicon-ok"></i></span>~ ;
		# my $red_tick    = qq~<span style="display:none;">0</span><span class="label label-danger"><i class="glyphicon glyphicon-ok"></i></span>~ ;
		my $center = qq~ class="dt-center"~ ;
		
		if ($_ eq 'active' || $_ eq 'events' || $_ eq 'analytics') { 
			$val_xlsx = ($val == 1) ? "Yes" : "No" ; 
			if ($val == 1) { 
				$val = &set_tick('green', '') ; 
			} else { 
				$val = &set_tick('red', '') ; 
			} 
			$align = $center ; 
		} elsif ($_ eq 'last_edited_by') {
			$val = $user{$db{$table}{$id}{$_}} ;
		} elsif ($_ eq 'last_updated') {
			$val = &common_min_date_as_string($val) ;
		}
		
		$val_xlsx = $val unless $val_xlsx ;
		
		&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format1) ;
		$xlsxcol++ ;
		
		# if ($_ eq 'monitor_after_hours_snapshots') { if ($val == 1) { $val = &set_tick('green', '') ; } else { $val = &set_tick('red', '') ; } $align = $center ; }		
		# if ($_ eq 'facial_recognition')            { if ($val == 1) { $val = &set_tick('green', '') ; } else { $val = &set_tick('red', '') ; } $align = $center ; }		
		# if ($_ eq 'object_recognition')            { 
			# if ($val == 1) { 
				# if ($protocol_action{$id}) {
					# my $tt = qq~ data-toggle="tooltip" data-placement="left" data-title="$protocol_action{$id}"~ ;
					# $val = &set_tick('green', $tt) ;
					# }
				# else
					# {
					# my $tt = qq~ data-toggle="tooltip" data-placement="left" data-title="Needs protocol actions set!"~ ;
					# $val = &set_tick('orange', $tt) ; 
					# }
				# } 
			# else 
				# {
				# $val = &set_tick('red', '') ;
				# } 
			# $align = $center ; 
			# }	

		# $protocol_action{$acc_id}		
		
		# data-toggle="tooltip" data-placement="right" data-title="Set to 'Yes' to enable Object Recognition for this client!"
		
		$print_tbody .= qq(<td $align>$val</td>) ;  
	}
		
	my $delete_butt = '' ; my $edit_butt = '' ;	
	
	if ($useropts{boss}{$username} or $useropts{super}{$username}) {
		$edit_butt   = qq(<a class="btn btn-info btn-xs" href="javascript:editMinItem('$id');"><i class="glyphicon glyphicon-edit icon-white"></i></a>) ;
		if ($useropts{super}{$username}) {
			$delete_butt = qq(<a class="btn btn-danger btn-xs" href="javascript:deleteMinItem('$db{$table}{$id}{name}','$id')"><i class="glyphicon glyphicon-trash icon-white"></i></a>) if not $seen_customer{$id}; 
			$delete_butt = qq(<a class="btn btn-default btn-xs" href="#" title data-toggle="tooltip" data-original-title="In system use!"><i class="glyphicon glyphicon-trash icon-white"></i></a>) if $seen_customer{$id}; 
		}
	}
        
        # &common_debug("$id : $customer_id_in_use_for_devices{$id}");
        
    if ($customer_id_in_use_for_devices{$id}) { $delete_butt = '' ; }
		
	$print_tbody .= qq~<td nowrap>&nbsp;$edit_butt&nbsp;$delete_butt</td></tr>~ ;
    $xlsxrow++ ;

}

$worksheet{$ws}->set_column("A:L",15) ;

&report_xlsx_export_footer('L',15,'customers') ;

$fnsortcol = 8 ; # order by ol devices col

$print_more_boxes .= qq(<br><button type="button" class="btn btn-default" onclick="history.go(-1);">Back</button>) ;
	
&common_min_extra_crumb("search-$lcpage\s","Search Screen") ;
	
} #------------------------------------------------------------------------------------------

sub set_tick {
	
my ($color,$tooltip) = @_ ;
	
$tick{green}  = qq~<span style="display:none;">2</span><span class="label label-success"><i $tooltip class="glyphicon glyphicon-ok"></i></span>~ ;
$tick{orange} = qq~<span style="display:none;">1</span><span class="label label-warning"><i $tooltip class="glyphicon glyphicon-ok"></i></span>~ ;
$tick{red}    = qq~<span style="display:none;">0</span><span class="label label-danger"><i $tooltip class="glyphicon glyphicon-remove"></i></span>~ ;

return ($tick{$color}) ;
		
} #------------------------------------------------------------------------------------------

sub load_list_vars {
	
my ($where) = @_ ;
	
# &db_min_ro('insurer','*','','','') ;
# foreach my $id (keys %{$db{insurer}}) { $insurer{$id} = $db{insurer}{$id}{name} ; }

# &db_min_ro('device_type','*','','','') ;
# foreach my $id (keys %{$db{device_type}}) { 
	# $is_mdvr{$id} = $db{device_type}{$id}{mdvr} ;
	# $device_name{$id} = $db{device_type}{$id}{name} ; 
	# }
	
# &db_min_ro('risk_profile_types','*','','','') ;
# foreach my $id (keys %{$db{risk_profile_types}}) { $risk_profile_type{$id} = $db{risk_profile_types}{$id}{name} ; }  # customer hash

# &db_min_ro('protocol_actions','*',$acc_id_sql_where,'','') ;
# foreach my $id (keys %{$db{protocol_actions}}) { 
	# my $acc_id   = $db{protocol_actions}{$id}{customer_id} ;
	# my $max      = $db{protocol_actions}{$id}{max} ;
	# my $show_max = '' ; if ($max) { $show_max = " > $max" ; }
	
	# $protocol_action{$acc_id} .= "$risk_profile_type{$db{protocol_actions}{$id}{risk_profile_type_id}}$show_max<br>" ; 
	# }

# &db_min_ro('device','id,customer_id,online,type_id',$acc_id_sql_where,'','') ;
# foreach my $id (keys %{$db{device}}) { 
	# $customer_id_in_use_for_devices{$db{device}{$id}{customer_id}}++ ; 
	
	# if ($db{device}{$id}{online}==1) {
		# $customer_online_devices{$db{device}{$id}{customer_id}}++ ; 
		# }
		
	# my $dev_nam = $device_name{$db{device}{$id}{type_id}} ;
	
	# $cnt_dev_typ{$db{device}{$id}{customer_id}}{$dev_nam}++ ;		
	# }
	
&db_min_ro($table,'*',$where,'name','') ;

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

sub thead {

&common_min_thead ;
    
} #-------------------------------------------------------------------------------

sub add_db_fields {

&common_customer_hidden_db_fields ;

$hidden{id} = 2 ;
# $hidden{user_id} = 2 ;


# $required{customer_nr} = 2 ;

if ($iaction eq 'add'){ &build_boxes_add ; } # can't be in add_screen, only works if here

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

sub edit_db_fields {

&common_customer_hidden_db_fields ;

$ignore{date_time} = 1 ;
$ignore{user_id} = 1 ;
# $ignore{customer_nr} = 1 ;
$ignore{last_updated} = 1 ;

# if ($user{privilege}{$username} eq 'super') {
	# $ignore{facial_recognition}             = '' ; # enable the switch for super users
	# $checkbox{facial_recognition}           = 1 ;
	# $info_glyph_tooltip{facial_recognition} = qq(<i style="margin-top:-3px" data-toggle="tooltip" data-placement="right" data-title="Set to 'Yes' to enable Driver Facial Recognition for this client!" class="glyphicons glyphicons-info-sign blue"></i>) ;
	
	# $ignore{object_recognition}             = '' ; # enable the switch for super users
	# $checkbox{object_recognition}           = 1 ;
	# $info_glyph_tooltip{object_recognition} = qq(<i style="margin-top:-3px" data-toggle="tooltip" data-placement="right" data-title="Set to 'Yes' to enable Object Recognition for this client!" class="glyphicons glyphicons-info-sign blue"></i>) ;
	# }

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

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

sub select_opts {

my ($id) = @_ ;
	
# &common_min_select_opts('asset_insurer_id','insurer','name',$db{$table}{$id}{asset_insurer_id}) ;
# &common_min_select_opts('git_insurer_id','insurer','name',$db{$table}{$id}{git_insurer_id}) ;
# &common_min_select_opts('insure_as_id','insurer','name',$db{$table}{$id}{insure_as_id}) ;
# &common_min_select_opts('company_id','company','name',$db{$table}{$id}{company_id},1) ;

# $db{$table}{$id}{country_id} = '242' unless $db{$table}{$id}{country_id} ;

# $db{$table}{$id}{region_id} = 1 ;

# &db_min_ro('regions','1,country_id',"`id`='$db{$table}{$id}{region_id}'",'','') if $db{$table}{$id}{region_id} ; 

# $db{$table}{$id}{country_id} = $db{regions}{1}{country_id} ;

# my $regions_sql = ($db{regions}{1}{country_id}) ? "`country_id`='$db{regions}{1}{country_id}'" : "" ;
my $regions_sql = ($db{$table}{$id}{country_id}) ? "`country_id`='$db{$table}{$id}{country_id}'" : "" ;

$regions_sql = &add_extra_region_filter($regions_sql) ; 

&common_min_select_opts('region_id','regions','name',$db{$table}{$id}{region_id},'','code',"$regions_sql") ;

my $other_region = qq~~ ;
if ($db{$table}{$id}{country_id} && !$opts{region_id}) {
	$other_region = qq~id='13'~ ;
	&common_min_select_opts('region_id','regions','name',$db{$table}{$id}{region_id},'','code',"name='Other'") ;
}


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

my $city_sql ;

$city_sql .= qq~country_id='$db{$table}{$id}{country_id}'~ if $db{$table}{$id}{country_id} ;
$city_sql .= qq~ AND ~ if $db{$table}{$id}{country_id} && $db{$table}{$id}{region_id} ;
$city_sql .= qq~region_id='$db{$table}{$id}{region_id}'~ if $db{$table}{$id}{region_id} ;
$city_sql = qq~($city_sql) OR region_$other_region~ if $other_region ;
# $other_region = "region_$other_region" if $other_region ;

&common_min_select_opts('city_id','cities','name',$db{$table}{$id}{city_id},'','',"$city_sql") ; 

$trigger_jquery_raw .= qq~

    //gallery delete
    \$('.thumbnails').on('click', '.gallery-delete', function (e) {
        e.preventDefault();
        // alert(\$(this).parents('.thumbnail').attr('id'));
        var imgid = \$(this).parents('.thumbnail').attr('id') ;
        var thumb = \$(this).parents('.thumbnail');
        BootstrapDialog.confirm({
        title: 'Confirm Delete',
        message: 'Are you sure you want to delete it?',
        type: BootstrapDialog.TYPE_WARNING,
        callback: function(result) {            
            if(result) {
                var url = "$useropts{scripts}/get/get_db_delete_upload_common.pl?$i{id}&trackusers/$i{id}&customer&"+imgid ; 
                // alert(url);
                \$.get(url);
                thumb.fadeOut();
                location.reload();
                }
            }
        });
        
    });
    
    //gallery edit
    \$('.thumbnails').on('click', '.gallery-edit', function (e) {
        e.preventDefault();
        //get image id
        alert('Delete logo and re-upload!');
        //alert(\$(this).parents('.thumbnail').attr('id'));
        //dlgMdl('/scripts/dialog/uploads.pl?$i{id}&photo&'+\$(this).parents('.thumbnail').attr('id'),'Photo Uploads','','medium-dialog');
    });
	
	\$("#customers-form [id^='select']").chosen({ allow_single_deselect:true });
	
	const mapCityToRegion = {};
	const mapCityToCountry = {};
	const mapRegionToCountry = {};

	const \$countrySelect = \$("#selectCountry_id") ;
	const \$regionSelect = \$("#selectRegion_id") ;
	const \$citySelect = \$("#selectCity_id") ;
	
	let countryId = \$countrySelect.val() ; 
	let regionId = \$regionSelect.val() ; 
	let cityId = \$citySelect.val() ; 
	
	const updateChosen = \$el => \$el.trigger("chosen:updated");

	const clearSelect = (\$el, includeBlank = true) => {
		\$el.empty();
		if (includeBlank) \$el.append(`<option value="0"></option>`);
		updateChosen(\$el) ;
	};

	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 = (\$el, dataList, labelFn) => {
		// let lastId = null ;
		// for (const data of dataList) {
			// \$el.append(`<option value="\${data.id}">\${labelFn(data)}</option>`);
			// lastId = data.id;
		// }
		// updateChosen(\$el) ;
		// return { count: dataList.length, lastId } ;
	// } ;

	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 === "" ;
		
		let lastId = null ;
		json_list.forEach(data => {
			const selected = autoSelectOnly || isSelected(data) ? "selected" : "" ;
			\$field.append(`<option value="\${data.id}" \${selected}>\${getLabel(data)}</option>`) ;
			lastId = data.id;
		});

		updateChosen(\$field) ;
		// return json_list.length ;
		return { count: json_list.length, lastId } ;
	};

	// --- Country Change ---
	
	\$countrySelect.on("change", async function () {
		
		countryId = \$(this).val() ;
		regionId = \$regionSelect.val() ;  
		cityId = \$citySelect.val() ;  
		
		clearSelect(\$regionSelect) ;
		
		const regionUrl = `$useropts{scripts}/get/get_regions_from_country.pl?country_id=\${countryId}`;
		const regionData = await fetchJSON(regionUrl);
		 
		// const { count: regionCount, lastId: region_est } = populateSelect(
		const { count: regionCount, lastId: region_est } = populateSelect(
			\$regionSelect,
			regionData,
			// ({ name, code }) => `\${name} [\${code}]`
			r => r.code ? `\${r.name} [\${r.code}]` : r.name , 
			""
		) ;

		let selectedRegionId = 0 ;
		
		if (regionCount === 1) {
			selectedRegionId = region_est ;
			// \$regionSelect.val(region_est).trigger("chosen:updated") ;
		} else if (regionCount === 0) {
			selectedRegionId = 13 ;
			\$regionSelect.append(`<option value="13" selected>Other [OT]</option>`).trigger("chosen:updated") ;
			// updateChosen(\$regionSelect) ;
		}
		
		// if (!\$regionSelect.val()) {
			// \$regionSelect.val(regionId).trigger("chosen:updated") ; 
		// } 

		// Load cities based on region (if available) or country
		clearSelect(\$citySelect);

		const script = `get_cities_from_region.pl?country_id=\${countryId}&region_id=\${selectedRegionId}`  ;
		const citiesUrl = `$useropts{scripts}/get/\${script}` ;
		const cityData = await fetchJSON(citiesUrl) ;
		
		const { count: cityCount, lastId: city_est } = populateSelect(
			\$citySelect,
			cityData,
			d => d.city_name ?? d.name,
			""
		) ;

		// if (cityCount === 1) {
			// \$citySelect.val(cityId).trigger("chosen:updated") ;
		// }
	 
		if (!countryId) {
			console.log("2 countryId : "+countryId) ; 
			if (!\$regionSelect.val()) \$regionSelect.val(regionId).trigger("chosen:updated") ;
			if (!\$citySelect.val()) \$citySelect.val(cityId).trigger("chosen:updated") ;
		}
		
	});

	// --- Region Change ---
	
	\$regionSelect.on("change", async function () {
		
		console.log("1 : regionId : "+regionId) ; 
		regionId = \$(this).val();
		console.log("2 : regionId : "+regionId) ; 
		countryId = \$countrySelect.val();
		cityId = \$citySelect.val() ;  
		
		clearSelect(\$citySelect);

		if (!regionId) return;

		const url = `$useropts{scripts}/get/get_cities_from_region.pl?country_id=\${countryId}&region_id=\${regionId}`;
		const cityData = await fetchJSON(url);
		const { count: cityCount, lastId: city_est } = populateSelect(\$citySelect, cityData, d => d.city_name,"");

		// if (cityCount === 1) {
			// \$citySelect.val(cityId).trigger("chosen:updated");
		// }

		if (!mapRegionToCountry[regionId]) {
			const lookupUrl = `$useropts{scripts}/get/get_country_from_region.pl?country_id=\${countryId}&region_id=\${regionId}`;
			const regionMeta = await fetchJSON(lookupUrl);

			const { country_id } = regionMeta[0] ?? {};
			if (country_id) {
				mapRegionToCountry[regionId] = country_id;
				\$countrySelect.val(country_id).trigger("chosen:updated");
			} 
		} else {
			\$countrySelect.val(mapRegionToCountry[regionId]).trigger("chosen:updated");
		}
		
		if (!regionId && !\$citySelect.val()) {
			\$citySelect.val(cityId).trigger("chosen:updated") ;
		}
		
	});

	// --- City Change ---
	
	\$citySelect.on("change", async function () {
		
		cityId = \$(this).val();
		if (!cityId) return;

		regionId = mapCityToRegion[cityId];
		countryId = mapCityToCountry[cityId];
		
		if (typeof regionId === 'undefined') regionId = "" ;
		if (typeof countryId === 'undefined') countryId = "" ;
		
		if (regionId && regionId != \$regionSelect.val()) {
			\$regionSelect.val(regionId).trigger("chosen:updated");
		}
		if (countryId && countryId != \$countrySelect.val()) {
			\$countrySelect.val(countryId).trigger("chosen:updated");
		}

		if (!regionId || !countryId) {
		
			const lookupUrl = `$useropts{scripts}/get/get_country_and_region_from_city.pl?city_id=\${cityId}&region_id=\${regionId}&country_id=\${countryId}`;
			const cityMeta = await fetchJSON(lookupUrl);
			const { region_id, country_id } = cityMeta[0] ?? {};
 
			if (region_id) {
				mapCityToRegion[cityId] = region_id;
				\$regionSelect.val(region_id).trigger("chosen:updated");
			}

			if (country_id) {
				mapCityToCountry[cityId] = country_id;
				\$countrySelect.val(country_id).trigger("chosen:updated");
			} 
		}
		
		if (!\$regionSelect.val()) {
			\$regionSelect.val("13").trigger("chosen:updated");
			mapCityToCountry[cityId] = 13;
		}
		
	});	
	
~ ;
		
} #-------------------------------------------------------------------------------

sub add_screen {

# called from common_add_screen

# if ($user_type eq 'track_users') {	
	# $db{$table}{''}{customer_id} = $client_id ; # set for input box
    # }

&select_opts('') ;

# &build_boxes_add ; # can't do this here

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

sub build_boxes_add {
	
&sort_fields ; 

$print_box_content_rows .= &common_min_forms_start($table) ;

$print_box_content_rows .= qq(<div class='row'><div class='col-md-6'>) ;
$print_box_content_rows .= &common_min_box_top('user',"&nbsp;&nbsp;Customer",$box_main_bg) ;  
# $print_box_content_rows .= &common_add_form($table,'',3,9,1,1) ;
$print_box_content_rows .= &common_min_add_form($table,'save',3,9,1,1) ;
$print_box_content_rows .= &common_min_box_foot ;
$print_box_content_rows .= qq(</div><div class='col-md-6'>) ;

&build_boxes_right;

$print_box_content_rows .= qq(</div></div>) ;

$print_box_content_rows .= &common_min_forms_end('',$table,'save') ;

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

sub edit_screen {

our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ;

# $selected{warranty_period}{$db{$table}{$id}{warranty_period}} = 'SELECTED';

&sort_fields ; 
&select_opts($i{id}) ;

# &build_boxes_edit($i{id}) ;   

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

sub sort_fields {
 
	%sort_field = () ;
	
	$sort_field{1}  = 'active' ; 
	$sort_field{2}  = 'events' ; 
	$sort_field{3}  = 'analytics' ; 
	$sort_field{4}  = 'name' ; 
	$sort_field{5}  = 'phone' ; 
	$sort_field{6}  = 'company_email' ; 
	$sort_field{7}  = 'contact_name' ; 
	$sort_field{8}  = 'contact_email' ; 
	$sort_field{9}  = 'physical_address' ; 
	$sort_field{10} = 'postal_address' ; 
	$sort_field{11} = 'country_id' ; 
	$sort_field{12} = 'region_id' ; 
	$sort_field{13} = 'city_id' ; 
	$sort_field{14} = 'vat_nr' ; 
 
	$select{country_id} = 1 ; 
	$select{region_id} = 1 ; 
	$select{city_id} = 1 ; 
	
	$trigger_jquery_raw .= qq~
	
	
	
	~ ; 
	
} #------------------------------------------------------------------------------------------

sub build_boxes_edit {

my ($id) = @_ ;

$print_box_content_rows  .= &common_min_forms_start($table) ;
$print_box_content_rows  .= qq(<div class='row'><div class='col-md-6'>) ;
$print_box_content_rows  .= &common_min_box_top('user',"&nbsp;&nbsp;Customer : $db{$table}{$id}{id}",$box_main_bg) ;  
# $print_box_content_rows .= &common_edit_form($id,$table,'',3,9,1,1) ;
$print_box_content_rows  .= &common_min_edit_form($i{id},$table,'update',3,9,1,1) ;
$print_box_content_rows  .= &common_min_box_foot ;
$print_box_content_rows  .= qq(</div><div class='col-md-6'>) ;   

&build_boxes_right($id);

$print_box_content_rows  .= qq(</div></div>) ;

$print_box_content_rows  .= &common_min_forms_end($id,$table,'update',$skip) ;

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

sub build_boxes_right {

my ($id) = @_ ;

my $box_icon = '' ;

$print_box_content_rows .= &common_min_box_top('picture','Logo Upload',$box_right_bg,$box_icon) ;
                           
$logo_uploads            = &get_uploads($id,'logo') ;

$print_box_content_rows .= qq(<div class="row"><div class="col-md-12">&nbsp;</div></div><div class="row">);

if ($logo_uploads) {
    $print_box_content_rows .= qq(<div class="col-md-6" id="logos">$logo_uploads</div>); 
} else {
    $print_box_content_rows .= qq(<div class="col-md-6"><div class="form-group">
            <label for="imageInputFile">Attach Logo</label>
            <input type="file" id="imageInputFile" name='iattachlogo' tabindex='$tindex'>
            <p class="help-block">Upload file from PC.</p>
        </div></div>);
    }
        
$print_box_content_rows .= qq(</div>);
    
$print_box_content_rows .= &common_min_box_foot ;
                          
} #----------------------------------------------------------------------------------------

sub get_uploads {

my ($id,$type) = @_ ;

unless ($id and $type) { return() ; }

my $gallery = '' ; my %gallery = () ;

my $field = $type ;
if ($db{$table}{$id}{$field}){
    $tooltip = qq(data-toggle="tooltip" data-placement="top" title="$type" data-original-title="$type") ;
    $gallery{$type} .= qq(<li id="$type-$db{$table}{$id}{$field}" class="thumbnail" $tooltip>
            <a style="background:url(/mediastorage/trackusers/$id/$db{$table}{$id}{case_nr}/$db{$table}{$id}{$field})" title="$type" href="/mediastorage/trackusers/$id/$db{$table}{$id}{case_nr}/$db{$table}{$id}{$field}"><img class="grayscale" src="/mediastorage/trackusers/$id/$db{$table}{$id}{case_nr}/$db{$table}{$id}{$field}" alt="$type" style="position:relative;max-height:100%;"></a>
        </li>) ;
    }

if ($gallery{$type}) { $gallery = '<ul class="thumbnails gallery">' . $gallery{$type} . '</ul>' ; }

return ($gallery) ;

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

sub page_opts {

our $glyphicon = 'list' ;
our $lcpage    = 'customer' ;

&common_page_name ;
   
our $table     = 'customers' ;

$page_title  = 'Customer' ;

&common_min_add_extras ;

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

sub report_screen {

our $lcol = 3 ;
our $fcol = 5 ;

$print_box_content_rows .= &common_min_forms_start('report') ;

&db_open_ro ;
    our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
	
	&common_min_select_opts('customer_id','customers','name',$i{customer_id},'') ;
	# &common_min_select_opts('company_id','company','name',$i{company_id},'') ;
		
	# &common_min_select_opts('asset_insurer_id','insurer','name',$i{asset_insurer_id},'') ;
	$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
&db_close_conn ;

$print_box_content_rows .= &common_min_form_select('customer_id',$i{customer_id}) ; 
# $print_box_content_rows .= &common_min_form_select('company_id',$i{company_id}) ; 
# $print_box_content_rows .= &common_min_form_select('asset_insurer_id',$i{asset_insurer_id}) ; 
$print_box_content_rows .= &common_min_form_input('active',$i{active}) ;

$opts{active} = qq(<option value=""></option>
<option $selected{active}{active} value="active">Active</option>
<option $selected{active}{inactive} value="inactive">Inactive</option>) ; 
$print_box_content_rows .= &common_min_form_select('active','','',1,'') ; 
 
$print_box_content_rows .= &common_min_forms_end('','','report') ;

&common_min_search_screen ;

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

# sub send_email {
	
# my ($email_subject,$email_msg) = @_ ;

# unless ($email_msg) { return ; }

# my %mail = () ;

# my $to  = 'duvan@kre8it.co.za' ;
# my $cc  = 'rory@kre8it.co.za' ;
        
# %mail = (
         # smtp    => 'localhost',
         # From    => 'TruckAssist IT <it@truckassist.co.za>',
         # To      => $to,
		 # Cc      => $cc,
         # Subject => $email_subject
         # );

# $mail{body} = <<END_OF_BODY;

# $email_msg

# END_OF_BODY

# sendmail(%mail) ;

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

use common ;
use report ;
use xlsxcreator ;
use today ;

1;