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


function allocate_customer_payment($invoice_id, $payment_id, $payment_amount)
{
    $my_row = get_customer_transaction_record_details($invoice_id, ST_SALESINVOICE);
    if($my_row == null){
        return array("passed" => false, "message" => _("Invoice [".$invoice_id."] not found in the database"));
    }
    
    $invoice_left_to_allocate = $my_row['ov_amount'] - $my_row['alloc'];
    
    if($payment_amount <= $invoice_left_to_allocate)
        $amount = $payment_amount;
    else{
        $amount = $invoice_left_to_allocate;
    }
            
    revers_debtor_trans_allocation($amount, $payment_id, $invoice_id);
    
    delete_cust_allocations($payment_id);
    
    $allocation_id = create_cust_allocations($amount, $payment_id, $invoice_id);
    if(!$allocation_id > 0){
        return array("passed" => false, "message" => _("Payment allocations could not be created"));
    }
    
    $no_of_rows_affected = allocate_debtor_trans_invoice($invoice_id);
    if(!$no_of_rows_affected > 0){
        return array("passed" => false, "message" => _("Debtor invoice could not be allocated"));
    }
    
    $no_of_rows_affected = allocate_debtor_trans_payment($payment_id);
    if(!$no_of_rows_affected > 0){
        return array("passed" => false, "message" => _("Debtor payment could not be allocated"));
    }
    
    return array("passed" => true, "message" => $allocation_id);

}



?>