#!/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'});
our $event_id 					= $ARGV[0] ;
our $system_id 					= $ARGV[1] ;
our $production_seconds 		= $ARGV[2] ;
our $cloud_recording_seconds 	= $ARGV[3] ;
our $event_code					= $ARGV[4] ;
our $date_from					= $ARGV[5] ;
our $date_to					= $ARGV[6] ;
our $row_cnt					= $ARGV[7] ;
our $action						= $ARGV[8] ;

$date_from =~ s/T/ /g;
$date_to =~ s/T/ /g;

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

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

our $savjqy = 1 ;
our $dialog = 1 ; 
 
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------

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
	
		$sort_field{1} 		= "event_id" ;
		$sort_field{2} 		= "system" ;
		# $sort_field{3} 		= "did_change_event" ;
		# $sort_field{4} 		= "did_change_system" ;
		# $sort_field{3} 		= "event_id" ;
		$select{event_id}	= 1 ;
		$select{system}	= 1 ;
		$box_header_title 	= 'Manually Match' ;
		$hidden_action    	= 'save' ;
		$head_col_width   	= 2 ;
		$allow_deselect{event_id} = 1 ;
		$allow_deselect{system} = 1 ;
		
		# $input{did_change_event} = 1 ; 
		# $input{did_change_system} = 1 ; 
		
		$extra_form_fields .= qq~<input type='text' name='did_change_event' value="0" style="display:none;" >~ ; #style="display:none;"
		$extra_form_fields .= qq~<input type='text' name='did_change_system' value="0" style="display:none;" >~ ; #style="display:none;"  
		
		&db_min_ro('event_systems','*',"",'','') ; 
		
		foreach my $id (sort {$db{event_systems}{$b}{name} cmp $db{event_systems}{$a}{name}} keys %{$db{event_systems}}) {
			
			my $selected = ($id eq $system_id) ? 'SELECTED' : '' ;
			$opts{system} .= qq~<option value="$id" $selected>$db{event_systems}{$id}{name} [$db{event_systems}{$id}{description}]</option>~ ;
		}
		#(date_from BETWEEN '$date_from' AND '$date_to') OR (date_to BETWEEN '$date_from' AND '$date_to') OR (date_from <= '$date_from' AND '$date_to' >= date_to)
		&db_min_ro('event_quotes','id,ref',"",'','') ;
		  
		foreach my $id (sort {$db{event_quotes}{$a}{ref} cmp $db{event_quotes}{$b}{ref}} keys %{$db{event_quotes}}) {
 
			my $selected = ($id eq $event_id) ? 'SELECTED' : '' ;
			$opts{event_id} .= qq~<option value="$id" $selected>$db{event_quotes}{$id}{ref} [$id]</option>~ ;
		}
		
		$trigger_jquery_raw .= qq~
		
			let input_event_id = "$event_id" ;
			
			if (parent.\$("#selectEvent_$row_cnt").val() != input_event_id) {
				\$("#selectEvent_id").val(parent.\$("#selectEvent_$row_cnt").val()) ;
				\$("#selectEvent_id").trigger("chosen:updated") ;
			}
						
			let input_system_id = "$system_id" ;
			
			if (parent.\$("#selectSystem_$row_cnt").val() != input_system_id) {
				\$("#selectSystem").val(parent.\$("#selectSystem_$row_cnt").val()) ;
				\$("#selectSystem").trigger("chosen:updated") ;
			}
			
		~ ; 
		
		$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
	&db_close_conn ;
	
	$trigger_jquery_raw .= qq~

		let original_event = "$event_id" ;
		let original_system = "$system_id" ;
		
		\$("#selectEvent_id").change( function () { 
			if (\$(this).val() != original_event) {
				\$("input[name='did_change_event']").val("1") ; 
			} else {
				\$("input[name='did_change_event']").val("0") ; 
			} 
		}) ;
		
		\$("#selectSystem").change( function () { 
			if (\$(this).val() != original_system) {
				\$("input[name='did_change_system']").val("1") ; 
			} else {
				\$("input[name='did_change_system']").val("0") ; 
			}		 
		}) ; 
	
	~ ; 
	
	# $trigger_jquery_raw .= qq~
	# // id="event_code_2"
		# console.log("Hello World") ; 
		# var helloValue = \$(window.parent.document).find('input[name="event_code_$row_cnt"]').val();
		# console.log("helloValue : "+helloValue) ; 
	# ~ ; 
	
} #------------------------------------------------------------------------------------------

