#!/usr/bin/perl

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

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

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{camera_system_id}) {
    push @report_sql, "(`camera_system_id`='$i{camera_system_id}')" ;
    push @report_results, "camera_system = $camera_system{$i{camera_system_id}}" ;
	# our $acc_id_sql_where = "`camera_id`='$i{camera_id}'"
}

# push @report_sql, "(`camera_system_id`='12')" ;
# push @report_results, "camera_system = $camera_system{12}" ;
	
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{stock}) {    
	# push @report_results, "Stock = $i{stock}" ;
    # }
	
if ($i{type}) {    
	push @report_results, "Type = $i{type}" ;
	}

push @report_sql, "(`quote_accepted`=1)" ;	
push @report_results, "Quote Accepted = '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 {

	# my $camera_systems_sql_where = "`id`='$i{camera_system_id}'" if $i{camera_system_id} ;
	# &db_min_ro('camera_systems','id,name',$camera_systems_sql_where,'','') ;
	if ($i{camera_system_id}) {
		&db_min_ro('camera_systems','id,name',"id='$i{camera_system_id}'",'','') ;
		foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } 
	}

	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 = '' ;
    
# our @sql_col_display = ("id","camera_nr","camera_serial_nr","date_received","amount_usd","amount_zar","in_stock") ;
# our @sql_col_display = ("camera_nr","camera_system_id","camera_serial_nr","date_received","amount_usd","amount_zar","in_stock") ;
our @sql_col_display = ("invoice_date","invoice_nr","client_id","ref","type","qty","roe","amount_usd","amount_zar","total") ;

&report_xls_export_header("Match_Credits_Report$xlsreportname",'matchcreditsreport') ;

&load_list_vars("$srch_where_sql$add_sql_where") ;

my @prefexes = ("item", "usd_amnt", "curr_amnt") ;

foreach my $prefex (@prefexes){
	
	$col_name = "$prefex" . "_costing_match_credits" ;
	$cnt = 0 ; 
	if($db{quotes_min}{$id}{$col_name}){
		foreach my $col_input (split(";", $db{quotes_min}{$id}{$col_name})){
			$cnt++ ; 
			$saved_field{$prefex}{$suffix}{$cnt} = $col_input ;  
			# &common_debug("$aa/$suffix : $cc") ; 
		}	
	}	
}

