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


//--------------------------------------------------------------------------------------------------

function check_refund_exists($refund_reference)
{
    $rr_row = get_refund_record($refund_reference);
    if($rr_row == null){
        return false;
    }
    else{
        return true;
    }
}


function fill_refund_cart($pos_invoice, $pos_refund, &$cart)
{
	global $Refs;

	
        $cart->order_id = 0;

	$cart->reference = $pos_invoice['reference']."_".$pos_refund['row_id'];
        
        $formatted_date = change_date_format("YYYYMMDD", $pos_invoice['order_date'], "MMDDYYYY");
	$cart->tran_date = $formatted_date;
	
        if (!is_date_in_fiscalyear($cart->tran_date))
		$cart->tran_date = end_fiscalyear();
	
	$cart->memo_ = '';
        
	$amount = $pos_refund["amount"];
        
        $branch_id = $pos_invoice['branch_id'];
        
        if ($branch_id != ANY_NUMERIC) {

		$branch_data = get_branch_accounts($branch_id);

		$debtors_account = $branch_data["receivables_account"];
		$discount_account = $branch_data["payment_discount_account"];

	} else {
		$debtors_account = $company_record["debtors_act"];
		$discount_account = $company_record["default_prompt_payment_act"];
	}
        
	$cart->add_gl_item($debtors_account, 0, 0, -$amount, '');


}

//-----------------------------------------------------------------------------------------------

function can_process_refund($pos_invoice, $pos_refund, $cart)
{

	global $Refs;

	if (!$pos_invoice['customer_id'])
	{
		return array("passed" => false, "message" => _("There is no customer selected."));
	} 
	
	if (!$pos_invoice['branch_id'])
	{
		return array("passed" => false, "message" => _("This customer has no branch defined."));
	} 
	
	if (!is_date($cart->tran_date)) {
		return array("passed" => false, "message" => _("The entered date is invalid. Please enter a valid date for the payment."));

	} elseif (!is_date_in_fiscalyear($cart->tran_date)) {
		return array("passed" => false, "message" => _("The entered date is not in fiscal year."));
	}

	if (!$Refs->is_valid($cart->reference)) {
		return array("passed" => false, "message" => _("You must enter a reference."));
	}

	//Chaitanya : 13-OCT-2011 - To support Edit feature
	if (isset($cart->order_id) && $cart->order_id == 0 && (!is_new_reference($cart->reference, ST_BANKPAYMENT))) {
		return array("passed" => false, "message" => _("The entered reference is already in use."));
	}
        
        $amount = -$cart->gl_items_total();

	if (!is_numeric($amount)) {
		return array("passed" => false, "message" => _("The entered amount is invalid and cannot be processed."));
	}

        if ($amount >= 0) {
                return array("passed" => false, "message" => _("The entered refund amount is possitive or zero and cannot be processed."));
	}

	if ($amount == 0.0) {
                return array("passed" => false, "message" => _("Refund amount should be less than zero."));
	}

	return array("passed" => true, "message" => _(""));
}

function refund_add($pos_invoice,$pos_refund)
{

        $cart = new items_cart(ST_BANKPAYMENT);
        $cart->trans_type = ST_BANKPAYMENT;

        fill_refund_cart($pos_invoice, $pos_refund, $cart);

        $list_code = "POS_PAYMENTS_BANCK_ACCOUNT_MAPPING";
        
        $bank_account_name = "";
        $bank_account_id = 0;
        
        $refund_method = $pos_refund['payment_method'];
        
        switch ($refund_method) {
                case 'Cash':
                case 'Credit Card':
                case 'Voucher':
                case 'Points':

                    $myrow = get_bank_account_name($list_code,$refund_method);
                    if($myrow != null){
                        $bank_account_name = $myrow["value_name"];
                    }

                    $bai_row = get_bank_account_id($bank_account_name);
                    if($bai_row != null){
                        $bank_account_id = $bai_row["id"];
                    }
        
                default:
        };

        if(check_refund_exists($cart->reference) == true){
            return  array("passed" => false, "message" => _("Refund record exists [".$cart->reference."]"));
        }

        $validation_result = can_process_refund($pos_invoice, $pos_refund, $cart);

        if($validation_result["passed"] == false){
            return $validation_result;
        }
    
	begin_transaction();

	$trans = write_bank_transaction(
		$cart->trans_type, $cart->order_id, $bank_account_id,
		$cart, $cart->tran_date,
		PT_CUSTOMER, $pos_invoice['customer_id'], $pos_invoice['branch_id'],
		$cart->reference, $cart->memo_, true, -$pos_refund["amount"]);
        
        // $trans_type, $trans_no, $from_account, $items, $date_,
	// $person_type_id, $person_id, $person_detail_id, $ref, $memo_, $use_transaction=true, $settled_amount=null

	add_new_exchange_rate(get_bank_account_currency($bank_account_id), $cart->tran_date, input_num('_ex_rate'));
	
        $trans_type = $trans[0];
   	$refund_no = $trans[1];
        
        unset($cart);
        
        if($refund_no > 0){
            $acr_msg = allocate_customer_refund($pos_invoice["trans_no"], $refund_no, -$pos_refund["amount"]);
            if($acr_msg['passed'] == true){
                commit_transaction();
                return array("passed" => true, "message" => $refund_no);
            }
            else{
                cancel_transaction();
                return  array("passed" => true, "message" => $acr_msg['message']);
            }  
        }
        else{
            cancel_transaction();
            return  array("passed" => false, "message" => "Could not add refund");
        }
        
        



}

//-----------------------------------------------------------------------------------------------

function check_refund_item_data()
{


	return true;
}

//-----------------------------------------------------------------------------------------------

function handle_update_item()
{
	$amount = ($_SESSION['pay_items']->trans_type==ST_BANKPAYMENT ? 1:-1) * input_num('amount');
    if($_POST['UpdateItem'] != "" && check_refund_item_data())
    {
    	$_SESSION['pay_items']->update_gl_item($_POST['Index'], $_POST['code_id'], 
    	    $_POST['dimension_id'], $_POST['dimension2_id'], $amount , $_POST['LineMemo']);
    }
	line_start_focus();
}

//-----------------------------------------------------------------------------------------------

function handle_delete_item($id)
{
	$_SESSION['pay_items']->remove_gl_item($id);
	line_start_focus();
}

//-----------------------------------------------------------------------------------------------

function handle_new_item()
{
	if (!check_refund_item_data())
		return;
	$amount = ($_SESSION['pay_items']->trans_type==ST_BANKPAYMENT ? 1:-1) * input_num('amount');

	$_SESSION['pay_items']->add_gl_item($_POST['code_id'], $_POST['dimension_id'],
		$_POST['dimension2_id'], $amount, $_POST['LineMemo']);
	line_start_focus();
}
//-----------------------------------------------------------------------------------------------

//-----------------------------------------------------------------------------------------------


?>