sub add_db_fields {

	$ignore{iaction}    		= 1 ;
	$ignore{id}         		= 1 ; 
	$hidden{sel_field}  		= 2 ;
	$required{system}			= 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~
	
	\$('#savebutt').click(function (e) {
			
		\$("#event_production_time-form").submit() ;

	}) ;
	
	\$('#btn-close-customer').click(function (e) {
	   parent.BootstrapDialog.closeAll() ;
	});~ ;

	&common_min_dialog_load_screen ;

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

sub screen2 {
	
	&db_min_ro('event_quotes','id,ref',"id='$i{event_id}'") ; 
	&db_min_ro('event_systems','id,name,description',"id='$i{system}'") ; 
	
	$trigger_jquery_raw .= qq~

		let similar_rows = \$(window.parent.document).find('input[name="similar_rows_$row_cnt"]').val();

		let system_drop_down_exists = parent.\$("#matched_system_$row_cnt").find('#selectSystem_$row_cnt').length ;
		let event_drop_down_exists = parent.\$("#matched_event_$row_cnt").find('#selectEvent_$row_cnt').length ;
		
		let did_change_system = "$i{did_change_system}" ;
		let did_change_event = "$i{did_change_event}" ;
	 
		if (similar_rows && similar_rows !== undefined && ((system_drop_down_exists && system_drop_down_exists !== undefined) || (event_drop_down_exists && event_drop_down_exists !== undefined))) {
			
			let similar_system_ids = similar_rows.split(',').filter(num => num !== '$row_cnt').map(num => '#selectSystem_' + num).join(',');  
			let similar_event_ids = similar_rows.split(',').filter(num => num !== '$row_cnt').map(num => '#selectEvent_' + num).join(',');  

			if (did_change_system) { 
				
				let select_system_option_exists = parent.\$("#selectSystem_$row_cnt").find("option[value='$i{system}']").length ; 

				if (!select_system_option_exists) { 
					parent.\$(similar_system_ids).append("<option value='$i{system}'>$db{event_systems}{$i{system}}{name}&nbsp;[$db{event_systems}{$i{system}}{description}]</option>") ;
					parent.\$(similar_system_ids).trigger("chosen:updated");					
				}
				
				let similar_system_ids_arr = similar_system_ids.split(',') ;
				for (let id1 in similar_system_ids_arr) {
					// console.log("id1 ; "+similar_system_ids_arr[id1]) ; 
					if (!parent.\$(similar_system_ids_arr[id1]).val()) {
						parent.\$(similar_system_ids_arr[id1]).val("$i{system}") ;
						parent.\$(similar_system_ids_arr[id1]).trigger("chosen:updated");					
					} 
				}  
			} 
			
			if (did_change_event) { 
				
				let select_event_option_exists = parent.\$("#selectEvent_$row_cnt").find("option[value='$i{event_id}']").length ; 
				if (!select_event_option_exists) {
					parent.\$(similar_event_ids).append("<option value='$i{event_id}'>$db{event_quotes}{$i{event_id}}{ref}&nbsp;[$i{event_id}]</option>") ;
					parent.\$(similar_event_ids).trigger("chosen:updated");	
				}
				
				let similar_event_ids_arr = similar_event_ids.split(',') ;
				for (let id2 in similar_event_ids_arr) {
					if (!parent.\$(similar_event_ids_arr[id2]).val()) {
						parent.\$(similar_event_ids_arr[id2]).val("$i{event_id}") ;
						parent.\$(similar_event_ids_arr[id2]).trigger("chosen:updated");					
					} 
				}  
			} 
		}
		 
		var url = "$useropts{scripts}/get/add_event_system_hours.pl?$i{event_id}&$i{system}&$production_seconds&$cloud_recording_seconds&$event_code" ;
		
		\$.get(url) ;
		
		// console.log("url : "+url) ; 
		
		let matched_row_ids = similar_rows.split(',').filter(num => num !== '$row_cnt').map(num => '#matched_row_' + num).join(',');  
		let not_matched_ids = similar_rows.split(',').filter(num => num !== '$row_cnt').map(num => '#not_matched_' + num).join(',');  
		
		parent.\$(matched_row_ids).removeClass('btn btn-danger btn-sm').addClass('btn btn-success btn-sm');	 			
		parent.\$(matched_row_ids).html("<i class='glyphicon glyphicon-ok'></i>") ; 	 			
		parent.\$(not_matched_ids).val("") ;
		parent.\$("#$row_cnt").css("display","none") ; 
		parent.\$("#final_col_$row_cnt").html('') ;
		parent.\$("#matched_system_$row_cnt").html('') ;
		parent.\$("#matched_event_$row_cnt").html('') ;
	
		parent.BootstrapDialog.closeAll() ;
	
	~;

	&common_min_dialog_save_screen ;

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

use today ;
use dialog ;
use common ;

1;