<?php

function fi_sales_invoice_returns($batch_no, $cutoff_date_, $timeout_at, $batch_size=1){
    global $systypes_array;
    $cutoff_date = date2sql($cutoff_date_);
    $trans_type = ST_CUSTOMER_PAYMENT_RETURN;
    
    $freight_account = get_company_pref("freight_act");
    if(!(strlen($freight_account) > 2)){ 
            $message = $systypes_array[$trans_type]." : freight account not found";
            write_fi_log($batch_no, $message);
            return array("success"=>false, "message"=>$message);
    }
            
    $result_h = get_fi_sales_invoice_returns($trans_type, $cutoff_date, $batch_size);
    while($h = db_fetch($result_h)){
            
        if($timeout_at < time()){
            return array("success"=>false, "message"=>get_fi_integration_timeout_message());
        }
        
            $tran_date = $h['tran_date'];
            $tran_date_ = sql2date($tran_date);
            $trans_no = $h['trans_no'];
            $customer_id = $h['debtor_no'];

            $currency_code = $h["curr_code"];
//            $ss = get_company_pref('curr_default');
            if(get_company_pref('curr_default') != $currency_code){
                    $currency_code = null;
            }
            
            $cgfit_msg = can_generate_fi_transaction($trans_type, $trans_no, $tran_date);
            if($cgfit_msg['success'] !== true){ 
                return $cgfit_msg;
            }
        
            $rate = 0;
        
//Income	Credit 	100		Sales Account:
//VAT payble	Credit 	8		
//Customer 	Debit	108		Accounts Receivable Acc

            
            $tax_included = $h["tax_included"];
            
            $sales_account = $h["sales_account"];
            if(!(strlen($sales_account) > 2)){ 
                    $sales_account = get_company_pref('default_inv_sales_act');
            }

            $receivable_account = $h["receivables_account"];
            if(!(strlen($receivable_account) > 2)){
                    $receivable_account = get_company_pref('debtors_act');
            } 
        
            $sales_discount_account = $h["sales_discount_account"];
            if(!(strlen($sales_discount_account) > 2)){
                    $sales_discount_account = get_company_pref('default_sales_discount_act');
            } 
        
            begin_global_transaction();
        
            // Taxes
            $taxes_result = get_fi_sales_invoice_return_taxes($trans_type, $trans_no);    
            $taxes_total = add_fi_sales_invoice_return_taxes($batch_no, $trans_type, $customer_id, $tran_date_, $taxes_result, $currency_code);        

            // Customer receivable
            $invoice_items_total = $h['ov_amount'];
            
            if($tax_included){
                $invoice_items_tax_free_total = $invoice_items_total + $taxes_total;
            }
            else{
                $invoice_items_tax_free_total = $invoice_items_total;
            }
            
            
            
            $invoice_tax_free_total = $h['ov_amount'];
            $invoice_tax_total = $h['ov_gst'];
            
            $freight_tax_free_amount = $h['ov_freight'];
            $freight_tax_amount = $h['ov_freight_tax'];
            
            $invoice_discount_total = $h['ov_discount'];
            
            $receivable_return_amount = $invoice_items_tax_free_total + ($taxes_total) + $freight_tax_free_amount + ($freight_tax_amount);
            $sales_return_amount = -$invoice_items_tax_free_total;


            if($receivable_return_amount == 0){
                continue;
            }

            if($receivable_return_amount != 0){
                $customer_receivable_return = add_fi_trans_customer($batch_no, $trans_type, $trans_no, 0, $tran_date_, $receivable_account, 0, 0, 
                                                        -$receivable_return_amount, $customer_id, $currency_code, $rate);
            }

            if($sales_return_amount != 0){
                $sales_revenue_return = add_fi_trans_customer($batch_no, $trans_type, $trans_no, 0, $tran_date_, $sales_account, 0, 0, 
                                                        -$sales_return_amount, $customer_id, $currency_code, $rate);
            }
            
//            if($invoice_discount_total != 0){
//                $invoice_discount = add_fi_trans_customer($batch_no, $trans_type, $trans_no, 0, $tran_date_, $sales_discount_account, 0, 0, 
//                                                        $invoice_discount_total, $customer_id, $currency_code, $rate);
//            }
            
            if ($freight_tax_free_amount != 0) {
                $freight_tax_free_amount = add_fi_trans_customer($batch_no, $trans_type, $trans_no, 0, $tran_date_, $freight_account, 0, 0, 
                                                        $freight_tax_free_amount, $customer_id, $currency_code, $rate);
            }

            $inv_balance = ($customer_receivable_return) + $sales_revenue_return + $freight_tax_free_amount + ($taxes_total + $freight_tax_amount);
            $inv_balance = round($inv_balance, 2);
            
            if($inv_balance != 0){
                $m = "Non zero balance - ".$systypes_array[$trans_type]." #".$trans_no;
                add_fi_balance($batch_no, $trans_type, $trans_no, $tran_date_, -$inv_balance, $currency_code, PT_CUSTOMER, $customer_id, $m);
            }
            
            
            
            /*
            // Costs
            $detail_costs_total = 0;
            $error = 0;
        
            $result_d = get_fi_sales_invoice_details($trans_type, $trans_no);
            while($d = db_fetch($result_d)){
                    $detail_line_id = $d['detail_line_id'];

                    if($d['amount'] == 0){
                            continue;
                    }

                    $detail_debit_account = $detail_credit_account = "";
                    if(strlen($d['debit_account']) > 2){
                            $detail_debit_account = $d['debit_account'];
                    }
            
                    if(strlen($d['credit_account']) > 2){
                            $detail_credit_account = $d['credit_account'];
                    }

                    $comment = "";

                    $amount = $d['amount'] * $tax_factor;
                    if($amount > 0){
                            if(strlen($detail_debit_account) > 1){
                                    $detail_costs_total += add_fi_trans_customer($batch_no, $trans_type, $trans_no, $detail_line_id, $tran_date_, $detail_debit_account, 0, 0, 
                                                                        $amount, $customer_id, $currency_code, $rate);
                            }

                            if(strlen($detail_credit_account) > 1){
                                    $detail_costs_total += add_fi_trans_customer($batch_no, $trans_type, $trans_no, $detail_line_id, $tran_date_, $detail_credit_account, 0, 0, 
                                                                        -$amount, $customer_id, $currency_code, $rate);
                            }

                    }else{
                
                            // Amount is a negative value. Change the accounts
                            $abs_amount = abs($amount);
                            if(strlen($detail_credit_account) > 1){
                                    $detail_costs_total += add_fi_trans_customer($batch_no, $trans_type, $trans_no, $detail_line_id, $tran_date_, $detail_credit_account, 0, 0, 
                                                                            $abs_amount, $customer_id, $currency_code, $rate);
                            }

                            if(strlen($detail_debit_account) > 1){
                                    $detail_costs_total += add_fi_trans_customer($batch_no, $trans_type, $trans_no, $detail_line_id, $tran_date_, $detail_debit_account, 0, 0, 
                                                                            -$abs_amount, $customer_id, $currency_code, $rate);
                            }
                    }
            }
        
            if($error > 0){ // if fails inner loop then continue with outer loop
                cancel_transaction();
                continue;
            }

            if($detail_costs_total != 0){
                $m = "Non zero detail section balance - ".$systypes_array[$trans_type]." #".$trans_no;
                add_fi_balance($batch_no, $trans_type, $trans_no, $tran_date_, -$detail_costs_total, $currency_code, PT_CUSTOMER, $customer_id, $m);
            }

            */
            
            $project_id = $h["project_id"];
            $gpae_msg = generate_project_costs_accounting_entries($trans_type, $trans_no, $project_id);
            if($gpae_msg['success'] !== true){
                cancel_transaction();
                $message = $systypes_array[$trans_type]." #".$trans_no." : ".$gpae_msg['message'];
                write_fi_log($batch_no, $message);
                continue;
            }
            
            $n = update_source_transaction_fi_batch_no($trans_type, $trans_no, $batch_no);
            if($n !== 1){
                cancel_transaction();
                $message = $systypes_array[$trans_type]." #".$trans_no." has been processed already";
                write_fi_log($batch_no, $message);
                continue;
            }
            
            add_fi_batch_transaction($batch_no, $trans_type, $trans_no, $tran_date);

            commit_transaction();
    }
    
    return array("success"=>true, "message"=>"");
    
}
    
function add_fi_sales_invoice_return_taxes($batch_no, $trans_type, $customer_id, $date_, $ub_taxes_result, $currency_code){
    $total = 0;
    while($taxitem = db_fetch($ub_taxes_result)){
        if($taxitem['amount'] != 0){
            $total += add_fi_trans_customer($batch_no, $trans_type, $taxitem['trans_no'], $taxitem['id'], $date_, $taxitem['sales_gl_code'], 0, 0, 
                                            ($taxitem['amount']), $customer_id, $currency_code);
        }
    }
    
    return $total;
}

?>