<?php
/**********************************************
***********************************************/


function allocate_customer_refund($creditnote_id, $refund_id, $refund_amount)
{
    $my_row = get_customer_transaction_record_details($creditnote_id, ST_CUSTCREDIT);
    if($my_row == null){
        return array("passed" => false, "message" => _("Credit note [".$creditnote_id."] not found in the database"));
    }
    
    $credit_note_left_to_allocate = $my_row['ov_amount'] - $my_row['alloc'];
    
    if($refund_amount <= $credit_note_left_to_allocate)
        $amount = $refund_amount;
    else{
        $amount = $credit_note_left_to_allocate;
    }
            
    revers_creditnote_refund_allocation($amount, $refund_id, $creditnote_id);
    
    delete_refund_allocations($refund_id);
    
    $allocation_id = create_creditnote_refund_allocations($amount, $refund_id, $creditnote_id);
    if(!$allocation_id > 0){
        return array("passed" => false, "message" => _("Refund allocations could not be created"));
    }
    
    $no_of_rows_affected = allocate_debtor_trans_creditnote($creditnote_id);
    if(!$no_of_rows_affected > 0){
        return array("passed" => false, "message" => _("Debtor credit note could not be allocated"));
    }
    
    $no_of_rows_affected = allocate_debtor_trans_refund($refund_id);
    if(!$no_of_rows_affected > 0){
        return array("passed" => false, "message" => _("Debtor refund could not be allocated"));
    }
    
    return array("passed" => true, "message" => $allocation_id);

}



?>