#!/usr/bin/perl

BEGIN { use lib '/usr/home/cfg' ; require push_inc ; }
    
use CGI qw( :standard );
use CGI::Carp qw(fatalsToBrowser);
use Date::Calc qw(:all);
    
require cfg ;

print header;   # CGI.pm method

# unless ($useropts{admin}{$userid} eq $username) { require '401.pm' ; exit ; }

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

&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 ;

&common_min_debug ("action [$action]") ;

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

&page_opts ;

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

&db_open_upd ;
    our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
	
	if ($action eq 'assign'){
		&common_min_load_params ;
		&update ;
		%i = () ; # clear so the list loads
		# exit;
		&common_min_screen2;
	}
	
	&common_min_action;

	$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
&db_close_conn ;

exit;

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

sub validate {

	# my $exists   = '' ;

	# $i{ref} = uc $i{ref} ;

	# &db_min_ro($table,'*',"`ref`='$i{ref}'",'ref','') ;

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

	# if ($exists) { $alert = &common_min_alert('warning',"$ucpage ALREADY EXISTS!",'ok') ; %col_name = (); &common_add_screen; &common_screen1; }

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

# sub insert {

	# &add_db_fields ;

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

	# &db_min_insert($table) ;

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

sub update {
	
	&common_min_debug ("update [$i{completed}] id=$i{id}") ;

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

	&edit_db_fields ;

	# unless ($i{camera_id}) { $i{camera_id}   = '0' ; }
	unless ($i{completed}) { $i{completed}   = '0' ; }
	if     ($i{staff_id})  { $i{assign_date} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; } else { $ignore{assign_date} = 1 ; }
	unless ($i{completed}) { $ignore{action_time} = 1 ; }
	
	&process_camera_ids;
	
	# if ($i{completed} == 1) {
	if ($iaction eq 'completed') {
		&update_open_closed ;
	} else {
		&db_min_upd($table,"id='$i{id}'") ;
	}

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

sub process_camera_ids {

local @cameraids = split(/\,/,$i{cameraids}) ;

my $cameraids = join(",",@cameraids) ;

$cameraids =~ s/\s//g; # remove white space

$ignore{cameraids} = 1 ;
$i{camera_ids} = $cameraids ;
    
} #------------------------------------------------------------------------------------------

sub update_open_closed {
	
	my $upd_id         = $i{id} ;
	my $upd_uid        = $i{unique_id} ;
	my $upd_suid       = $i{suid} ;
	my $from           = $i{sent_from} ;
	my $completed      = $i{completed} ;
	
	%i                 = () ;	
	$i{id}             = $upd_id ;
		
	if ($completed == 1) {
		$i{completed}      = 1 ;
		$i{action_time}    = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
	} else {
		$success           = qq~<b><i>`$upd_uid`</i></b> OPENED~ ;
		$i{completed}      = '0' ;
	}	
	
	&db_min_upd($table,"id='$i{id}' OR suid='$upd_uid' OR unique_id='$upd_uid' OR suid='$upd_suid' OR unique_id='$upd_suid'") ;
	
	if ($completed == 1) {
		&auto_send_close_email if $from ;
		$success           = qq~<b><i>`$upd_uid`</i></b> CLOSED~ ;
		$success          .= qq~ and email sent to $from~ if $from ;
	} else {
		$success           = qq~<b><i>`$upd_uid`</i></b> OPENED~ ;
	}
	
	# exit;
	
} #------------------------------------------------------------------------------------------

sub auto_send_close_email {
	
my $remsg = qq~Hello,

Your ticket $i{unique_id} has now been closed.

Do not hesitate to contact us should you need additional assistance.

Best regards,

The ITV Africa Team~ ;
		
&common_send_mail("$i{sent_from}",'','','','',"$remsg","$i{subject}") ;

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

sub list_screen {
	
	local $surl = qq~javascript:dlgMdl('$useropts{scripts}/dialog/read_ticket.pl~;

	&load_db_vars ;

	# our @sql_col_display = ("ref","unique_id","sent_date","subject","sent_from","priority_id","staff_id","client_id","camera_id","camera_system_id","serial_nr","part_nr","") ;
	our @sql_col_display = ("ref","unique_id","sent_date","subject","sent_from","priority_id","staff_id","client_id","camera_nr","quote_nr","") ;
	
	my $sql_where  = $iaction eq 'closed' ? "completed = '1'" : "completed = '0'" ;
	
	   $sql_where .= (!$useropts{super}{$username} && !$useropts{boss}{$username} && !$useropts{it}{$username} && !$useropts{tickets}{$username}) ? " AND staff_id = '$userid'" : '' ;

	&db_min_ro($table,'*',$sql_where,'','') ;
	
	foreach my $id (sort {$a <=> $b} keys %{$db{$table}}) {
		
		my $uid                = $db{$table}{$id}{unique_id} ;
		my $responded          = $db{$table}{$id}{responded} ;
		
		my $date_time          = $db{$table}{$id}{date_time} ;
		my $subject            = $db{$table}{$id}{subject} ;
		my $camera_ids         = $db{$table}{$id}{camera_ids} ;
		my $priority_id        = $db{$table}{$id}{priority_id} ;
		my $staff_id           = $db{$table}{$id}{staff_id} ;
		my $client_id          = $db{$table}{$id}{client_id} ;
		my $sent_from          = $db{$table}{$id}{sent_from} ;
							   
		my @hash_split         = split /\#\#/, $subject ;
		my @subj_uid           = split / /, $hash_split[1] ;
		# my $suid             = ($subj_uid[0]) ? $subj_uid[0] : $uid ;
		my $suid               = $subj_uid[0] ;
							   
		$open_ticket{$suid}    = $has_responce{$suid} ;
		$open_cameras{$suid}   = $has_camera_ids{$suid} ;
		$open_client{$suid}    = $has_client_id{$suid} ;
		$open_staff{$suid}     = $has_staff_id{$suid} ;
		$open_priority{$suid}  = $has_priority_id{$suid} ;
		$open_sent_from{$suid} = $has_sent_from{$suid} ;
		
		$has_sent_from{$uid}   = &get_from($sent_from) ;  
		$has_responce{$uid}    = $responded ;
		$has_camera_ids{$uid}  = $camera_ids ;
		$has_client_id{$uid}   = $client_id ;
		$has_staff_id{$uid}    = $staff_id ;
		$has_priority_id{$uid} = $priority_id ;
		
		&common_min_debug ("[open=$open_ticket{$suid}] [$uid] [$suid] [$subject]") ;
		
		if ($responded && $client_id && !$suid) { $suid = $uid ; }
	
		$cnt{$suid}++ ;
		
		next unless $responded ;
		
		$link_previous{$suid} .= qq~ <a href="$surl?uniqueid=$uid&from=$sent_from{$uid}&suid=$suid&responded=$responded&subject=$hash_split[0]','$val [$uid] $clientname{$client_id}','','medium-dialog');" data-toggle="tooltip" data-placement="top" data-title="Read ticket : $subject [$date_time]">[<i class="glyphicon glyphicon-envelope"></i>$cnt{$suid}]</a>~ ;
				
	}
	
	# &common_min_debug ("action [$action]") ;

	foreach my $id (sort {$b <=> $a} keys %{$db{$table}}) {
		
		my $uid         = $db{$table}{$id}{unique_id} ;
		my $completed   = $db{$table}{$id}{completed} ;
		my $responded   = $db{$table}{$id}{responded} ;
		my $sent_from   = $db{$table}{$id}{sent_from} ;
		my $date_time   = $db{$table}{$id}{date_time} ;
		my $client_id   = $db{$table}{$id}{client_id} ;
		my $staff_id    = $db{$table}{$id}{staff_id} ;
		my $priority_id = $db{$table}{$id}{priority_id} ;
		my $s_uid       = $db{$table}{$id}{suid} ;
		
		next if $responded && ($iaction eq 'list' || $iaction eq 'active')  ;
		# next if $s_uid && $iaction eq 'open'  ;
		next if $got_open_ticket{$s_uid} && $iaction eq 'open'     && $s_uid ne '0'  ; $got_open_ticket{$s_uid}   = 1 ; $got_open_ticket{$uid}   = 1 ;
		next if $got_closed_ticket{$s_uid} && $iaction eq 'closed' && $s_uid ne '0'  ; $got_closed_ticket{$s_uid} = 1 ; $got_closed_ticket{$uid} = 1 ;
		
		# &common_min_debug ("got_open_ticket [$s_uid] $uid [$iaction]") ;
		
		my $subject   = $db{$table}{$id}{subject} ;
		
		# my @hash_split = split /\#/, $subject ;
		# my $sub_uid = ($hash_split[1]) ? $hash_split[1] : $uid ;
		
		my @hash_split       = split /\#\#/, $subject ;
		my @subj_uid         = split / /, $hash_split[1] ;
		my $suid             = ($subj_uid[0]) ? $subj_uid[0] : $uid ; $got_open_ticket{$suid} = 1 ; $got_closed_ticket{$suid} = 1 ;
		
		$sent_from{$uid} = &get_from($sent_from) ;
		
		# my @from_array = split /\</, $db{$table}{$id}{sent_from} ; my $from_email = pop @from_array; $from_email =~ s/\>//g; $sent_from{$uid} = $from_email ;
		
		# &common_min_debug ("$id. sub_uid=$sub_uid [$uid]") ;
		
		# if ($responded) { 
			# $link_previous{$sub_uid} .= qq~ $surl?uniqueid=$uid&subject=$subject&from=$sent_from{$uid}','$val [$uid] $clientname{$client_id}','','max-dialog');" data-toggle="tooltip" data-placement="top" data-title="Read ticket">[$sub_uid]</a>~ ;
			# next ;
		# }
		
		$print_tbody .= qq~<tr id="$uid">~ ;
	
			foreach (@sql_col_display) { 
				unless ($_) { next ; } # blank for the buttons column
				my $val = $db{$table}{$id}{$_} ;
				# if ($_ eq 'rate_id')  { $val = $rate{$db{$table}{$id}{$_}}  ; }  

				$align = qq~class="dt-center"~ ;				
				
				if ($_ eq 'staff_id')           { $val = ($val > 0) ? "<span class='label label-default'>$staffname{$val}</span>" : ($open_staff{$suid}) ? "<span class='label label-default'>$staffname{$open_staff{$suid}}</span>" : ($completed) ? '' : &load_links('staff',$id,$suid) ; }
				if ($_ eq 'client_id')          { $val = ($val > 0) ? "<span class='label label-default'>$clientname{$val}</span>" : ($open_client{$suid}) ? "<span class='label label-default'>$clientname{$open_client{$suid}}</span>" : ($completed) ? '' : &load_links('customers',$id,$suid) ; }
				if ($_ eq 'priority_id')        { $val = ($val > 0) ? "<span class='label label-default' style='background-color:$prioritycolour{$val};'>$priorityname{$val}</span>" : ($open_priority{$suid}) ? "<span class='label label-default' style='background-color:$prioritycolour{$open_priority{$suid}};'>$priorityname{$open_priority{$suid}}</span>" : ($completed) ? '' : &load_links('priority',$id,$suid) ; }
				
				if ($_ eq 'camera_nr' || $_ eq 'quote_nr') { 
					my @camera_ids = ($db{$table}{$id}{camera_ids}) ? split(/\,/,$db{$table}{$id}{camera_ids}) : ($open_cameras{$suid}) ? split(/\,/,$open_cameras{$suid}) : () ;
					$val = '' ;

					foreach my $cam_id (@camera_ids) { 
						&common_debug("$_ : cam_id [$cam_id] : $camera_quote_nr{$cam_id}") ;
						if ($_ eq 'quote_nr')          {
							$val = &common_camera_links($tables,$cam_id,$camera_quote_nr{$cam_id}) if $pixellot_limit{$username}!=1 and $events_limit{$username}!=1 ;
							next if $done_quote{$camera_quote_nr{$cam_id}} ; $done_quote{$camera_quote_nr{$cam_id}} ;							
						} elsif ($_ eq 'camera_nr') {
							# my $tt_txt   = qq~Camera System:$camera_system_id{$cam_id}<br>Serial Nr:$camera_serial_nr{$cam_id}<br>~ ;
							my $tt_txt   = qq~Camera System:$camera_system_id{$cam_id}<br>Camera Nr:$camera_nr{$cam_id}<br>~ ;
							   $tt_txt  .= ($camera_part_nr{$cam_id}) ? qq~Part Nr:$camera_part_nr{$cam_id}<br>~ : qq~Part Nr: n/a<br>~ ;
							   $tt_txt  .= ($camera_sport_type{$cam_id}) ? qq~Sport Type:$camera_sport_type{$cam_id}<br>~ : qq~Sport Type: n/a<br>~ ;
							our $tooltip = qq~data-toggle="tooltip" data-placement="top" data-title="$tt_txt"~ ;
							$val        .= &common_camera_links($tables,$cam_id,$camera_serial_nr{$cam_id}) . '&nbsp;' if $pixellot_limit{$username}!=1 and $events_limit{$username}!=1 ;
							    $tooltip = '' ;
							# $val      .= ($cam_id > 0) ? "<span class='label label-primary' data-toggle='tooltip' data-placement='top' data-title='$tt_txt'>$camera_nr{$cam_id}</span>&nbsp;" : '' ; 
						} # elsif ($_ eq 'sport_type_id') { 
							# $val        .= $camera_sport_type{$cam_id} ;
						# }
					}	
					# $val = ($val > 0) ? "<span class='label label-primary'>$camera_nr{$val}</span>" : ($open_cameras{$suid}) ? "<span class='label label-primary'>$camera_nr{$open_cameras{$suid}}</span>" : '' ; 
				}
				
				# if ($_ eq 'camera_system_id')   { $val = ($val > 0) ? "<span class='label label-primary'>$camera_system_id{$val}</span>" : ($open_cameras{$suid}) ? "<span class='label label-primary'>$camera_system_id{$open_cameras{$suid}}</span>" : '' ; }
				# if ($_ eq 'serial_nr')          { $val = ($val > 0) ? "<span class='label label-primary'>$camera_serial_nr{$val}</span>" : ($open_cameras{$suid}) ? "<span class='label label-primary'>$camera_serial_nr{$open_cameras{$suid}}</span>" : '' ; }
				# if ($_ eq 'part_nr')            { $val = ($val > 0) ? "<span class='label label-primary'>$camera_part_nr{$val}</span>" : ($open_cameras{$suid}) ? "<span class='label label-primary'>$camera_part_nr{$open_cameras{$suid}}</span>" : '' ; }
				if ($_ eq 'sent_from')          { $val = ($open_sent_from{$suid}) ? $open_sent_from{$suid} : $sent_from{$uid} ; } # strip off the > character
				# if ($_ eq 'subject')          { $val = qq~<a href="javascript:dlgMdl('$useropts{scripts}/dialog/read_ticket.pl?uniqueid=$uid&subject=$subject&from=$sent_from{$uid}','$val [$uid] $clientname{$client_id}','','max-dialog');" data-toggle="tooltip" data-placement="top" data-title="Read ticket">$val</a>~; $align = '' ; }
				# if ($_ eq 'subject')          { $val = '<a href="' . $surl . qq~?uniqueid=$uid&from=$sent_from{$uid}&suid=$suid&responded=&subject=$subject','$val [$uid] $clientname{$client_id}','','medium-dialog');" data-toggle="tooltip" data-placement="top" data-title="Read ticket [$date_time]">$val $link_previous{$suid}</a>~; $align = '' ; }
				if ($_ eq 'subject')            { $val = (!$completed && ($client_id || $open_client{$suid}) && ($staff_id || $open_staff{$suid}) && ($priority_id || $open_priority{$suid})) ? '<a href="' . $surl . qq~?uniqueid=$uid&from=$sent_from{$uid}&suid=$suid&responded=&subject=$subject','$val [$uid] $clientname{$client_id}','','medium-dialog');" data-toggle="tooltip" data-placement="top" data-title="Read ticket [$date_time]">$val&nbsp;<i class="glyphicon glyphicon-envelope"></i></a>~ : '<a href="' . $surl . qq~?uniqueid=$uid&from=$sent_from{$uid}&suid=$suid&responded=1&subject=$subject','$val [$uid] $clientname{$client_id}','','medium-dialog');" data-toggle="tooltip" data-placement="top" data-title="Read ticket [$date_time]">$val&nbsp;<i class="glyphicon glyphicon-envelope"></i></a>~ ; $align = '' ; }
				if ($_ eq 'ref')                { $val = $id ; }
				
				
				
								
				$print_tbody .= qq~<td $align>$val</td>~ ;  
			}
				
			$print_tbody .= qq~<td nowrap>&nbsp;~;
			
			my $tooltip_start = qq~data-toggle="tooltip" data-placement="top"~ ;
			
			if (!$completed && ($client_id || $open_client{$suid}) && ($staff_id || $open_staff{$suid}) && ($priority_id || $open_priority{$suid})) {
				$print_tbody .= qq~<a class="btn btn-primary btn-xs" href="$surl?uniqueid=$uid&from=$sent_from{$uid}&suid=$suid&responded=&subject=$subject','$subject [$uid] $clientname{$client_id}','','medium-dialog');" $tooltip_start data-title="Reply"><i class="glyphicon glyphicon-circle-arrow-left icon-white"></i></a>&nbsp;~;
			}
				
			unless ($completed || $link_previous{$suid}) {
				$print_tbody .= qq~
					<a class="btn btn-info btn-xs" href="javascript:editMinItem('$id');" $tooltip_start data-title="Edit"><i class="glyphicon glyphicon-edit icon-white"></i></a>&nbsp;
				~;
			}
			
			$print_tbody .= &load_links('completed',$id,$suid) ;
			
			if (!$completed && !$link_previous{$suid} && ($useropts{it}{$username} || $useropts{boss}{$username})) {
				$print_tbody .= qq~
					<a class="btn btn-danger btn-xs" href="javascript:deleteMinItem('$subject','$id')" $tooltip_start data-title="Delete"><i class="glyphicon glyphicon-trash icon-white"></i></a>&nbsp;
				~;
			}
			
			# $print_tbody .= qq~<a class="btn btn-primary btn-xs" href="javascript:ticketReply('$db{$table}{$id}{subject}','$id')" $tooltip_start data-title="Reply"><i class="glyphicon glyphicon-circle-arrow-left icon-white"></i></a>&nbsp;~;

			# <a class="btn btn-success btn-xs" href="javascript:ticketCompleted('$db{$table}{$id}{subject}','$id')" $tooltip_start data-title="Mark Completed"><i class="glyphicon glyphicon-thumbs-up icon-white"></i></a>&nbsp;
				
			$print_tbody .= qq~</td>~ ;		
			
		$print_tbody .= qq~</tr>~ ;
	}
	
	&build_jquery ;
	
	$box_icon .= qq~<div><a href="/open-tickets"><span class="notification green" style="font-size:11px;">$opentickets</span></a></div>~ if $opentickets > 0 ;
	
	# &common_min_extra_crumb("closed-$table","Closed $page_title") unless $iaction eq 'closed' ;
	# &common_min_extra_crumb("open-$table","Open $page_title")     unless $iaction eq 'open' ;
	&common_min_extra_crumb("active-$table","Active $page_title") unless $iaction eq 'list' || $iaction eq 'active' ;

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

sub get_from {
	
	my ($sfrom) = @_ ;
	
	@from_array = split /\</, $sfrom ; my $from_email = pop @from_array; $from_email =~ s/\>//g; 
	
	return ($from_email) ;
	
} #------------------------------------------------------------------------------------------

sub load_db_vars {
	
	# local $last_year =  $now_year - 1 ;
	
	my ($sql_back_ccyy_mm_dd) = &common_add_delta_days(-90) ;

	# &db_min_ro('quotes','DISTINCT quote_to',"quote_date >= '$last_year-06-01'",'','') ; 
	&db_min_ro('quotes','DISTINCT quote_to',"quote_date >= '$sql_back_ccyy_mm_dd' AND quote_to <> 1",'','') ; 
	# &db_min_ro('quotes','DISTINCT quote_to','','quote_date DESC',10) ; 
	
	foreach my $clid (keys %{$db{quotes}}) { 
		$display_client{$clid} = 1 ;
	}
	
	&db_min_ro('quotes','DISTINCT user_id',"quote_date >= '$sql_back_ccyy_mm_dd'",'','') ; 
	# &db_min_ro('quotes','DISTINCT user_id','','quote_date DESC',10) ; 
	
	foreach my $uid (keys %{$db{quotes}}) { 
		$display_user{$uid} = 1 ;
	}
	
	# &db_min_ro('quotes','DISTINCT user_id',"quote_date >= '$sql_back_ccyy_mm_dd'",'','') ; 
	
	# foreach my $uid (keys %{$db{quotes}}) { 
		# $display_user{$uid} = 1 ;
	# }
	
	&db_min_ro('users','id,username','','','') ;
	foreach my $id (keys %{$db{users}}) { 
		$staffname{$id}   = $db{users}{$id}{username} ; 
	}
	
	&db_min_ro('customers','id,name',"active = '1'",'','') ; 
	foreach my $id (keys %{$db{customers}}) { 
		# &common_min_debug ("load_db_vars customers [clientid=$id] display_client=$db{customers}{$id}{name}") ;
		$clientname{$id}   = $db{customers}{$id}{name} ;
	}
	
	&db_min_ro('priority','id,name,colour','','','') ; 
	foreach my $id (keys %{$db{priority}}) { 
		$priorityname{$id}   = $db{priority}{$id}{name} ;
		$prioritycolour{$id} = $db{priority}{$id}{colour} ;
	}
	
	&db_min_ro('sport_types','*','','','') ; 
	foreach my $id (keys %{$db{sport_types}}) { 
		$sport_type_name{$id} = $db{sport_types}{$id}{name} ;
	}
	
	my $t1 = 'cameras' ;
	my $t2 = 'camera_systems' ;
	our $tables = "$t1,$t2" ;
	
	&db_min_ro($tables,"$t1.id,$t1.camera_nr,$t1.serial_nr,$t1.part_number,$t1.camera_system_id,$t1.quote_nr,$t1.sport_type_ids,$t2.name AS 'camera_system_name',$t2.description AS 'camera_system_desc'","$t1.camera_system_id = $t2.id",'','') ;
	
	foreach my $id (keys %{$db{$tables}}) { 
		# $camera_nr{$id}           = "$db{cameras}{$id}{camera_nr} [$db{cameras}{$id}{serial_nr}]" ;
		$camera_nr{$id}             = $db{$tables}{$id}{camera_nr} ;
		$camera_serial_nr{$id}      = $db{$tables}{$id}{serial_nr} ;
		$camera_part_nr{$id}        = $db{$tables}{$id}{part_number} ;
		$camera_system_id{$id}      = $db{$tables}{$id}{camera_system_desc} ;
		$camera_quote_nr{$id}       = $db{$tables}{$id}{quote_nr} ;
		# $camera_sport_type{$id}   = $sport_type_name{$db{$tables}{$id}{sport_type_id}} ;
		
		my @sport_type_ids = split(/\,/,$db{$tables}{$id}{sport_type_ids});

		foreach (@sport_type_ids) { 
			$camera_sport_type{$id} .= ($camera_sport_type{$id}) ? ", $sport_type_name{$_}" : $sport_type_name{$_} ;
		}		
	}
	
	my $xtra_sql_where = (!$useropts{super}{$username} && !$useropts{boss}{$username} && !$useropts{it}{$username} && !$useropts{tickets}{$username}) ? " AND staff_id = '$userid'" : '' ;
	# my $xtra_sql_where = " AND staff_id = '$userid'" ;
	
	# &db_min_ro('tickets','DISTINCT suid',"completed = '0'",'','') ; 
	&db_min_ro($table,'*',"completed = '0'",'','') ; 
	
	our $opentickets = 0 ;
	
	foreach (keys %{$db{$table}}) { 
		my @hash_split       = split /\#\#/, $db{$table}{$_}{subject} ;
		my @subj_uid         = split / /, $hash_split[1] ;
		my $suid             = ($subj_uid[0]) ? $subj_uid[0] : ($db{$table}{$_}{suid}) ? $db{$table}{$_}{suid} : $db{$table}{$_}{unique_id} ;
		
		next if $check_open_ticket{$suid} ;
		$opentickets++ ;
		$check_open_ticket{$suid} = 1 ;
	}
	
	&common_load_quote_vars("cameras.quote_nr>0 AND cameras.quote_nr=quotes.quote_nr");
	
} #------------------------------------------------------------------------------------------

sub load_links {
	
	local ($type,$id,$suid) = @_ ;
	
	local $links = '' ;
	
	# return('') unless $useropts{admin}{$userid} ;	
	
	# &common_min_debug ("load_links [$type,$id]") ;
	
	local $cnt = 0 ;

	if ($type eq 'staff') {
		foreach my $staffid (keys %{$db{users}}) { 
			next if $useropts{it}{$staffname{$staffid}} ;
			next unless $display_user{$staffid} ;
			my $department_id = $db{users}{$staffid}{department_id} ; 
			my $initial       = uc substr($staffname{$staffid},0,1) ;
			next if $department_id==2 || $department_id==2 ; # accounts
			$cnt++ ;
			$links .= qq~<a href="javascript:saveStaff('$db{$table}{$id}{unique_id}','$staffid','$id')" data-toggle="tooltip" data-placement="left" data-title="Save to $staffname{$staffid}!">[$initial]</a>&nbsp;~ ;
			last if $cnt>=5 ;
		}
	}
	
	if ($type eq 'customers') {
		foreach my $clientid (keys %{$db{customers}}) { 
			# &common_min_debug ("load_links customers [clientid=$clientid] display_client=$display_client{$clientid}") ;
			next unless $display_client{$clientid} ;
			# my $ref_init     = uc substr($db{customers}{$clientid}{ref},0,3) ;
			my $ref_init       = uc substr($clientname{$clientid},0,3) ;
			
			# &common_min_debug ("load_links customers [clientid=$clientid] display_client=$display_client{$clientid}") ;
			
			$cnt++ ;
			$links .= qq~<a href="javascript:saveClient('$db{$table}{$id}{unique_id}','$clientid','$id')" data-toggle="tooltip" data-placement="left" data-title="Save to $clientname{$clientid}!">[$ref_init]</a>&nbsp;~ ;
			last if $cnt>=5 ;
		}
	}
	
	if ($type eq 'priority') {
		foreach my $priorityid (sort keys %{$db{priority}}) { 
			my $priority_init = uc substr($db{priority}{$priorityid}{name},0,1) ;
			$links .= qq~<a href="javascript:savePriority('$db{$table}{$id}{unique_id}','$priorityid','$id')" style='color:$db{priority}{$priorityid}{colour};' data-toggle="tooltip" data-placement="left" data-title="Save to $db{priority}{$priorityid}{name}!">[$priority_init]</a>&nbsp;~ ;
		}
	}
		
	if ($type eq 'completed') {
		my $completed = $db{$table}{$id}{completed} ;
		my $openclose = ($completed) ? 0 : 1 ;
		# my $color   = ($completed) ? 'green' : 'red' ;
		# my $color     = ($completed) ? 'success' : 'danger' ;
		my $color     = ($completed) ? 'success' : 'warning' ;
		my $text      = ($completed) ? 'Open'  : 'Close' ;
		# my $glyph     = ($completed) ? 'ok-circle'  : 'remove-circle' ;
		# my $glyph     = ($completed) ? 'eye-open'  : 'eye-close' ;
		# my $glyph     = ($completed) ? 'tags'  : 'tags' ;
		# $links .= qq~<a href="javascript:setOpenClose('$db{$table}{$id}{unique_id}','$openclose','$id')" style='color:$color;' data-toggle="tooltip" data-placement="left" data-title="$text">[$text]</a>&nbsp;~ ;
		$links .= qq~<a href="javascript:setOpenClose('$db{$table}{$id}{unique_id}','$openclose','$id','$sent_from{$db{$table}{$id}{unique_id}}','$suid')" data-toggle="tooltip" data-placement="top" data-title="$text ticket" class="btn btn-$color btn-xs"><i class="glyphicon glyphicon-tags" style="margin-top:2px;"></i></a>&nbsp;~ ;
	}
		
	return ($links) ;
	
} #------------------------------------------------------------------------------------------

sub build_jquery {
	
	$trigger_jquery_raw .= qq~
	function saveStaff(uniqueid,staffid,id)
	{
		document.staffform.unique_id.value = uniqueid ;
		document.staffform.staff_id.value  = staffid ;
		document.staffform.id.value        = id ;
		\$('#staff-form').submit();
	}
	function saveClient(uniqueid,clientid,id)
	{
		document.clientform.unique_id.value = uniqueid ;
		document.clientform.client_id.value = clientid ;
		document.clientform.id.value        = id ;
		\$('#client-form').submit();
	}
	function savePriority(uniqueid,priorityid,id)
	{
		document.priorityform.unique_id.value   = uniqueid ;
		document.priorityform.priority_id.value = priorityid ;
		document.priorityform.id.value          = id ;
		\$('#priority-form').submit();
	}
	function setOpenClose(uniqueid,openclose,id,sent_from,suid)
	{
		document.completedform.unique_id.value   = uniqueid ;
		document.completedform.completed.value   = openclose ;
		document.completedform.sent_from.value   = sent_from ;
		document.completedform.suid.value        = suid ;
		document.completedform.id.value          = id ;
		\$('#completed-form').submit();
	}
	~;
	
	$print_footer_forms .= qq~
<form name="staffform" id="staff-form" action="assign-tickets" method="post">
<input type="hidden" name="iaction"      value="staff">
<input type="hidden" name="id"           value="">
<input type="hidden" name="unique_id"    value="">
<input type="hidden" name="staff_id"     value="">
</form>
<form name="clientform" id="client-form" action="assign-tickets" method="post">
<input type="hidden" name="iaction"      value="client">
<input type="hidden" name="id"           value="">
<input type="hidden" name="unique_id"    value="">
<input type="hidden" name="client_id"    value="">
</form>
<form name="priorityform" id="priority-form" action="assign-tickets" method="post">
<input type="hidden" name="iaction"      value="priority">
<input type="hidden" name="id"           value="">
<input type="hidden" name="unique_id"    value="">
<input type="hidden" name="priority_id"  value="">
</form>
<form name="completedform" id="completed-form" action="assign-tickets" method="post">
<input type="hidden" name="iaction"      value="completed">
<input type="hidden" name="id"           value="">
<input type="hidden" name="suid"         value="">
<input type="hidden" name="unique_id"    value="">
<input type="hidden" name="completed"    value="">
<input type="hidden" name="sent_from"    value="">
</form>
	~ ;
	
} #------------------------------------------------------------------------------------------

sub thead {

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

# sub add_db_fields {

# &hidden_fields ;

# $ignore{id} = 1 ;

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

sub edit_db_fields {
	
&sort_fields;

&hidden_fields ;

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

sub hidden_fields {

$ignore{iaction}       = 1 ;
$ignore{date_time}     = 1 ;
$ignore{mailtype}      = 1 ;
$ignore{doctype}       = 1 ;
$ignore{cc}            = 1 ;
$ignore{bcc}           = 1 ;
$ignore{responded}     = 1 ;

$hidden{id}            = 1 ;
$hidden{unique_id}     = 1 ;
$hidden{suid}          = 2 ;
$hidden{assign_date}   = 2 ;
$hidden{completed}     = 2 ;
$hidden{action_time}   = 2 ;

$preferred_title{id}   = 'Ref' ;

$readonly{sent_from}   = 'READONLY' ;
$readonly{sent_to}     = 'READONLY' ;
$readonly{reply_to}    = 'READONLY' ;
$readonly{subject}     = 'READONLY' ;
$readonly{unique_id}   = 'READONLY' ;
$readonly{sent_date}   = 'READONLY' ;
$readonly{assign_date} = 'READONLY' ;
$readonly{id}          = 'READONLY' ;

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

sub sort_fields {
	
%sort_field = () ;

$sort_field{1}  = 'client_id' ; 
$sort_field{2}  = 'camera_ids' ; $preferred_title{camera_ids} = 'Cameras' ; 
$sort_field{3}  = 'priority_id' ; 
$sort_field{4}  = 'staff_id' ; 
$sort_field{5}  = 'sent_date' ; 
$sort_field{6}  = 'sent_from' ; 
$sort_field{7}  = 'reply_to' ; 
$sort_field{8}  = 'sent_to' ;
$sort_field{9}  = 'subject' ;

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

# sub add_screen {

# # called from common_add_screen

# &select_opts('') ;

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

sub edit_screen {

# called from common_edit_screen

&select_opts($i{id}) ;

$custom_back_button = qq~&nbsp;<button type="button" class="btn btn-default" onclick="window.location.assign('/active-tickets')">Back</button>~ ;

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

sub select_opts {

	my ($id) = @_ ;

	# $selected{contact_title}{$db{$table}{$id}{contact_title}} =  'SELECTED' ;
	# $select{contact_title} = 1 ;
	# $opts{contact_title}   = qq(<option value="Mr" $selected{contact_title}{Mr}>Mr</option><option value="Mrs" $selected{contact_title}{Mrs}>Mrs</option>) ; 

	$opts{staff_id}  = qq~<option value="0">-- blank --</option>~ ;  			  
	$opts{client_id} = qq~<option value="0">-- blank --</option>~ ;  			  
	# $opts{camera_ids} = qq~<option value="0">-- blank --</option>~ ;  
				  
	# &common_min_select_opts('staff_id','users','username',$db{$table}{$id}{staff_id},1) ;
	&common_min_select_opts('staff_id','users','username',$db{$table}{$id}{staff_id},1,,'',"user_type NOT LIKE 'casual%' AND block <> 1 AND inactive <> 1") ;
	&common_min_select_opts('client_id','customers','name',$db{$table}{$id}{client_id},1) ;
	&common_min_select_opts('priority_id','priority','name',$db{$table}{$id}{priority_id},1) ;

	&common_load_quote_vars("quotes.quote_to='$db{$table}{$id}{client_id}'");

	$select{camera_ids}   = 1 ;
	$multiple{camera_ids} = 1; 
	# $setmultiple = 'multiple' ;

	my @camera_ids = split(/\,/,$db{$table}{$id}{camera_ids});

	foreach (@camera_ids) { 
		$selected_multi{$_} = 'SELECTED' ; 
		&common_debug("SELECTED camera_ids [$_] : [selected=$selected_multi{$_}]") ;
	}

	foreach my $cam_id (keys %quote_customer) {
		next if $gotit{$cam_id} ;
		# $selected        = ($cam_id eq $db{$table}{$id}{camera_ids}) ? 'SELECTED' : '' ;
		$selected          = ($selected_multi{$cam_id}) ? 'SELECTED' : '' ;
		my $cam_txt        = qq~$quote_camera_camera_nr{$cam_id} [$quote_camera_serial_nr{$cam_id}]~ ; $cam_txt =~ s/\-/ /g ; # $cam_txt =~ s/ //g ;
           $cam_txt       .= qq~ $quote_nr{$cam_id}~ if $quote_nr{$cam_id} ;
		$opts{camera_ids} .= qq~<option value="$cam_id" $selected>$cam_txt</option>~ ; 
		$gotit{$cam_id}    = 1 ;
	}

	# &common_min_select_opts('camera_ids','cameras','camera_nr',$i{camera_ids},1,'serial_nr',"quote_nr>0") ;

	$extra_form_fields .= qq~<input type="hidden" name="cameraids" id="camera-ids" value="">~;

	$trigger_jquery_raw .= qq(
	\$("#selectClient_id").change(function() {
		var cid  = \$("#selectCamera_ids") ;
		cid.empty(); // remove old options
		cid.trigger("chosen:updated");
		var url = "$useropts{scripts}/get/get_db_cameras.pl?clientid=" + \$("#selectClient_id").val() ;
		\$.get(url, function(json) {
		  \$.each(json, function(key, data) {
			let txt = '' ;
			if (data.camera_nr) { txt = data.camera_nr ; }
			if (data.serial_nr) { txt = txt + " [" + data.serial_nr + "]" ; }  
			    txt = txt.replace(/-/g, " ");
			cid.append("<option value='"+data.id+"'>"+txt+"</option>");
			cid.trigger("chosen:updated");
		  });
		},
		'json');    
		});
	);
	
	$trigger_jquery_raw .= qq~
	\$("#savebutt").click(function() {
		let msg_x = '' ;
		let sc_val = \$("#selectCamera_ids").chosen().val() ;
		\$('#camera-ids').val(sc_val);
	    \$('#tickets-form').submit();   
	});~;

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

sub page_opts {

our $glyphicon = 'envelope' ;
our $lcpage    = 'ticket' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; our $page_title = $ucfirstpage . 's' ;
our $table     = 'tickets' ; 

our $redirsave = 'active' ;
our $savjqy    = 1 ; # incorporate jquery into the save event to accommodate the multiple chosen options

$alert = qq~<div id="alertbar"></div>~ ;

$box_icon .= qq~<div class="box-icon"><a class="btn btn-info btn-round" href="javascript:dlgMdl('$useropts{'scripts'}/dialog/getmail.pl','Get Mail','height:100px;','pop-dialog');" data-toggle="tooltip" data-placement="top" data-title="Get Mail"><i class="glyphicon glyphicon-envelope" style="margin-top:1px;"></i></a></div>~ ;
# $box_icon .= qq~<div class="box-icon"><a class="btn btn-success btn-round" href="/open-tickets" data-toggle="tooltip" data-placement="top" data-title="Open Tickets"><i class="glyphicon glyphicon-eye-open" style="margin-top:1px;"></i></a></div>~ ;
# $box_icon .= qq~<div class="box-icon"><a class="btn btn-warning btn-round" href="/closed-tickets" data-toggle="tooltip" data-placement="top" data-title="Closed Tickets"><i class="glyphicon glyphicon-eye-close" style="margin-top:1px;"></i></a></div>~ ;
$box_icon .= qq~<div class="box-icon"><a class="btn btn-success btn-round" href="/open-tickets" data-toggle="tooltip" data-placement="top" data-title="Open Tickets"><i class="glyphicon glyphicon-tags" style="margin-top:1px;"></i></a></div>~ ;
$box_icon .= qq~<div class="box-icon"><a class="btn btn-warning btn-round" href="/closed-tickets" data-toggle="tooltip" data-placement="top" data-title="Closed Tickets"><i class="glyphicon glyphicon-tags" style="margin-top:1px;"></i></a></div>~ ;
	
# &common_add_box_icon ;

# $useropts{'common'}{'css'} .= qq~.top-block i {font-size: 12px;}~ ;
# $useropts{'common'}{'css'} .= qq~.box-icon .glyphicons::before { padding: 0px; }~ ;

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

use db ;
use common ;
use today ;

1;