
sub users_list_screen {

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

	foreach my $id (keys %{$db{$table}}) {
		
		$delete_button = ($seen_operator{$id}) ? 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>~ : qq~<a class="btn btn-danger btn-xs" href="javascript:deleteMinItem('$db{$table}{$id}{username}','$db{$table}{$id}{id}')"><i class="glyphicon glyphicon-trash icon-white"></i></a>~  ;
		
		my $disp_blocked = qq~<span class="label label-success" title="Active!" data-toggle="tooltip"><i class="glyphicon glyphicon-ok"></i></span>~; 
		if ($db{$table}{$id}{block} || $db{$table}{$id}{inactive} ) { $disp_blocked = qq~<span class="label label-danger" title="Blocked!" data-toggle="tooltip"><i class="glyphicon glyphicon-remove"></i></span>~; }
		
		# if (!$useropts{it}{$username} && (substr($db{$table}{$id}{username},0,4) eq 'rory' || substr($db{$table}{$id}{username},0,6) eq 'handre')) { next ; }
		
		my $it_username_subs_4 = substr($db{$table}{$id}{username},0,4) ; # rory / jean
		my $it_username_subs_6 = substr($db{$table}{$id}{username},0,6) ; # handre
		
		if (($useropts{it}{$it_username_subs_4} || $useropts{it}{$it_username_subs_6}) && !$useropts{it}{$username} && $useremail =~ /re8it/g) { next ; }
		
		next if $glod_user_level < 4 && $level{$db{$table}{$id}{user_type}} > 1 && $user_type eq 'casual' ;
		
		$opts{$lcpage} .= qq~<option value="$db{$table}{$id}{username}">$db{$table}{$id}{name}</option>~ ;
		$print_tbody   .= qq~<tr id="$id">
			<td>$id</td>
			<td>$db{$table}{$id}{username}</td>
			<td>$db{$table}{$id}{name}</td>
			<td>$db{$table}{$id}{email}</td>
			<td>$disp_blocked</td>
			<td>$db{$table}{$id}{based_in}</td>~ ;
			
		$print_tbody  .= qq~
			<td>$level{$db{$table}{$id}{user_type}}</td>~ if $user_type eq 'casual' ;
			
		$print_tbody  .= qq~
			<td>$db{$table}{$id}{lastupdate}</td>
			<td>$db{$table}{$id}{lastvisitdate}</td>
			<td nowrap>
				&nbsp;<a class="btn btn-info btn-xs" href="javascript:editMinItem('$db{$table}{$id}{id}');"><i class="glyphicon glyphicon-edit icon-white"></i></a>
				&nbsp;$delete_button
			</td>
		</tr>~ ;
    }

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

sub users_list_vars {

	our %seen = () ; our %seen_operator = () ; our $delete_button = '' ;

	&db_min_ro('events','id, user_id','','','') ; 

	foreach my $id (keys %{$db{'events'}}) {
		next if $seen{$db{'events'}{$id}{user_id}} ; 
		$seen{$db{'events'}{$id}{user_id}} = 1 ; 
	}

	&db_min_ro('event_quotes','id,user_id,operator_ids,daily_operator_ids','','','') ; 

	foreach my $id (keys %{$db{event_quotes}}) {
		# next if $seen{$db{event_quotes}{$id}{user_id}} ; 
		$seen{$db{event_quotes}{$id}{user_id}} = 1 ;
		my $op_ids = $db{event_quotes}{$id}{operator_ids} ;
		next unless $op_ids ;
		my @op_ids = ($op_ids =~ /;/) ? split(/;/,$op_ids) : split(/,/,$op_ids) ;
		for my $op_id (@op_ids) {
			next if $seen_operator{$op_id} || !$op_id ;
			$seen_operator{$op_id} = 1 ;
		}
		foreach my $op_ids_list (split(/\|/,$db{event_quotes}{$id}{daily_operator_ids})) { 
			next unless $op_ids_list  ;
			foreach my $op_id (split(/\;/,$op_ids_list)) {
				next if $seen_operator{$op_id} || !$op_id ;
				$seen_operator{$op_id} = 1 if $op_id ;
			}
		}
	}

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

	foreach my $id (keys %{$db{quotes}}) {
		next if $seen{$db{quotes}{$id}{user_id}} ; 
		$seen{$db{quotes}{$id}{user_id}} = 1 ; 
	}
	
	$level{casual_a} = 1 ;
	$level{casual_b} = 2 ;
	$level{casual_c} = 3 ;
	
	if ($user_type eq 'coding_provider') { 
		&db_min_ro('analytics_event_bookings','id,fixtures_saved_values','','','') ;
		foreach my $id (keys %{$db{analytics_event_bookings}}) {
			my @split1 = split(/\|/,$db{analytics_event_bookings}{$id}{fixtures_saved_values}) ;
			foreach my $row (@split1) {
				my @split2 = split(/\;/,$row) ;
				$seen{$split2[-2]} = 1 ;  
			}
		}
	}
	
	if ($user_type eq 'analytics_client') {
		&db_min_ro('analytics_event_bookings','id,client_id','','','') ;
		foreach (keys %{$db{analytics_event_bookings}}) {
			$seen{$db{analytics_event_bookings}{$_}{client_id}} = 1 ;  
		}
	}

	# my $cust_sql_where = "user_type = '$user_type'" if $user_type ;
	my $cust_sql_where = ($user_type) ? "user_type LIKE '$user_type%'" : "user_type NOT LIKE 'casual%' AND user_type <> 'schools_manager' AND user_type <> 'installation_partner'" ;

	&db_min_ro($table,'*',$cust_sql_where,'username','') ;
	
} #------------------------------------------------------------------------------------------

sub users_sort_fields {
	
	my $fcnt                = 1 ;

	$sort_field{$fcnt}      = 'name'  ; $fcnt++ ;
	$sort_field{$fcnt}      = 'email' ; $fcnt++ ; 
	$sort_field{$fcnt}      = 'phone' ; $fcnt++ ;
	
	if ($user_type eq 'casual') {
		$sort_field{$fcnt}    = 'bank'  ; $fcnt++ ; 
		$sort_field{$fcnt}    = 'bank_acc_no' ; $fcnt++ ; 
	}	
	
	$sort_field{$fcnt}      = 'based_in' ; $fcnt++ ;
	$sort_field{$fcnt}      = 'user_type' ; $fcnt++ ;
	# $sort_field{$fcnt}    = 'organisation_ids' ; $fcnt++ ;
	
	if ($user_type eq 'schools_manager' || $user_type eq 'installation_partner' || $user_type eq 'casual') {
		$sort_field{$fcnt}  = 'region_ids' ;
		$fcnt++ ;
	}
	
	if ($user_type eq 'installation_partner') {
		$sort_field{$fcnt}  = 'customer_ids' ;
		$fcnt++ ;
	}
	
	$sort_field{$fcnt}      = 'block' ; $fcnt++ ;
	$sort_field{$fcnt}      = 'inactive' ; $fcnt++ ;
	
	# if ($dialog) {
		# $sort_field{$fcnt}  = 'sel_field' ; $fcnt++ ;
	# }
	
	$sort_field{$fcnt}      = 'username' ; $fcnt++ ;
	$sort_field{$fcnt}      = 'password' if $iaction eq 'add' ;

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

sub users_add_db_fields {

	$ignore{lastvisitdate} = 1 ;
	$ignore{iaction}    = 1 ;
	$ignore{block}      = 1 ;
	$ignore{inactive}   = 1 ;
	# $ignore{id}         = 1 ; 
	$hidden{lastupdate} = 2 ;
	$required{email}    = 1 ;
	$required{username} = 1 ;
	$required{name}     = 1 ;
	$required{password} = 1 ;

	&sort_fields ;

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

sub users_edit_db_fields {

	$ignore{lastvisitdate} = 1 ;
	$ignore{password}      = 1 ;
	$ignore{iaction}       = 1 ;
	$hidden{id}            = 1 ; # 1 = bypass for db update
	$hidden{username}      = 1 ; # 1 = bypass for db update
	$hidden{lastupdate}    = 2 ; # 2 = update db
	# $readonly{username}  = 'READONLY' ;
	$checkbox{block}       = 1 ;
	$checkbox{inactive}    = 1 ;
	# $required{username}  = 1 ;
	$required{email}       = 1 ;

	&sort_fields ;

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

sub users_add_screen {

	# called from common_add_screen
	
	$selected{user_type}{$user_type} = "SELECTED" if $user_type ;

	&users_select_opts ;
	
	our $savjqy = 1 if $user_type ; # incorporate jquery into the save event to accommodate the multiple chosen options

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

sub users_edit_screen {

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

	$selected{based_in}{$db{$table}{$i{id}}{based_in}}   = "SELECTED" ;
	$selected{user_type}{$db{$table}{$i{id}}{user_type}} = "SELECTED" ;

	$extra_form_fields .= &common_min_form_input('new_password','','password') ; 

	&users_select_opts ;
	
	our $savjqy = 1 if $user_type ; # incorporate jquery into the save event to accommodate the multiple chosen options

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

sub users_thead {

	$print_thead  = qq~<THEAD><TR><TH>ID</TH><TH>USERNAME</TH><TH>NAME</TH><TH>EMAIL</TH><TH>ACTIVE</TH><TH>BASE</TH>~;
	
	$print_thead .= qq~<TH>LEVEL</TH>~ if $user_type eq 'casual' ;
	
	$print_thead .= qq~<TH>LASTUPDATE</TH><TH>LASTVISITDATE</TH><TH>&nbsp;</TH></TR></THEAD>~ ;
    
} #-------------------------------------------------------------------------------

sub users_process_multi_select {

	# local @organisationids   = split(/\,/,$i{organisationids}) ;
	# my $organisationids      = join(",",@organisationids) ;
	# $organisationids         =~ s/\s//g; # remove white space
	# $ignore{organisationids} = 1 ;
	# $i{organisation_ids}     = $organisationids ;
	
	$i{organisation_ids}       = '0' ;
	
	local @regionids   = split(/\,/,$i{regionids}) ;
	my $regionids      = join(",",@regionids) ;
	$regionids         =~ s/\s//g; # remove white space
	$ignore{regionids} = 1 ;
	$i{region_ids}   = $regionids || '0' ;
	
	if ($user_type eq 'installation_partner' || $user_type eq 'coding_provider' || $user_type eq 'analytics_client') {
		local @customerids   = split(/\,/,$i{customerids}) ;
		my $customerids      = join(",",@customerids) ;
		$customerids         =~ s/\s//g; # remove white space
		$ignore{customerids} = 1 ;
		$i{customer_ids}     = $customerids ;
	} else {
		$i{customer_ids}     = '0' ;
	}
    
} #------------------------------------------------------------------------------------------

sub users_select_opts {
	
	# $multiple{organisation_ids} = 1; 
	# my @organisation_ids = split(/\,/,$db{$table}{$i{id}}{organisation_ids});
	# foreach (@organisation_ids) { $selected_multi{$_} = 'SELECTED' ; }
	# $preferred_title{organisation_ids} = "Venue" ; 
	# &common_min_select_opts('organisation_ids','organisations','name',$db{$table}{$i{id}}{organisation_ids},'') ;
	# $extra_form_fields .= qq~<input type="hidden" name="organisationids" id="organisation-ids" value="">~;

	# $trigger_jquery_raw .= qq~
	# \$("#savebutt").click(function() {
		# let st_val = \$("#selectOrganisation_ids").chosen().val() ;
		# \$('#organisation-ids').val(st_val);
		# \$('#users-form').submit();   
	# });~;
		
	if ($user_type eq 'installation_partner' || $user_type eq 'coding_provider' || $user_type eq 'analytics_client') {
		$multiple{customer_ids} = 1; 
		my @customer_ids = split(/\,/,$db{$table}{$i{id}}{customer_ids});
		foreach (@customer_ids) { $selected_multi{$_} = 'SELECTED' ; }
		$preferred_title{customer_ids} = "Customers" ; 
		&common_min_select_opts('customer_ids','customers','name','','') ;
		$extra_form_fields .= qq~<input type="hidden" name="customerids" id="customer-ids" value="">~;
		$add_to_trigger_jquery_raw = qq~
			let cust_val = \$("#selectCustomer_ids").chosen().val() ;
			\$('#customer-ids').val(cust_val);
		~;
	}
		
	if ($user_type eq 'schools_manager' || $user_type eq 'installation_partner' || $user_type eq 'casual' || $user_type eq 'coding_provider' || $user_type eq 'analytics_client') {
		$multiple{region_ids} = 1; 
		my @region_ids = split(/\,/,$db{$table}{$i{id}}{region_ids});
		foreach (@region_ids) { $selected_multi{$_} = 'SELECTED' ; }
		$preferred_title{region_ids} = "Regions" ; 
		&common_min_select_opts('region_ids','regions','name','','') ;
		$extra_form_fields .= qq~<input type="hidden" name="regionids" id="region-ids" value="">~;

		$trigger_jquery_raw .= qq~
		\$("#savebutt").click(function() {
			let st_val = \$("#selectRegion_ids").chosen().val() ;
			\$('#region-ids').val(st_val);
			$add_to_trigger_jquery_raw
			\$('#users-form').submit();   
		});~;
	}
		
	# &common_min_select_opts('organisation_ids','organisations','name',$db{$table}{$i{id}}{organisation_ids},1,'','');
	
	&common_min_select_opts('based_in','regions','name',$db{$table}{$i{id}}{based_in},1,'','','code') ;

	# $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>~ ;
	# $opts{based_in} = qq~<option value="GP" $selected{based_in}{'GP'}>Gauteng</option><option value="CT" $selected{based_in}{'CT'}>Cape Town</option>~ ;
						 
	$required{user_type} = 1 ;
	$select{user_type} = 1 ;
	if ($user_type eq 'casual') {
		if ($glod_user_level > 2) {
			$opts{user_type}  = qq~<option value="casual_a" $selected{user_type}{casual_a}>Operator Level 1</option>~;
		} 
		if ($glod_user_level > 3) {
			$opts{user_type} .= qq~<option value="casual_b" $selected{user_type}{casual_b}>Operator Level 2</option><option value="casual_c" $selected{user_type}{casual_c}>Operator Level 3</option>~;
		}
		$opts{user_type} .= qq~<option value="casual_calibrator" $selected{user_type}{casual_calibrator}>Temp Calibrator</option>~;
	} elsif ($user_type) {
		my $user_type_name = join(" ", map { ucfirst lc } split /_/, $user_type);
		$opts{user_type} = qq~
			<option value="$user_type" $selected{user_type}{$user_type}>$user_type_name</option>
		~ ;
	} else {
		$opts{user_type} = qq~
			<option value="manager" $selected{user_type}{'manager'}>Manager</option>
			<option value="support" $selected{user_type}{'support'}>Support</option>
			<option value="external" $selected{user_type}{external}>External</option>
			<option value="it" $selected{user_type}{it}>IT</option>
			<option value="nonquote" $selected{user_type}{nonquote}>Non-quotes</option>
			<option value="parttime" $selected{user_type}{'parttime'}>Part-time</option>
			<option value="permanent" $selected{user_type}{'permanent'}>Permanent</option>
			<option value="senior_manager" $selected{user_type}{'senior_manager'}>Senior Manager</option>
			<option value="dcb_partner" $selected{user_type}{'dcb_partner'}>DCB Partner</option>
		~ ;
	}

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

sub users_insert {

	&add_db_fields ;

	my $crypted_password = apache_md5_crypt($i{password},$useropts{salt}) ;
	$i{password} = $crypted_password ;
	$i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
	$i{email}    = lc $i{email} ;
	
	$i{id} = &db_min_get_max($table,'id') ;
	
	&process_multi_select if $user_type ;

	&db_min_insert($table) ;

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

sub users_update {

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

	&edit_db_fields ;

	unless ($i{block})    { $i{block}    = '0' ; }
	unless ($i{inactive}) { $i{inactive} = '0' ; }

	if ($i{new_password}) { 
		my $crypted_password = apache_md5_crypt($i{new_password},$useropts{salt}) ;
		$i{password} = $crypted_password ;
		$ignore{password} = 0 ;
		$hidden{password} = 2 ;    
	}
		
	$i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
	
	&process_multi_select if $user_type ;

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

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

sub users_validate {

	my $user_exists   = '' ; my $email_exists   = '' ;

	$i{username} = lc $i{username} ;
	$i{username} =~ s/ //gi ;

	$i{email}    = lc $i{email} ;
	$i{email}    =~ s/ //gi ;

	&db_min_ro($table,'*',"username='$i{username}' OR email='$i{email}'",'username','') ;

	foreach my $id (keys %{$db{$table}}) { 
		if ($db{$table}{$id}{username} eq $i{username}) { 
			$user_exists = 1 ;
			last;			
		} 
		
		if ($i{email} && $db{$table}{$id}{email} eq $i{email}) { 
			$email_exists = 1 ; 
			last;
		} 
	}

	if ($user_exists) {
		$alert = &common_min_alert('warning',"USERNAME ALREADY EXISTS!",'ok') ;
		%col_name = ();
		&common_min_add_screen;
		&common_min_screen1 unless $dialog ;
		&screen1 if $dialog ;
	} 
	
	if ($email_exists) {
		$alert = &common_min_alert('warning',"EMAIL ALREADY EXISTS!",'ok') ;
		%col_name = ();
		&common_min_add_screen;
		&common_min_screen1 unless $dialog ;
		&screen1 if $dialog ;
	}

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

1 ;