foreach my $id (sort {$b <=> $a} keys %{$db{$table}}) {
	
	# next unless $db{$table}{$id}{quote_accepted} ;
	# next unless $db{$table}{$id}{invoice_nr} ;
	
	if ($i{type}) {
		
		# my $sql_match_credits = '' ;	
		# if ($cnt_match_credits) { # match_credits_report.pl
			# for (1 .. $cnt_match_credits) {
				# $sql_match_credits .= qq~,$t2.item_$_\_costing_match_credits~ ;
			# }
		# }
		
		# &common_debug("type=$i{type} -> next unless $quote_camera_system_id{$id} eq $i{type}  ;") ;
		
		my $quote_match_credit_found = 0 ;
		for (1 .. $cnt_match_credits) {
			# my $type = $db{$table}{$id}{"item_$_\_costing_match_credits"} ;
			my $type = $saved_field{"item"}{"_costing_match_credits"}{$_} ;
			$quote_match_credit_found = 1 if $type eq $i{type} ;
		}
		next unless $quote_match_credit_found  ;
	}
	
	my $quote_match_credit = '' ;
	for (1 .. $cnt_match_credits) {
		# my $type = $db{$table}{$id}{"item_$_\_costing_match_credits"} ;
		my $type = $saved_field{"item"}{"_costing_match_credits"}{$_} ;
		$quote_match_credit .= $price_list{$type} . " " if $type ;
	}
	
	my $usd_match_credit = '' ; my $zar_match_credit = '' ;
	for (1 .. $cnt_match_credits) {
		# my $usd = $db{$table}{$id}{"usd_amnt_$_\_costing_match_credits"} ;
		my $usd = $saved_field{"usd_amnt"}{"_costing_match_credits"}{$_} ;
		$usd_match_credit += $usd if $usd ;
		# my $zar = $db{$table}{$id}{"curr_amnt_$_\_costing_match_credits"} ;
		my $zar = $saved_field{"curr_amnt"}{"_costing_match_credits"}{$_} ;
		$zar_match_credit += $zar if $zar ;
	}
	
	# if ($i{client_id}) { next unless $client{$i{client_id}} eq $quote_customer{$id} ; }
	# if ($i{client_id}) { next unless $db{$table}{$id}{client_id} eq $i{client_id} ; }
	# if ($i{stock})     { next unless $i{stock} eq lc $quote_type{$id} ; }
	
	$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 'date_received')    { $align = $center ;  }  
		# if ($_ eq 'amount_zar')       { $val   = $db{$table}{$id}{cur_amount}                                           ; }
		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 'amount_usd')       { $val   = $db{$table}{$id}{usd_amount}                                           ; }
		# if ($_ eq 'quote_total_zar')  { $val   = $quote_amount{$id}                                                     ; }
		if ($_ eq 'total')              { $val   = &common_commify(sprintf("%0.2f",($db{$table}{$id}{total_1_purchase_summary} + $db{$table}{$id}{total_2_purchase_summary} +  $db{$table}{$id}{total_3_purchase_summary}))) ; $align = $right ; }
		# if ($_ eq 'camera_serial_nr') { $val   = $db{$table}{$id}{serial_nr}                                            ; }
		# if ($_ eq 'camera_system_id') { $val   = $camera_system{$val}                                                   ; }
		# if ($_ eq 'invoice_date')     { $val   = $invoice_date{$id}                                                     ; }
		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_type{$id}                                                       ; }
		# if ($_ eq 'type')               { $val   = ucfirst $db{$table}{$id}{type}                                       ; }
		if ($_ eq 'type')               { $val   = $quote_match_credit                                                    ; }
		# if ($_ eq 'qty')              { $val   = $quote_qty{$id}                                                        ; }
		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   = $quote_customer{$id}                                                   ; }
		if ($_ eq 'client_id')          { $val   = $customer{$db{$table}{$id}{quote_to}}                                  ; }
		# if ($_ eq 'in_stock')         { if ($db{$table}{$id}{quote_nr}) { $val = 0 ; } else { $val = 1 ; } }
		# if ($_ eq 'in_stock')         { if ($db{$table}{$id}{quote_nr} or $db{$table}{$id}{demo_recipient} or $db{$table}{$id}{replacement_date}) { $val = 0 ; } else { $val = 1 ; } }
		
        &report_xls_export_process_cell('','',$val) ; # ------------------------------------------------------------------------- HTML AFTER
        $xlscol++; 
		
		$val = &common_camera_links($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($table,$id,$val) if $_ eq 'ref' ;
		
		$print_tbody .= qq~<td $align>$val</td>~ ;  
        }
		
	$print_tbody .= qq~</tr>~ ;
    $xlsrow++ ;
	}
	
&report_xls_export_footer('L',15,'matchcreditsreport') ;

$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 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) = @_ ;
	
# &db_min_ro('camera_systems','id,name','','','') ;
# foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } 
	
&db_min_ro('customers','id,name','','','') ;
foreach my $id (keys %{$db{customers}}) { $customer{$id} = $db{customers}{$id}{name} ; } 

&db_min_ro('price_list','id,description',"type='match_credits'",'','') ;
foreach my $id (keys %{$db{price_list}}) { $price_list{$id} = $db{price_list}{$id}{description} ; } 

# &common_load_quote_vars('>0');
# &common_load_quote_vars("cameras.quote_nr>0 AND cameras.quote_nr=quotes.quote_nr");
	
&db_min_ro($table,'*',$where,'','') ;

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

sub thead {

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

sub page_opts {

our $glyphicon = 'list' ;
our $lcpage    = 'match-credits' ;

&common_page_name ;
   
# our $table     = 'cameras' ;
our $table     = 'quotes' ;
$page_title    = 'Match Credits' ;

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

sub report_screen {

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

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

# &common_camera_opts ;

# &common_min_select_opts('camera_system_id','price_list','description','','') ;
&common_min_select_opts('client_id','customers','name','','') ;
&common_min_select_opts('type','price_list','description','','','',"`type`='match_credits'",'') ;

# &common_camera_opts ;

&common_min_select_opts('camera_system_id','camera_systems','code','12','','',"id='12'") ; # LIGR only

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") ; 
$print_box_content_rows  .= &common_min_form_select('camera_system_id','') ; 
# $opts{stock}              = qq~<option value=""></option>
# <option value="stock">In Stock</option>
# <option value="purchased">Purchased</option>
# <option value="rental">Rental</option>
# <option value="demo">Demo</option>~ ; 
# $print_box_content_rows  .= &common_min_form_select('stock','','',1,'') ; 
$print_box_content_rows  .= &common_min_form_select('client_id','') ; 
$print_box_content_rows  .= &common_min_form_select('type','') ; 
$print_box_content_rows  .= &common_min_forms_end('','','report') ;

&common_min_search_screen ;

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

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

1;