#!/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 ;
		
} #------------------------------------------------------------------------------------------

sub quote_list {

	our @sql_col_display = ("nr","customer","event","location","city","quote_total","car_hire","flights","accommodation","meal_allowance","travel_expenses","other","operator_total","total_expenses","profit/Loss","invoice_nr","sports_type","date_from","date_to") ;
	# our @col_display_excel = ("event", "date", "day", "sport_type", "production_type", "ligr_integration", "location","city_&_province", "onsite_team") ; 
	@col_display_excel = @sql_col_display  ; 

	&report_xlsx_export_header_events("Cosings_Detailed",'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,10);
	$worksheet{$ws} -> set_column(1,1,30);
	$worksheet{$ws} -> set_column(2,3,40);
	$worksheet{$ws} -> set_column(4,14,15);
	$worksheet{$ws} -> set_column(15,15,10);
	
	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} ;
		our $nowrap = '' ;
		foreach (@sql_col_display) { 
			unless ($_) { next ; } # blank for the buttons column
			$nowrap = '' ;
			my $val = &get_val($id, $_) ;
			my $align = qq~ class="dt-center"~ ; 
			$print_tbody .= qq~<td $nowrap $align>$val</td>~ ;  	
## EXCEL----------------------------
			if ($_ eq 'nr'){ $val = $id ; }
			if ($_ eq 'sports_type'){ $val =~ s/\<br>/\;/g ; }
			
			if ($_ eq 'nr' or $_ eq 'customer' or $_ eq 'event' or $_ eq 'location' or $_ eq 'city' or $_ eq 'invoice_nr') {
				&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format_event_data) 
			} else {
				&xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format_management_report_data) 
			}
			
			# &report_write_events($val, 0) ;	
			$xlsxcol++; 		
		}
		$print_tbody .= qq~</tr>~ ;		
		$xlsxrow++; 	
	}
