<?php

function fi_project_invoices($batch_no, $cutoff_date_, $timeout_at, $batch_size=1){
    global $systypes_array;
    $cutoff_date = date2sql($cutoff_date_);
    $trans_type = ST_PROJECT_INVOICE;
    
    $result_h = get_fi_project_invoices($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'];
            $project_id = $h['project_id'];

            $currency_code = $h["curr_code"];
            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

            
            if(strlen($h["receivables_account"]) > 2){ // Customer receivable account
                    $receivable_account = $h["receivables_account"]; 
            }else{ // Company default receivable account
                    $receivable_account = get_company_pref('debtors_act');
            } 
            
            if(strlen($h["project_sales_account"]) > 2){ // Customer project sales account
                    $sales_account = $h["project_sales_account"]; 
            }elseif(strlen($h["revenue_account"]) > 2){ // Project master project revenue account
                    $sales_account = $h["revenue_account"]; //
            }else{ // Company default project revenue account
                    $sales_account = get_company_pref('default_proj_revenue_act');
            } 
        
            begin_global_transaction();
        
            // Taxes
            $taxes_result = get_fi_project_invoice_taxes($trans_no);    
            $taxes_total = add_fi_project_invoice_taxes($batch_no, $trans_type, $customer_id, $tran_date_, $taxes_result, $currency_code, $project_id);        

            // Customer receivable
            $invoice_total = $h['total'] + $h['taxes'];

            if($h['rate_include_taxes']){
                    $tax_factor = ($invoice_total - $taxes_total) / $invoice_total;
            }else{
                    $tax_factor = 1;
            }

            $customer_receivable = add_fi_trans_customer($batch_no, $trans_type, $trans_no, 0, $tran_date_, $receivable_account, $project_id, 0, 
                                                        $invoice_total, $customer_id, $currency_code, $rate);

            $project_revenue = add_fi_trans_customer($batch_no, $trans_type, $trans_no, 0, $tran_date_, $sales_account, $project_id, 0, 
                                                        -$h['total'], $customer_id, $currency_code, $rate);

            $inv_balance = $customer_receivable + $taxes_total + $project_revenue;
            if($inv_balance != 0){
                $m = "Non zero header section 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;
        
            //=======================================================
            // In order to avoid non-zero balances postings due to differences in header and lines total, it was decided to post advances and retentions manually
            //=======================================================
            
            /*
            $result_d = get_fi_project_invoice_details($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, $project_id, 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, $project_id, 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);
            }
             * 
             */

            $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_project_invoice_taxes($batch_no, $trans_type, $customer_id, $date_, $ub_taxes_result, $currency_code, $project_id){
    $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'], $project_id, 0, 
                                            (-$taxitem['amount']), $customer_id, $currency_code);
            if($taxitem['suspended'] == 1){
                $total += add_fi_trans_customer($batch_no, $trans_type, $taxitem['trans_no'], $taxitem['id'], $date_, $taxitem['purchasing_gl_code'], $project_id, 0, 
                                            ($taxitem['amount']), $customer_id, $currency_code);
            }
        }
    }
    
    return $total;
}

?>