<?php

function fi_supplier_credit_notes($batch_no, $cutoff_date_, $timeout_at, $batch_size=1){
    global $systypes_array;
    $cutoff_date = date2sql($cutoff_date_);
    $trans_type = ST_SUPPCREDIT;

    
    $def_inventory_account = get_company_pref('default_inventory_act');
    if(!(strlen($def_inventory_account) > 2)){
            $message = $systypes_array[$trans_type]." - could not find default inventory account";
            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 = $systypes_array[$trans_type]." - Default payable account not found";
            write_fi_log($batch_no, $message);
            return array("success"=>false, "message"=>$message);
    }
    
    
    $result_h = get_fi_supplier_credit_notes($cutoff_date, $batch_size);
    while($h = db_fetch($result_h)){
//        $supplier_payable = $taxes_total = $project_cost = $expenses_total = 0;
        
        if($timeout_at < time()){
            return array("success"=>false, "message"=>get_fi_integration_timeout_message());
        }
        
        
            $tran_date = $h['tran_date'];
            $tran_date_ = sql2date($h['tran_date']);
            $trans_no = $h['trans_no'];
            $supplier_id = $h['supplier_id'];
            $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($tran_type, $trans_no, $tran_date);
            if($cgfit_msg['success'] !== true){ 
                return $cgfit_msg;
            }
        
//Inventry/expence	Debit 	100		COGS Account:
//VAT receivale 	Debit 	8		
//Supplier              Credit	108		Accounts payble Acc
        
        
            $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();

            // Taxes
            $taxes_result = get_fi_supplier_credit_note_taxes($trans_type, $trans_no);    
            $taxes_total = add_fi_supplier_credit_notes_taxes($batch_no, $trans_type, $supplier_id, $tran_date_, $taxes_result, $currency_code, $project_id);        

            // Supplier payable
            

            if($h['tax_included']){
                $cn_taxed_total = $h['ov_amount'];
                $cn_tax_free_total = $h['ov_amount'] - $taxes_total;
                
                $tax_factor = ($cn_tax_free_total ) / $cn_taxed_total;
            }else{
                $cn_taxed_total = $h['ov_amount'] + $taxes_total;
                $cn_tax_free_total = $h['ov_amount'];
                
                $tax_factor = 1;
            }
        
            $supplier_payable = add_fi_trans_supplier($batch_no, $trans_type, $trans_no, 0, $tran_date_, $payable_account, $project_id, 0, 
                                                        -$cn_taxed_total, $supplier_id, $currency_code);

//            $expenses_total = add_fi_trans_supplier($batch_no, $trans_type, $trans_no, 0, $tran_date_, $clearing_act, 0, 0, 
//                                                        $invoice_tax_free_total, $supplier_id, $currency_code);

        


            /*=================== gl_codes =============================*/

            $gl_codes_total = 0;
            $result_gl_codes = get_fi_supplier_credit_note_gl_codes($trans_type, $trans_no);
            while($gl_code = db_fetch($result_gl_codes)){
                    $detail_line_id = $gl_code['detail_line_id'];
                    
                    $gl_code_amount = $gl_code['unit_price'];
                    $gl_code_tax_amount = -$gl_code['unit_tax'];
                    $gl_account = $gl_code['gl_code'];
                    
                    $comment = "Line Id $detail_line_id : ".$gl_code['gl_code']." - Invoice added account";
                    //$total += add_gl_trans_supplier($trans_type, $trans_no, $tran_date_, $gl_code['gl_code'], 0, 0,
                    //        $gl_code['unit_price'], $supplier_id, "", 0, $memo_);
                    
                    $gl_codes_total += add_fi_trans_supplier($batch_no, $trans_type, $trans_no, $detail_line_id, $tran_date_, $gl_account, $project_id, 0, 
                                                    $gl_code_amount, $supplier_id, null, 0, $comment);   

                    
                    add_fi_tax_details($gl_account, $trans_type, $trans_no, $gl_code_tax_amount,
                                        0, $tran_date_, $h['reference'], $h['tax_included']);
                    
                    $taxes_total += $gl_code_tax_amount;
        
            }
            
            
            /*=================== items =============================*/
            
            $returned_items_total = 0;
            $result_items = get_fi_supplier_credit_note_items($trans_type, $trans_no);
            while($item = db_fetch($result_items)){
                    // Credit note supplier item (supplier prices)

                    $cn_tran_unit_conv_factor = 1;
                    if($item['inv_tran_unit_conv_factor'] > 0.0000001){
                        $cn_tran_unit_conv_factor = $item['inv_tran_unit_conv_factor'];
                    }
                    
                    if($item['inv_tran_unit_qty'] == 0){ // old transactions do not have uniut conversion
                        $cn_qty = $item['quantity'];
                        $cn_unit_price = $item['unit_price'];
                    }
                    else{
                        $cn_qty = $item['inv_tran_unit_qty'] * $cn_tran_unit_conv_factor;                        
                        $cn_unit_price = $item['inv_tran_unit_price'] / $cn_tran_unit_conv_factor;                        
                    }
                    
                    $cn_discounted_unit_price = ($cn_unit_price) * (1 - $item['inv_tran_unit_price_discount']/100);
                    
                    
                    $cn_unit_tax = $item['unit_tax'];
                    if($h['tax_included']){
                            $cn_discounted_tax_free_unit_price = $cn_discounted_unit_price - $cn_unit_tax;
                            $tax_factor = ($cn_discounted_tax_free_unit_price ) / $cn_discounted_unit_price;
                    }else{
                            $cn_discounted_tax_free_unit_price = $cn_discounted_unit_price;
                            $tax_factor = 1;
                    }

//                    $po_discounted_unit_price = ($item['order_unit_price']/$item['order_unit_conv_factor']) * (1 - $item['order_unit_price_discount']/100);                    
//                    $po_discounted_tax_free_unit_price = $po_discounted_unit_price * $tax_factor;


//                    $invoice_po_tax_free_total += $po_discounted_tax_free_unit_price * $invoice_qty;
                    
                    // Credit note stock item
//                    $grn_unit_cost = 0;
                    $returned_item_line_cost = $cn_discounted_tax_free_unit_price * $cn_qty;
                    
//                    $line_dif = ($invoice_discounted_tax_free_unit_price - $po_discounted_tax_free_unit_price) * $cn_qty;
//                    
//                    if(abs($line_dif) < 0.00001){
//                        continue;
//                    }

                    $detail_line_id = $item['detail_line_id'];
                    
                    if(strlen($item['inventory_account']) > 2){
                        $inventory_account = $item['inventory_account'];
                    }
                    else{
                        $inventory_account = $def_inventory_account;
                    }
//
//                    $comment = "Invoice price difference: Line Id $detail_line_id : ".$item['stock_id']." - ".$item['description'];

                    $comment= "";

                    $returned_items_total += add_fi_trans_supplier($batch_no, $trans_type, $trans_no, 0, $tran_date_, $inventory_account, $project_id, 0, 
                                                    $returned_item_line_cost, $supplier_id, null, 0, $comment);    
                    

            }
            
//            $grn_difference = $supplier_payable - $taxes_total - $returned_items_total;
//            $grn_diff_comment = "Line Id $detail_line_id : ".$d['stock_id']." - ".$d['description'];
//
//            if(abs($grn_difference) > 0.00001){
//                $total += add_fi_trans_supplier($batch_no, $trans_type, $trans_no, 0, $tran_date_, $inventory_account, 0, 0, 
//                                                $grn_difference, $supplier_id, null, 0, $grn_diff_comment);
//            }
//            
//            $invoice_po_expenses_total = add_fi_trans_supplier($batch_no, $trans_type, $trans_no, 0, $tran_date_, $purchase_account, 0, 0, 
//                                                        $invoice_po_tax_free_total, $supplier_id, $currency_code);

            $balance = ($returned_items_total + $gl_codes_total) + $taxes_total + $supplier_payable;
            if(abs($balance) > 0.00001){
                $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);
            }
            
//            if($line_dif_total != 0){
//                $comment = "Stock items invoice price defferences total";
//                add_fi_trans_supplier($batch_no, $trans_type, $trans_no, $detail_line_id, $tran_date_, $purchase_account, 0, 0, 
//                                            -$line_dif_total, $supplier_id, null, 0);
//            }


            $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_supplier_credit_notes_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;
}

?>