#!/usr/bin/perl

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

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

&today ;

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

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

@ARGV		= split(/\\*\&/, $ENV{'QUERY_STRING'});
$action				= $ARGV[0] ;
$date_from 			= $ARGV[1] ;
$date_to 			= $ARGV[2] ;
$quote_to 			= $ARGV[3] ;
$organisation_ids 	= $ARGV[4] ;
$supplier_id 		= $ARGV[5] ;
$status_id 			= $ARGV[6] ;
$region_id 			= $ARGV[7] ;
# $from_to 			= $ARGV[8] ;

# our $debug  = 1 ;
our $table    = 'event_quotes_poc' ;

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

# if ($username ne 'handre') {
	# print "<< MAINTENANCE IN PROGRESS >>" ; exit ; 	
# }

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

if ($iaction eq 'add') {
    &common_min_add_screen;
    &screen1;
}
    
if ($iaction eq 'save') {
    &common_min_load_params ;
    # &update ;
    &screen2 ;
}
	
&common_min_action;
   
exit ;    

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

sub update {

	# &add_db_fields ; # $i{last_edited_by} = $userid ; $i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ;
	
	# &validate ;
	
	# $ignore{sel_field} = 1 ;
	
	# # $i{id} = &db_min_get_max($table,'id') ;

	# &db_min_upd($table,) ;

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

# sub validate {

	# # called from common_min_action

	# my $exists   = '' ;

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

	# &db_min_ro($table,'id,poc_name,poc_contact_nr',"`poc_name`='$i{poc_name}' AND `poc_contact_nr`='$i{poc_contact_nr}'",'','') ;

	# foreach my $id (keys %{$db{$table}}) {
		# if ($db{$table}{$id}{poc_name} eq $i{poc_name} && $db{$table}{$id}{poc_contact_nr} eq $i{poc_contact_nr}) {
			# $exists = 1 ;
			# last ;
		# }
	# }
		
	# if ($exists) {
		# $alert = &common_min_alert('warning',"POC ALREADY EXISTS!",'warning-sign') ;
		# %col_name = () ;
		# &common_min_add_screen;
		# &screen1;
    # }

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

sub add_screen {
	
	&db_open_ro ;
		our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
		
		$print_box_content_rows .= &common_min_forms_start("event-quotes-poc-recipient") ;
		
		# $sort_field{1} 				= "$name_field1" ;
		# $sort_field{2} 				= "$nr_field1" ;
		# $sort_field{3} 				= "event_id" ;
		$ignore{contact_nr} = 1 ; 
		$ignore{name} = 1 ; 
		# $select{event_id}			= 1 ;
		# $allow_deselect{event_id} 	= 1 ;
		$box_header_title 			= "Add POC" ;
		$hidden_action    			= 'save' ;
		$head_col_width   			= 2 ;
		
		# $select{$name_field1} = 1 ; 
		# $select{$nr_field1} = 1 ; 
		
		$trigger_jquery_raw .= qq~
			
			\$("#selectPoc_name,#selectPoc_contact_nr,#selectRecipient_name,#selectRecipient_nr,#selectEvent_id").chosen({ allow_single_deselect:false }) ;
			\$("#selectRecipient_nr_chosen,#selectRecipient_name_chosen").css("width","100%") ;

		~ ; 
		
		&db_min_ro('event_quotes_poc','*','','','') ;
		&db_min_ro('event_quotes_recipient','*','','','') ;
 
		$add_form_fields = '' ;
		
		$fcol = 3 ; $lcol = 1 ;
		
		# our %required = () ; 
		
		$required{poc_name} = 'data-validation="required"' ; $req_glyph{poc_name} = qq(<i class="glyphicon glyphicon-asterisk yellow"></i>) ; 
		
		$required{poc_contact_nr} = $required{poc_name} ; $req_glyph{poc_contact_nr} = $req_glyph{poc_name} ;
		$required{event_id} = $required{poc_name} ; $req_glyph{event_id} = $req_glyph{poc_name} ;
		
		$add_form_fields .= qq~<input type='hidden' name='recipient' value='0'>~ ;
		$add_form_fields .= qq~<input type='hidden' name='poc' value='1'>~ ;
		
		$add_form_fields .= qq~<div id='poc_section'>~ ; 
		
		&common_shared_poc_recipient_select_code("poc",1) ; 
		
		$add_form_fields .= qq~</div><div id='recpient_section' style='display:none;'>~ ;  #  
		
		&common_shared_poc_recipient_select_code("recipient",1) ; 
		
		$add_form_fields .= qq~</div>~ ; 
		
		&common_shared_poc_recipient_select_shared_jquery ;

		&common_shared_build_select_primary_jquery ;

		$print_box_content_rows .= $add_form_fields ;
		
		$trigger_jquery_raw .= qq~
			
			let map_event_id_to_recipient = {} ; 
			
			\$("#selectEvent_id").on("change", async function () {
				
				let event_id = \$(this).val() ;

				if (!map_event_id_to_recipient[event_id]) {

					let url = "$useropts{scripts}/get/get_recipient_from_event_quote.pl?event_quote_id="+event_id ; 

					let recipient_id = "" ; 
					await \$.get(url, function(json) {
						\$.each(json, function(key, data) {
							if (data.recipient_id) {
								if (data.recipient_id == "0") {
									map_event_id_to_recipient[event_id] = "-1" ;
								} else {
									map_event_id_to_recipient[event_id] = data.recipient_id ;
								}
							}
						}) ;
					},'json') ;					
				}

				if (map_event_id_to_recipient[event_id] && map_event_id_to_recipient[event_id] != "-1" && \$("#recpient_section").is(":hidden")) {

					\$("#recpient_section").show() ; 
					\$("#poc_section").hide() ; 
					\$("#selectPoc_name").removeAttr("data-validation") ;
					\$("#selectPoc_contact_nr").removeAttr("data-validation") ;	
					\$("label[for='selectPoc_name'] i.glyphicon-asterisk.yellow").remove();
					\$("label[for='selectPoc_contact_nr'] i.glyphicon-asterisk.yellow").remove();
					\$("label[for='selectRecipient_name']").append('<i class="glyphicon glyphicon-asterisk yellow"></i>') ;
					\$("label[for='selectRecipient_nr']").append('<i class="glyphicon glyphicon-asterisk yellow"></i>') ;
					\$("#selectRecipient_name").attr("data-validation", "required");
					\$("#selectRecipient_nr").attr("data-validation", "required");	
					\$("input[name='poc']").val("0") ; 
					\$("input[name='recipient']").val("1") ; 
					
				} else if ((!map_event_id_to_recipient[event_id] || map_event_id_to_recipient[event_id] == "-1") && \$("#poc_section").is(":hidden")) {

					\$("#recpient_section").hide() ; 
					\$("#poc_section").show() ;
					\$("label[for='selectPoc_name']").append('<i class="glyphicon glyphicon-asterisk yellow"></i>') ;
					\$("label[for='selectPoc_contact_nr']").append('<i class="glyphicon glyphicon-asterisk yellow"></i>') ;
					\$("#selectPoc_name").attr("data-validation", "required");
					\$("#selectPoc_contact_nr").attr("data-validation", "required");		
					\$("#selectRecipient_name").removeAttr("data-validation") ;
					\$("#selectRecipient_nr").removeAttr("data-validation") ;	
					\$("label[for='selectRecipient_name'] i.glyphicon-asterisk.yellow").remove();
					\$("label[for='selectRecipient_nr'] i.glyphicon-asterisk.yellow").remove();
					\$("input[name='poc']").val("1") ; 
					\$("input[name='recipient']").val("0") ; 
					
				}
				
			}) ;
		
		~ ; 
		
		&db_min_ro('event_systems','*',"(`system_type` = 'mobile' OR `description` lIKE 'cricket%')",'','') ; 
		
		my @report_sql = () ;
		
		if ($from_to eq 'to') {
			push @report_sql, "('$now_ccyy_mm_dd' <=`date_from`)" ;
		} else {
			push @report_sql, "('$now_ccyy_mm_dd' <=`date_to`)" ;
		}
		
		# if ($date_from && !$date_to) { # check dates
			# push @report_sql, "`date_from` >= '$i{date_from} 00:00:00'" ; ############################################### > OR >=
		# } elsif ($date_from && $date_to) { # check dates
			# push @report_sql, "(('$date_from 00:00:00' <= `date_from` AND `date_from` <= '$date_to 23:59:59') OR ('$date_from 00:00:00' <= `date_to` AND `date_to` <= '$date_to 23:59:59'))" ; 
		# } 

		if ($date_from && $date_to) {
			push @report_sql, "(
				('$date_from 00:00:00' <= `date_from` AND `date_from` <= '$date_to 23:59:59') OR 
				('$date_from 00:00:00' <= `date_to` AND `date_to` <= '$date_to 23:59:59') OR 
				('$date_from 00:00:00' >= `date_from` AND `date_to` >= '$date_to 23:59:59') OR 
				('$date_from 00:00:00' <= `date_from` AND `date_to` <= '$date_to 23:59:59')
			)" ; ############################################### > OR >=
			push @report_results, "(EVENT EXISTS BETWEEN '$date_from' AND '$date_to')" ;
		} elsif (!$date_from && $date_to) {
			push @report_sql, "`date_to` >= '$date_to 23:59:59'" ; ############################################### > OR >=
			push @report_results, "(EVENT ENDING BEFORE '$date_to')" ;		
		} elsif ($date_from && !$date_to) {
			push @report_sql, "'$date_from 00:00:00' <= `date_from`" ; ############################################### > OR >=
			push @report_results, "(EVENT STARTING AFTER '$date_from')" ;		
		} elsif (!$date_from && !$date_to) {
			# $error = qq~PLEASE ENTER AT LEAST A START OR END DATE!!!~ ;
		}
			
		# if ($date_from) { # check dates
			# push @report_sql, "`date_to` >= '$date_from'" ;
		# } 		
		# if ($date_to) { # check dates
			# push @report_sql, "`date_to` <= '$date_to'" ;
		# } 
		if ($quote_to) {    
			push @report_sql, "(`quote_to` = '$quote_to')" ;
		}	
		
		if ($organisation_ids) {
			push @report_sql, "(FIND_IN_SET($organisation_ids,organisation_ids))" ;
		}	
		
		if ($supplier_id) {
			
			push @report_sql, "((logistics_suppliers REGEXP '(^|;)[^-]*-$supplier_id(\$\|;)') OR (logistics_suppliers REGEXP '(^|;)($supplier_id)-[^;]*(\$\|;)'))" ;
			# push @report_results, "Supplier = `$db{logistics_suppliers}{$supplier_id}{supplier}`" ;
			
			# if ($from_to eq 'to') {
				# push @report_sql, "(logistics_suppliers REGEXP '(^|;)[^-]*-$supplier_id(\$\|;)')" ;
			# } else {
				# push @report_sql, "(logistics_suppliers REGEXP '(^|;)($supplier_id)-[^;]*(\$\|;)')" ;
			# }
		}
		
		if ($status_id) {
			push @report_sql, "((logistics_status_ids REGEXP '(^|;)[^-]*-$status_id(\$\|;)') OR (logistics_status_ids REGEXP '(^|;)($status_id)-[^;]*(\$\|;)'))" ;
			# if ($from_to eq 'to') {
				# push @report_sql, "(logistics_status_ids REGEXP '(^|;)[^-]*-$status_id(\$\|;)')" ;
			# } else {
				# push @report_sql, "(logistics_status_ids REGEXP '(^|;)($status_id)-[^;]*(\$\|;)')" ;
			# }
			# push @report_sql, "(`logistics_status_ids` LIKE '$i{status_id}-%' OR `logistics_status_ids` LIKE '%-$i{status_id}')" ; 
		}	
		
		# if ($organisation_ids) {
			# push @report_sql, "(`organisation_ids` LIKE '%$organisation_ids%')" ;
		# }	
		# if ($supplier_id) {
			# push @report_sql, "(`logistics_suppliers` LIKE '%-$supplier_id' OR `logistics_suppliers` LIKE '$supplier_id-%')" ;
		# }
		# if ($status_id) {
			# push @report_sql, "(`logistics_status_ids` LIKE '%-$status_id' OR `logistics_status_ids` LIKE '$status_id-%')" ;
		# }	
		if ($region_id) {
			push @report_sql, "`region_id` = '$region_id'" ;
		}
		
		my $srch_where_sql = join(' AND ',@report_sql) ; 
		
		$table = 'event_quotes' ;
		
		&db_min_ro($table,'id,ref,event_system_id_multiple,organisation_ids',"$srch_where_sql",'','') ;
		
		foreach my $id (sort {$db{$table}{$a}{ref} cmp $db{$table}{$b}{ref}} keys %{$db{$table}}) {
		
			if ($organisation_ids) {
				my @or_ids_arr =  split(/\,/,$db{$table}{$id}{organisation_ids}) ;	
				my $cnt = 0 ; 
				foreach my $or_id (@or_ids_arr) {
					next unless $or_id ;
					$cnt++ if $or_id eq $organisation_ids ;
				}
				next unless $cnt ;			
			}
			my @system_name_ids = split(/\;/,$db{$table}{$id}{event_system_id_multiple}) ;		  
			my $cnt = 0 ; 
			foreach my $event_sys_id (@system_name_ids) {
				next unless $event_sys_id ;
				next unless $db{event_systems}{$event_sys_id}{system_type} ;
				$cnt++ ;
			}
			next unless $cnt ;
			$opts{event_id} .= qq~<option value="$id">$db{$table}{$id}{ref} [$id]</option>~ ;
		}
		
		
		$print_box_content_rows  .= &common_min_form_select('event_id') ; 
		
		$print_box_content_rows .= &common_min_forms_end('','','save') ; ;
		
		$table = 'event_quotes_poc' ;
		
		$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
	&db_close_conn ;
	
} #------------------------------------------------------------------------------------------

