#!/usr/bin/perl

BEGIN { use lib '/usr/home/cfg' ; require push_inc ; }
    
require cfg ;
# unless ($username eq 'handre') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; }
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------

use CGI::Carp qw(fatalsToBrowser);
use CGI;
use Mail::Sendmail;
use Fcntl qw(:flock);
use File::Copy;
use File::Basename;
use Date::Calc qw(:all);
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 $cnt_match_credits = 4 ; # used in common_load_quote_vars

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

&page_opts ;

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

print "Content-type: text/html\n\n";
	
our $srchscr   = 1 ;

&db_open_ro ;
    our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it
	if ($iaction eq ''){ &report_screen ; }
	&common_min_action;
	$db_ignore_open_close = 0 ; # do one open and one close instead of repeating it
&db_close_conn ;

exit;

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

sub report_ifields {
		
	&load_search_vars ;
		
	if ($i{date_from} and $i{date_to}) { # check dates
		my $date_from_check = $i{date_from} ;
		   $date_from_check =~ s/\-//g ;
		my $date_to_check = $i{date_to} ;
		   $date_to_check =~ s/\-//g ;
		if ($date_from_check > $date_to_check) { $error = qq(CAMERAS FROM ($i{date_from}) > CAMERAS TO ($i{date_to})); &report_screen; }
	}
		
	if ($i{date_from}) {
		push @report_sql, "(`quote_date` >= '$i{date_from}')" ;
		push @report_results, "quote_date >= $i{date_from}" ;
	}

	if ($i{date_to}) {
		push @report_sql, "(`quote_date` <= '$i{date_to}')" ;
		push @report_results, "quote_date <= $i{date_to}" ;
	}
		
	if ($i{client_id}) {    
		push @report_sql, "(`quote_to`='$i{client_id}')" ;
		push @report_results, "Client = $client{$i{client_id}}" ;
	}
		
	if ($i{options} eq 'accepted') {    
		# push @report_sql, "(`quote_to`='$i{client_id}')" ;
		# push @report_results, "Client = $client{$i{client_id}}" ;
		
		push @report_sql, "(`quote_accepted`=1)" ;	
		push @report_results, "Quote Accepted = 'Yes'" ;
	}
	
	if ($i{options} eq 'cancelled') {    
		
		push @report_sql, "(`quote_cancelled`=1)" ;	
		push @report_results, "Quote Cancelled = 'Yes'" ;
	}
	
	if ($i{options} eq 'pending') {    
		
		push @report_sql, "(`quote_pending`=1)" ;	
		push @report_results, "Quote Pending = 'Yes'" ;
	}
		
	
	push @report_sql, "(`invoice_nr`>0)" ;
	push @report_results, "Invoice Nr exists" ;
		
	$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 {

	if ($i{client_id}) {
		my $customers_sql_where = "`id`='$i{client_id}'" ;
		&db_min_ro('customers','*',$customers_sql_where,'','') ;
		foreach my $id (keys %{$db{customers}}) { $client{$id} = $db{customers}{$id}{name} ; }
	}

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

sub list_screen {

	my $srch_where_sql = join(' AND ', @report_sql) ;
	my $add_sql_where = '' ;
	&load_list_vars("$srch_where_sql$add_sql_where") ;
	&quote_list;
	
		
	# our @sql_col_display = ("invoice_date","invoice_nr","client_id","ref","type","qty","roe","amount_usd","amount_zar","total") ;
	# # our @sql_col_display = ("nr","date","customer","event","location","city","date_from","date_to","days","type","ligr","amount","invoice_nr","") ;
	# # &report_xlsx_export_header_events("Event_Quote_$xlsreportname",'events') ;



	# # foreach my $id (sort {$b <=> $a} keys %{$db{$table}}) {
			
		# # $print_tbody .= qq~<tr>~ ;
		
		# # $xlscol=0;
		
		# # foreach (@sql_col_display) { 
			# # unless ($_) { next ; } # blank for the buttons column
			# # my $val = $db{$table}{$id}{$_} ;
			# # my $align = '' ;
			
			# # my $center = qq~ class="dt-center"~ ;
			# # my $right  = qq~ class="dt-right"~ ;
			
			# # if ($_ eq 'amount_usd')         { $val   = &common_commify(sprintf("%0.2f",$usd_match_credit)) ; $align = $right  ; }
			# # if ($_ eq 'amount_zar')         { $val   = &common_commify(sprintf("%0.2f",$zar_match_credit)) ; $align = $right  ; }
			# # if ($_ eq 'total')              { $val   = &common_commify(sprintf("%0.2f",($db{$table}{$id}{grand_total}))) ; $align = $right ; }
			# # if ($_ eq 'invoice_date')       { $val   = $db{$table}{$id}{invoice_date}                                         ; }
			# # if ($_ eq 'invoice_nr')         { $val   = $db{$table}{$id}{invoice_nr} ; $align = $center                        ;}
			# # if ($_ eq 'type')               { $val   = $quote_match_credit                                                    ; }
			# # if ($_ eq 'roe')                { $val   = $db{$table}{$id}{roe} ; $align = $center                               ; }
			# # if ($_ eq 'qty')                { $val   = $db{$table}{$id}{qty} ; $align = $center                               ; }
			# # if ($_ eq 'ref')                { $val   = $db{$table}{$id}{quote_nr} ; $align = $center                          ; }
			# # if ($_ eq 'client_id')          { $val   = $customer{$db{$table}{$id}{quote_to}}                                  ; }
			
			# # &report_xlsx_export_process_cell('','',$val) ; # ------------------------------------------------------------------------- HTML AFTER
			# # $xlscol++; 
			
			# # $val = &common_camera_links_events($table,$id,$val) if $_ eq 'camera_nr' or $_ eq 'ref_nr' ;
			
			# # if ($_ eq 'in_stock') { 
				# # if ($val==1) { 
					# # $val = &set_tick('green', '') ; 
				# # } else { $val = &set_tick('red', '') ; 
				# # } 
				# # $align = $center ; 
			# # }
			
			# # $val = &common_camera_links_events($table,$id,$val) if $_ eq 'ref' ;
			
			# # $print_tbody .= qq~<td $align>$val</td>~ ;  
			# # }
			
		# # $print_tbody .= qq~</tr>~ ;
		# # $xlsrow++ ;
		# # }
		
	# # &report_xlsx_export_footer('L',15,'events') ;

	# # $fnsortcol   = 3 ; 
	# # $fnsortorder = 'asc' ;

	# # $print_more_boxes .= qq~<br><button type="button" class="btn btn-default" onclick="history.go(-1);">Back</button><br><br>~ ;

	# # &common_min_extra_crumb("$lcpage-report","Search Screen") ;
		
} #------------------------------------------------------------------------------------------

sub quote_list {

	our @sql_col_display = ("nr","date","customer","event","location","city","date_from","date_to","days","type","ligr","amount","invoice_nr","") ;
	our @col_display_excel = ("event", "date", "day", "sport_type", "production_type", "ligr_integration", "location","city_&_province", "onsite_team") ; 
	&report_xlsx_export_header_events("Events",'events') ; 
	$worksheet{$ws} -> set_row(0, 40) ; 
	$worksheet{$ws} -> set_row(1, 25) ;
	$worksheet{$ws} -> set_row(2, 25) ;
	$worksheet{$ws} -> set_row(3, 5) ;
	
	$worksheet{$ws} -> set_column(0,0,50);
	$worksheet{$ws} -> set_column(1,1,20);
	$worksheet{$ws} -> set_column(2,2,15);
	$worksheet{$ws} -> set_column(3,3,20);
	$worksheet{$ws} -> set_column(4,4,40);
	$worksheet{$ws} -> set_column(5,5,20);
	$worksheet{$ws} -> set_column(6,6,20);
	$worksheet{$ws} -> set_column(7,7,20);
	$worksheet{$ws} -> set_column(8,8,45);
	my @month_fullname = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") ; 
	# if ($i{export_to_excel}) { &report_xls_export_header("Event Quotes",'event_quotes') ; }
	my @day_of_week_text = ("", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") ;
	foreach my $id (sort {$b <=> $a} keys %{$db{$tables}}) {
		
		unless ($id) { next ; }
		
		my $quote_expiry = $db{$tables}{$id}{quote_expiry} ; $quote_expiry =~ s/\-//iog ;
		
		# if ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd" and $iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all') { next ; }
		if ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd" and $db{$tables}{$id}{quote_accepted}!=1 and
			$iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all' and 
			$i{options} ne 'accepted' and $i{options} ne 'closed' and $i{options} ne 'all') 
		{ next ; }
		
		$print_tbody .= qq~<tr>~ ;
		
		$xlsxcol=0;
		
		my $quote_nr = $db{$tables}{$id}{quote_nr} ;
		
		foreach (@sql_col_display) { 
			unless ($_) { next ; } # blank for the buttons column
			my $val = $db{$tables}{$id}{$_} ;
			my $align = qq~ class="dt-center"~ ; 
			my $nowrap = '' ;
			
			if ($_ eq 'date_to')		   { 
				$val   = substr($db{$tables}{$id}{date_to},0,10) ;   
				$align = qq~ class="dt-center" style="width:6.9%"~ ; 
			} elsif ($_ eq 'date_from') { 
				$val   = substr($db{$tables}{$id}{date_from},0,10) ; 
			} elsif ($_ eq 'event') { 
				$val   = $db{$tables}{$id}{ref} ;       
				$nowrap = 'nowrap' ;    
			} elsif ($_ eq 'customer') { 
				$val   = $customer{$db{$tables}{$id}{quote_to}} ;  
				$nowrap = 'nowrap' ;    	
			} elsif ($_ eq 'date') { 
				$val   = $db{$tables}{$id}{quote_date} ; 
			} elsif ($_ eq 'curr'){ 
				$val   = $db{$tables}{$id}{currency} ;  			
			} elsif ($_ eq 'city'){ 
				$val   = $db{$tables}{$id}{city} ;  			
			} elsif ($_ eq 'ligr'){ 
				$val   = $db{$tables}{$id}{ligr} ;  			
			} elsif ($_ eq 'country_id') { 
				$val   = $db{$tables}{$id}{country} ; 
			} elsif ($_ eq 'days') { 
				$val   = $db{$tables}{$id}{qty} ; 				
			} elsif ($_ eq 'type') { 
				$val   = $event_types{$db{$tables}{$id}{type}} if $db{$tables}{$id}{type} ;   				
			} elsif ($_ eq 'amount')  { 
				my $ttl = sprintf("%0.2f",($db{$tables}{$id}{grand_total})) ;
				   $val = &common_commify($ttl) ; 	  
			} elsif ($_ eq 'nr') { 
				my $class = 'info' ; 
				if ($db{$tables}{$id}{quote_cancelled}) {
					$class = 'danger' ;
				} elsif ($db{$tables}{$id}{quote_accepted}) {
					$class = 'success' ; 
				# } elsif ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd") {
					# $class = 'danger' ;
				} elsif ($db{$tables}{$id}{quote_pending}) {
					$class = 'warning' ; 
				} 
				$val = qq~<a class="btn btn-$class btn-xs" href="javascript:editMinItem('$id');">$quote_nr</a>~ ; 
			}
			$print_tbody .= qq~<td $nowrap $align>$val</td>~ ;  
		}
		
## EXCEL----------------------------
		
		my $start_date = substr($db{$tables}{$id}{date_from},0,10); 
		my $end_date = substr($db{$tables}{$id}{date_to},0,10); 
		my @event_dates = () ; 
		
		my $year = substr($db{$tables}{$id}{date_from}, 0, 4 ) ; 
		my $month = substr($db{$tables}{$id}{date_from}, 5, 2 ) ; 
		my $day = substr($db{$tables}{$id}{date_from}, 8, 2 ) ; 	
		
		push (@event_dates, $year . '-' . $month . '-' . $day) ;
 
		while ($start_date ne $end_date){	
		
			($year,$month,$day) = Add_Delta_Days($year,$month,$day,1) ;
			$day 	= sprintf("%02d", $day) ;  
			$month 	= sprintf("%02d", $month) ; 
			push (@event_dates, $year . '-' . $month . '-' . $day) ; 
			$start_date = $year . '-' . $month . '-' . $day ; 
		}
		
		# print "EVENT_DATES: @event_dates\n" ; 
		my $row_count = 0; 
		for my $event_date (sort @event_dates) {
			$xlsxcol = 0 ; 
			$row_count++ ; 
			foreach (@col_display_excel) { 
				
				if ($_ eq 'event') { 
					$val   = $db{$tables}{$id}{ref} ; 
				} elsif ($_ eq 'date') { 	
					$val  = substr($event_date, 5, 2 )  ;
					$val = substr($event_date, 8, 2 ) . ' ' . $month_fullname[$val - 1] . ' ' .  substr($event_date, 0, 4 ) ; 									
				} elsif ($_ eq 'day') { 
					$year = substr($event_date, 0, 4 ) ; 
					$month = substr($event_date, 5, 2 ) ; 
					$day = substr($event_date, 8, 2 ) ; 	
					my $dow = Day_of_Week($year,$month,$day); 
					$val  = $day_of_week_text[$dow] ; 
				} elsif ($_ eq 'sport_type') { 
					$val = $db{$tables}{$id}{sports_type} ; 
				} elsif ($_ eq 'production_type') {
					$val = $event_types{$db{$tables}{$id}{type}} if $db{$tables}{$id}{type};
				} elsif ($_ eq 'ligr_integration') { 
					$val = $db{$tables}{$id}{ligr} ; 
				} elsif ($_ eq 'location') { 
					$val = $db{$tables}{$id}{location} ;
				} elsif ($_ eq 'city_&_province') { 
					$val = $db{$tables}{$id}{city} ; 
					$val = &get_province_name($val) ;
				} elsif ($_ eq 'onsite_team') { 		
					if ($onsite_team{$db{$tables}{$id}{quote_nr}}){
						$val  = $onsite_team{$db{$tables}{$id}{quote_nr}}; 
					} else {
						$val = "Unknown" ; 
					}				
				}    		
				if ($event_date ne $end_date) {
					&report_write_events($val, 0) ;
				} else {
					&report_write_events($val, 1) ;
				}
				$xlsxcol++; 
			}
			$xlsxrow++; 
		}
# EXCEL---------------------------------------------
	
		my $delete_butt = '' ;
		my $edit_butt = '' ;		
		my $quote_nr = $quote_nr ; $quote_nr =~ s/'//iog; unless ($quote_nr) { $quote_nr = $id ; }
		
		# 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>~ ;	
		$delete_butt = qq~<a class="btn btn-danger btn-xs" href="javascript:deleteMinItem('$quote_nr','$id')"><i class="glyphicon glyphicon-trash icon-white"></i></a>~ ;
		$copy_butt   = qq~<a class="btn btn-success btn-xs" href="javascript:copyMinItem('$id');" title="Copy" data-toggle="tooltip" data-placement="top"><i class="glyphicon glyphicon-retweet icon-white"></i></a>~;
		$pdf_butt    = qq~<a class="btn btn-primary btn-xs" href="javascript:dlgMdl('$useropts{scripts}/pdf/event_quote_pdf.pl?$id&$tabcnt{$db{$tables}{$id}{activetab}}&$tabsec{$db{$tables}{$id}{activetab}}','EVENT QUOTE $quote_nr','','waybill-dialog');"><i class="glyphicon glyphicon-print"></i></a>~;
			
		$print_tbody .= qq~<td nowrap class="dt-center">&nbsp;$edit_butt&nbsp;$copy_butt&nbsp;$delete_butt&nbsp;$pdf_butt</td></tr>~ ;
		# if ($i{export_to_excel}) {  
		# $xlsxrow++ ; 
		# }
	}
		
	# if ($i{export_to_excel}) { 
	&report_xlsx_export_footer('L',15,'events') ; 
	# }
		
	# $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><br><br>~ ;
		
	&common_min_extra_crumb("search-$lcpage\s","Search Screen") ;

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

sub get_province_name {
	
	my ($val) = @_ ; 
	
	if ($val eq 'Johannesburg'){	
		$val .= ", GP" ; 
	} elsif ($val eq 'Port Elizabeth') {
		$val .= ", EC" ; 
	} elsif ($val eq 'Kloof') {
		$val .= ", KZN" ; 
	} elsif ($val eq 'Durban') {
		$val .= ", KZN" ; 
	} elsif ($val eq 'Pietermatitzburg') {
		$val .= ", KZN" ; 
	} elsif ($val eq 'Pretoria') {
		$val .= ", GP" ; 
	} elsif ($val eq 'Polokwane') {
		$val .= ", LP" ; 
	} elsif ($val eq 'Kimberly') {
		$val .= ", NC" ; 
	} elsif ($val eq 'Cape Town') {
		$val .= ", WC" ; 
	} elsif ($val eq 'George') {
		$val .= ", WC" ; 
	} elsif ($val eq 'Knysna') {
		$val .= ", WC" ; 
	} elsif ($val eq 'Bloemfontein') {
		$val .= ", FS" ; 
	} elsif ($val eq 'Nelspruit') {
		$val .= ", MP" ; 
	} elsif ($val eq 'East London') {
		$val .= ", EC" ; 
	} elsif ($val eq 'Potchefstroom') {
		$val .= ", NW" ; 
	} elsif ($val eq 'Mafikeng') {
		$val .= ", NW" ; 
	} elsif ($val eq 'Stellenbosch') {
		$val .= ", WC" ; 
	} elsif ($val eq 'Gqeberha') {
		$val .= ", EC" ; 
	} elsif ($val eq 'Mbombela') {
		$val .= ", MP" ; 
	} elsif ($val eq 'Vereeniging') {
		$val .= ", GP" ; 
	} elsif ($val eq 'Soweto') {
		$val .= ", GP" ; 
	} elsif ($val eq 'Mossel Bay') {
		$val .= ", WC" ; 
	} elsif ($val eq 'Soshanguve') {
		$val .= ", GP" ; 
	} elsif ($val eq 'Upington') {
		$val .= ", NC" ; 
	} elsif ($val eq 'Makhanda') {
		$val .= ", EC" ; 
	} elsif ($val eq 'Grahamstown') {
		$val .= ", EC" ; 
	} elsif ($val eq 'Rustenburg') {
		$val .= ", NW" ; 
	} elsif ($val eq 'Benoni') {
		$val .= ", GP" ; 
	}  else {
		$val .= "" ; 
	}
	
	return $val ; 
	
}

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-ok"></i></span>~ ;

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

sub load_list_vars {
	
	my ($where) = @_ ;
	our %event_types = () ; 
	&db_min_ro('event_types','id,name','','','') ;
	foreach my $id (keys %{$db{event_types}}) { $event_types{$id} = $db{event_types}{$id}{name} ; }
	&db_min_ro('customers','id,name','','','') ;
	foreach my $id (keys %{$db{customers}}) { $customer{$id} = $db{customers}{$id}{name} ; } 	
	&db_min_ro($tables,'*',$where,'','') ;

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

sub thead {

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

sub page_opts {

	our $glyphicon = 'list' ;
	our $lcpage    = 'event-quote' ;

	&common_page_name ;
	   
	our $tables     = 'event_quotes' ;
	$page_title    = 'Event Quotes' ;

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

sub report_screen {

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

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

	&common_min_select_opts('client_id','customers','name','','') ;

	my @datefrom = &common_add_delta_ymd(-2,0,0) ;

	$print_box_content_rows  .= &common_min_form_datepicker('date_from',"$datefrom[0]-01-01") ;  
	$print_box_content_rows  .= &common_min_form_datepicker('date_to',"$now_year-$now_mm-$now_dd") ; 

	$opts{options} = qq~
		<option value=""></option>
		<option value="all">All</option>
		<option value="pending">Pending</option>
		<option value="accepted">Accepted</option>
		<option value="cancelled">Cancelled</option>
	~ ; 
	$print_box_content_rows  .= &common_min_form_select('options','','',1,'') ; 

	$print_box_content_rows  .= &common_min_form_select('client_id','') ; 
	# $print_box_content_rows  .= &common_min_form_select('options','') ; 
	$print_box_content_rows  .= &common_min_forms_end('','','report') ;

	&common_min_search_screen ;

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

sub common_camera_links_events {
	
	my ($table,$id,$val) = @_ ;

	if ($_ eq 'camera_nr') { 
		my $class = 'info' ; $class = 'warning' if $db{$table}{$id}{quote_nr} ;
		my $style = '' ; $style = "style='background-color:purple;'" if $db{$table}{$id}{demo_recipient} ;
		$val   = qq~<a class="btn btn-$class btn-xs" href="javascript:editMinItem('$id','cameras');" style="padding: 0px 3px 0px 3px;font-size:12px">$val</a>~ ;
	}
	
	if ($_ eq 'quote_nr' or $_ eq 'ref_nr' or $_ eq 'ref') { 
		my $class = 'info' ; $class = 'warning' if $val ;
		my $style = '' ;     $style = "style='background-color:purple;'" if $db{$table}{$id}{demo_recipient} ; $class = 'success' if $db{$table}{$id}{quote_accepted} or $quote_accepted{$id} ; $class = 'danger' if $db{$table}{$id}{quote_cancelled} or $quote_cancelled{$id}  ;
		my $quote_id = $quote_id{$val} ? $quote_id{$val} : $id ;
		$val = $val ? qq~<a class="btn btn-$class btn-xs" href="javascript:editEventQuote('$quote_id');" style="padding: 0px 3px 0px 3px;font-size:12px">$val</a>~ : '' ; 
	}
	
	return ($val) ;

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

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

1;