<?php

function fi_subcontractor_credit_notes($batch_no, $cutoff_date_, $timeout_at, $batch_size=1){
    global $systypes_array;
    $cutoff_date = date2sql($cutoff_date_);
    $trans_type = ST_SUBCONTRACTOR_CREDIT_NOTE;
    
    $purchase_account = get_company_pref('subcontract_exp_act');
    if(!(strlen($purchase_account) > 2)){
            $message = "Default subcontractor expenses account not found";
            write_fi_log($batch_no, $message);
            return array("success"=>false, "message"=>$message);
    }
    
    $payable_account = get_company_pref('creditors_act');
    if(!(strlen($payable_account) > 2)){
            $message = "Default payable account not found";
            write_fi_log($batch_no, $message);
            return array("success"=>false, "message"=>$message);
    }
    
    $result_h = get_fi_subcontractor_credit_notes($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'];
        $supplier_id = $h['supplier_id'];
        $project_id = $h['project_id'];
        
        
        $cgfit_msg = can_generate_fi_transaction($tran_type, $trans_no, $tran_date);
        if($cgfit_msg['success'] !== true){ 
            return $cgfit_msg;
        }
        
        $currency_code = $h["curr_code"];
        if(get_company_pref('curr_default') == $currency_code){
            $currency_code = null;
        }
        
        $purchase_account = $h["purchase_account"];
        if(!(strlen($purchase_account) > 2)){
            $purchase_account = get_company_pref('subcontract_exp_act');
        }
        
        $payable_account = $h["payable_account"];
        if(!(strlen($payable_account) > 2)){
            $payable_account = get_company_pref('creditors_act');
        }
    
//        if(!($h['total'] > 0)){
//            $message = $systypes_array[$trans_type]." #$trans_no - Total is negative.";
//            write_fi_log($batch_no, $message);
//            continue;
//        }
        
        begin_global_transaction();
        
        
        
        // Taxes
        $taxes_result = get_fi_subcontractor_credit_note_taxes($trans_no);    
        $taxes_total = add_fi_subcontractor_credit_note_taxes($batch_no, $trans_type, $supplier_id, $tran_date_, $taxes_result, $currency_code, $project_id);        
        
        // Customer receivable
        $credit_note_total = $h['total'] + $h['taxes'];
        
        if($h['rate_include_taxes']){
            $tax_factor = ($credit_note_total - $taxes_total) / $credit_note_total;
        }else{
            $tax_factor = 1;
        }
        
        $supplier_payable = add_fi_trans_supplier($batch_no, $trans_type, $trans_no, 0, $tran_date_, $payable_account, $project_id, 0, 
                                                    $credit_note_total, $supplier_id, $currency_code);
        
        $expenses_total = add_fi_trans_supplier($batch_no, $trans_type, $trans_no, 0, $tran_date_, $purchase_account, $project_id, 0, 
                                                -$h['total'], $supplier_id, $currency_code);
        
        $balance = $supplier_payable + $taxes_total + $expenses_total;
        if($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_, -$balance, $currency_code, PT_SUPPLIER, $supplier_id, $m);
        }
        
        //=======================================================
        // 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
        //=======================================================
        
        
        /*
        // Costs
        $costs_total = 0;
        $error =0;
        
        $result_d = get_fi_subcontractor_credit_note_details($trans_no);
        while($d = db_fetch($result_d)){
            $detail_line_id = $d['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'] == '0';
            }
            
            $amount = $d['amount'] * $tax_factor;
            
            if($amount > 0){
                if(strlen($detail_debit_account) > 1){
                    $costs_total += add_fi_trans_supplier($batch_no, $trans_type, $trans_no, $detail_line_id, $tran_date_, $detail_debit_account, 0, 0, 
                                                            -$amount, $supplier_id, $currency_code);
                }

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

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


        if(abs($costs_total) > 0.00001){
            $m = "Non zero detail section balance - ".$systypes_array[$trans_type]." #".$trans_no;
            add_fi_balance($batch_no, $trans_type, $trans_no, $tran_date_, -$costs_total, $currency_code, PT_SUPPLIER, $supplier_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]." - Could not process #$trans_no.";
            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_subcontractor_credit_note_taxes($batch_no, $trans_type, $supplier_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_supplier($batch_no, $trans_type, $taxitem['trans_no'], $taxitem['id'], $date_, $taxitem['purchasing_gl_code'], $project_id, 0, 
                                            -$taxitem['amount'], $supplier_id, $currency_code);
            if($taxitem['suspended'] == 1){
                $total += add_fi_trans_supplier($batch_no, $trans_type, $taxitem['trans_no'], $taxitem['id'], $date_, $taxitem['sales_gl_code'], $project_id, 0, 
                                            ($taxitem['amount']), $supplier_id, $currency_code);
            }
        }
    }
    return $total;
}

?>