# EXCEL---------------------------------------------
	# 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_val {
	# our @sql_col_display = ("nr","customer","event","location","city","quote_total","car_hire","flights","accommodation","meal_allowance", "travel_expenses", "other", "operator_total", "total_expenses", "profit/Loss", "invoice_nr") ;
	
	my ($id, $col) = @_ ; 
	my $val = $db{$tables}{$id}{$_} ;
	# print "$col, $val \n" ; 
	if ($col eq 'event') { 
		$val   = $db{$tables}{$id}{ref} ;       
		# $nowrap = 'nowrap' ;    
	} elsif ($col eq 'location') {
		$val = ($db{$tables}{$id}{region_id}) ? "$db{regions}{$db{$tables}{$id}{region_id}}{name} [$db{regions}{$db{$tables}{$id}{region_id}}{code}]" : "" ; 
	} elsif ($col eq 'city') {
		$val   = ($db{$tables}{$id}{city_id}) ? $db{cities}{$db{$tables}{$id}{city_id}}{city} : $db{$tables}{$id}{city} ;
	} elsif ($col eq 'sports_type') {
		$val = join("<br>", map { $db{sport_types}{$_}{name} } split(",", $db{$tables}{$id}{sport_type_ids}));
	} elsif ($col eq 'customer') { 
		$val   = $customer{$db{$tables}{$id}{quote_to}} ;  
		$nowrap = 'nowrap' ;    	
	} elsif ($col eq 'location') { 
		# $val = "Unknown" unless $val ;  	
	}  elsif ($col eq 'city'){ 
		$val   = $db{$tables}{$id}{city} ;  			
	} elsif ($col eq 'ligr'){ 
		$val   = $db{$tables}{$id}{ligr} ;  			
	} elsif ($col eq 'quote_total'){
		$val = $db{$tables}{$id}{grand_total} ; 
		# $val = 100000000 ; 
		$val = 0 if not $val ; 
		# my $ttl = &common_commify($val) ;
		$val = sprintf("%.2f", $val) ; 
	} elsif ($col eq 'total_expenses'){
		$val = $db{$tables}{$id}{total_grand_amount_workings_event} ; 
		# $val = 100000000 ; 
		$val = 0 if not $val ; 
		# my $ttl = &common_commify($val) ;
		$val = sprintf("%.2f", $val) ; 
	} elsif ($col eq 'profit/Loss'){
		$val = $db{$tables}{$id}{grand_total} - $db{$tables}{$id}{total_grand_amount_workings_event} ; 
		# $val = 100000000 ; 
		$val = 0 if not $val ; 
		# my $ttl = &common_commify($val) ;
		$val = sprintf("%.2f", $val) ; 
	} elsif ($col eq 'car_hire') {
		$val = $total_car_hire{$id} ; 
		$val = 0 if not $val ; 
		# $val = &common_commify($val) ;
		$val = sprintf("%.2f", $val) ; 
	} elsif ($col eq 'flights') {
		$val = $total_flights{$id} ; 
		$val = 0 if not $val ; 
		# $val = &common_commify($val) ;
		$val = sprintf("%.2f", $val) ; 
	} elsif ($col eq 'accommodation') {
		$val = $total_accomodation{$id} ; 
		$val = 0 if not $val ; 
		# $val = &common_commify($val) ;
		$val = sprintf("%.2f", $val) ; 
	} elsif ($col eq 'meal_allowance') {
		$val = $total_meal_allowance{$id} ; 
		$val = 0 if not $val ; 
		# $val = &common_commify($val) ;
		$val = sprintf("%.2f", $val) ; 
	} elsif ($col eq 'travel_expenses') {
		$val = $total_travel_expenses{$id} ; 
		$val = 0 if not $val ; 
		# $val = &common_commify($val) ;
		$val = sprintf("%.2f", $val) ; 
	} elsif ($col eq 'other') {
		$val = $total_other{$id} ; 
		$val = 0 if not $val ; 
		# $val = &common_commify($val) ;
		$val = sprintf("%.2f", $val) ; 
	} elsif ($col eq 'operator_total') {
		$val = $total_operator{$id} ; 
		$val = 0 if not $val ; 
		# $val = &common_commify($val) ;
		$val = sprintf("%.2f", $val) ; 
	} elsif ($col eq 'total') {
		$val = &common_commify($db{$tables}{$id}{grand_total}) ;
	} elsif ($col eq 'date_to' or $col eq 'date_from') {
		$nowrap = 'nowrap' ;    
		$val = substr($val, 0, 10) ;
	} elsif ($col 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');">$id</a>~ ; 
	}	
	return ($val) ; 
}

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} ; } 	
	
	our %total_accomodation = () ; 
	our %total_car_hire = () ;
	our %total_flights  = () ;
	our %total_meal_allowance  = () ;
	our %total_travel_expenses = () ;
	our %total_other  = () ;
	our %total_operator   = () ;
	
	db_min_ro('event_quotes_min','id, description_workings_event, amount_workings_event','','','') ;

	foreach my $iid (keys %{$db{event_quotes_min}}) {
		
		@amnt_work = split(";", $db{event_quotes_min}{$iid}{amount_workings_event});
		@des_work  = split(";", $db{event_quotes_min}{$iid}{description_workings_event});
	
		for (1 .. 50) {
			if ($des_work[$_ - 1] == 1){
				$total_flights{$iid} += $amnt_work[$_ - 1] ;
			} elsif ($des_work[$_ - 1] == 2){
				$total_accomodation{$iid} += $amnt_work[$_ - 1] ;
			} elsif ($des_work[$_ - 1] == 3){
				$total_car_hire{$iid} += $amnt_work[$_ - 1] ;
			} elsif ($des_work[$_ - 1] == 4){
				$total_meal_allowance{$iid} += $amnt_work[$_ - 1] ;
			} elsif ($des_work[$_ - 1] == 6){
				$total_other{$iid} += $amnt_work[$_ - 1] ;
			} elsif ($des_work[$_ - 1] == 13){
				$total_travel_expenses{$iid} += $amnt_work[$_ - 1] ;
			} elsif ($des_work[$_ - 1] == 14){
				$total_operator{$iid} += $amnt_work[$_ - 1] ;
			}
		}	
	}	
	
	my $sql_select = "id,ref,quote_to,city,ligr,grand_total,total_grand_amount_workings_event,quote_cancelled,quote_accepted,quote_pending,location,invoice_nr,quote_expiry,quote_nr,sport_type_ids,date_from,date_to,city,city_id,region_id" ;
	# for (1 .. 15){ $sql_select .= ",description_$_\_workings_event" ; $sql_select .= ",amount_$_\_workings_event" ;  }
	
	&db_min_ro($tables,$sql_select,$where,'','') ;
	
	# foreach my $iid (keys %{$db{$tables}}) {
		# for (1 .. 15) {
			# if ($db{$tables}{$iid}{"description_$_\_workings_event"} == 1){
				# $total_flights{$iid} += $db{$tables}{$iid}{"amount_$_\_workings_event"} ;
			# } elsif ($db{$tables}{$iid}{"description_$_\_workings_event"} == 2){
				# $total_accomodation{$iid} += $db{$tables}{$iid}{"amount_$_\_workings_event"} ;
			# } elsif ($db{$tables}{$iid}{"description_$_\_workings_event"} == 3){
				# $total_car_hire{$iid} += $db{$tables}{$iid}{"amount_$_\_workings_event"}  ;
			# } elsif ($db{$tables}{$iid}{"description_$_\_workings_event"} == 4){
				# $total_meal_allowance{$iid} += $db{$tables}{$iid}{"amount_$_\_workings_event"} ;
			# } elsif ($db{$tables}{$iid}{"description_$_\_workings_event"} == 6){
				# $total_other{$iid} += $db{$tables}{$iid}{"amount_$_\_workings_event"};
			# } elsif ($db{$tables}{$iid}{"description_$_\_workings_event"} == 13){
				# $total_travel_expenses{$iid} += $db{$tables}{$iid}{"amount_$_\_workings_event"} ;
			# } elsif ($db{$tables}{$iid}{"description_$_\_workings_event"} eq '14'){
				# $total_operator{$iid} += $db{$tables}{$iid}{"amount_$_\_workings_event"} ;
			# }
		# }	
	# }	
	
	&db_min_ro('sport_types','id,name','','','') ;
	&db_min_ro('cities','id,city,province','','','') ;
	&db_min_ro('regions','id,code,name','','','') ; 
	
} #------------------------------------------------------------------------------------------

sub thead {

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

sub page_opts {

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

	&common_page_name ;
	   
	our $tables     = 'event_quotes' ;
	$page_title    = 'Costings Detailed' ;

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

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;