sub add_db_fields {

	$ignore{iaction}    		= 1 ;
	$ignore{id}         		= 1 ; 
	$hidden{sel_field}  		= 2 ;
	$required{poc_name}			= 1 ;
	$required{poc_contact_nr}	= 1 ;
	$required{event_id}			= 1 ;
	# $eventids =~ s/\,/\,#selectItem_/g ;
	# $eventids = substr($eventids,1) ;
	# $db{$table}{''}{sel_field} = $eventids if $eventids ;
	
} #------------------------------------------------------------------------------------------

sub thead {

	&common_min_thead ;
    
} #-------------------------------------------------------------------------------
 
sub screen1 {

	$trigger_jquery_raw .= qq~
	\$('#btn-close-customer').click(function (e) {
	   parent.BootstrapDialog.closeAll() ;
	});~ ;
	
		# require _blank_4 ;
	
	&common_min_dialog_load_screen ;

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

sub screen2 {
 
	if ($i{recipient}) {
		$trigger_jquery_raw .= qq~parent.\$("#selectPoc_from_$i{event_id},#selectPoc_to_$i{event_id}").append("<option value='$i{recipient_id}' SELECTED>$i{recipient_name}&nbsp;[$i{recipient_nr}]</option>")~ ;
	} elsif ($i{poc}) {
		$trigger_jquery_raw .= qq~parent.\$("#selectPoc_from_$i{event_id},#selectPoc_to_$i{event_id}").append("<option value='$i{poc_id}' SELECTED>$i{poc_name}&nbsp;[$i{poc_contact_nr}]</option>")~ ;
	}
	
	if ($i{recipient_id} || $i{poc_id}) {
		$trigger_jquery_raw .= qq~
			// parent.\$("$eventids").val('$new_row_id').trigger('change'); // this must stay commented out for multi-selects, otherwise it removes existing selected options
			parent.\$("#selectPoc_from_$i{event_id}").trigger("chosen:updated");
			parent.\$("#selectPoc_to_$i{event_id}").trigger("chosen:updated");
			parent.\$("#checkboxUpdate_from_$i{event_id}").prop("checked",true) ; 
			parent.\$("#checkboxUpdate_to_$i{event_id}").prop("checked",true) ; 
			parent.BootstrapDialog.closeAll() ;
		~;
	}

	&common_min_dialog_save_screen ;

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

use today ;
use dialog ;
use common ;
use common_shared ;

1;