<?php

function fi_utility_bill_credit_notes($batch_no, $cutoff_date_, $timeout_at, $batch_size=1){
    global $systypes_array;
    $cutoff_date = date2sql($cutoff_date_);
    $trans_type = ST_UTILITY_BILL_CREDIT_NOTE;
    
    $currency_code = get_company_pref('curr_default');
    
    $purchase_account = get_company_pref('default_cogs_act');
    if(!(strlen($purchase_account) > 2)){
                $message = "Default COGS account not found";
                write_fi_log($batch_no, $message);
                return array("success"=>false, "message"=>$message);
    }
    
    $default_exp_debit_act = get_company_pref('default_ub_exp_debit_act');
    if(!(strlen($default_exp_debit_act) > 2)){
                $message = "Default utility bill expense debit account not found";
                write_fi_log($batch_no, $message);
                return array("success"=>false, "message"=>$message);
    }
    
    $default_exp_credit_act = get_company_pref('default_ub_exp_credit_act');
    if(!(strlen($default_exp_credit_act) > 2)){
                $message = "Default utility bill expense credit account not found";
                write_fi_log($batch_no, $message);
                return array("success"=>false, "message"=>$message);
    }
    
    $result_h = get_fi_utility_bill_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());
        }
        
        $supplier_payable = $taxes_total = $expenses_total = 0;
        
        $tran_date = $h['tran_date'];
        $tran_date_ = sql2date($tran_date);
        $trans_no = $h['trans_no'];
        $project_type_id = $h['project_type_id'];
        $project_id = $h['project_id'];
        $supplier_id = $h['supplier_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;
        }
        
        $cost_account = $h["cost_account"];
        if(!(strlen($cost_account) > 1)){
            $cost_account = get_company_pref('default_proj_cost_act');
        }
        
//        if(strlen($cost_account) > 0){
//            if($cost_account == '-1' || $cost_account == '0'){
//                $message = $systypes_array[$trans_type]." #$trans_no - Invalid Cost Account";
//                write_fi_log($batch_no, $message);
//                continue;
//            }
//        }else{
//            $message = $systypes_array[$trans_type]." #$trans_no - Invalid Cost Account";
//            write_fi_log($batch_no, $message);
//            continue;
//        }
        
        $purchase_account = $h["purchase_account"];
        if(!(strlen($purchase_account) > 2)){
            $purchase_account = get_company_pref('default_cogs_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();
        
        $result_d = get_fi_utility_bill_credit_note_details($trans_no);
        if(!(db_num_rows($result_d) > 0)){
            write_fi_log($batch_no, $systypes_array[$trans_type]." #$trans_no - No Details found.");
            $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;
            }else{
                commit_transaction();
                continue;
            }
        }

                
        // Taxes
        $taxes_result = get_fi_utility_bill_credit_note_taxes($trans_no);    
        $taxes_total = add_fi_utility_bill_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, 0,
                                                  $currency_code);

        $detail_costs_total = 0;
        $error = 0;
        
        while($d = db_fetch($result_d)){
            $detail_line_id = $d['detail_line_id'];

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

            $expense_account = $coc_account = "";
            
            if(strlen($d['debit_account']) > 2){
                $expense_account = $d['debit_account'];              
            }            
            
            if(strlen($d['coc_account']) > 2){
                $coc_account =$d['coc_account'];
            }
            
            set_fi_applicable_expense_account($project_type_id, $expense_account, $coc_account);
                    
            $amount = $d['amount'] * $tax_factor;
//            if($amount > 0){
            if($expense_account > 2){
                    $detail_costs_total += add_fi_trans_supplier($batch_no, $trans_type, $trans_no, $detail_line_id, $tran_date_, $expense_account, $project_id, 0, -$amount, $supplier_id, 
                                                          $currency_code);                
            }
//            else{
//                $abs_amount = abs($amount);
//                    $costs_total += add_fi_trans_supplier($batch_no, $trans_type, $trans_no, $detail_line_id, $tran_date_, $exp_debit_act, 0, 0, $abs_amount, $supplier_id, 
//                                                          $currency_code);
//            }
        }
        
        if($error > 0){ // if fails inner loop then continue with outer loop
            cancel_transaction();
            continue;
        }

        $expenses_total = 0;
        $header_and_lines_difference = $h['total'] + $detail_costs_total;
        if(($header_and_lines_difference) != 0){ 
            // total tax free amount is covered by the debit accounts of the line Expense Types
            $mhd = "Header and lines total difference";
            $fi_balances_account = get_company_pref('fi_balances_act');
            $expenses_total = add_fi_trans_supplier($batch_no, $trans_type, $trans_no, 0, $tran_date_, $fi_balances_account, $project_id, 0, -$header_and_lines_difference, $supplier_id, 0, $currency_code, $mhd);
        }
        
        $balance = $supplier_payable + $taxes_total + $detail_costs_total + $expenses_total;
        if($balance != 0){
            $m = "Non zero 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);
        }
        
        $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_utility_bill_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_customer($batch_no, $trans_type, $taxitem['trans_no'], $taxitem['id'], $date_, $taxitem['sales_gl_code'], 0, 0, 
//                                            $taxitem['amount'], $supplier_id, 0,$currency_code);
            $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;
}

?>