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

function check_payment_exists($payment_reference)
{
    $pr_row = get_payment_record($payment_reference);
    if($pr_row == null){
        return false;
    }
    else{
        return true;
    }
}

function can_process($payment)
{
	global $Refs;

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

	} elseif (!is_date_in_fiscalyear($payment['DateBanked'])) {
		return array("passed" => false, "message" => _("The entered date is not in fiscal year."));
	}

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

	//Chaitanya : 13-OCT-2011 - To support Edit feature
	if (isset($payment['trans_no']) && $payment['trans_no'] == 0 && (!is_new_reference($payment['reference'], ST_CUSTPAYMENT))) {
		return array("passed" => false, "message" => _("The entered reference is already in use."));
	}
	//Avoid duplicate reference while modifying
//	elseif ($payment['ref'] != $payment['old_ref'] && !is_new_reference($payment['ref'], ST_CUSTPAYMENT))
//	{
//		return array("passed" => false, "message" => _("The entered reference is already in use."));
//	}

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

        if ($payment['amount'] <= 0) {
        return array("passed" => false, "message" => _("The entered amount is negative or zero and cannot be processed."));
	}
        
	if (!is_numeric($payment['charge'])){
		return array("passed" => false, "message" => _("The entered amount is invalid and cannot be processed."));
	}
        
        if($payment['charge'] < 0){
		return array("passed" => false, "message" => _("The entered amount is negative and cannot be processed."));
        }
        
        
	if ( !is_numeric($payment['charge']) || !$payment['charge'] >= 0) {
		$charge_acct = get_company_pref('bank_charge_act');
		if (get_gl_account($charge_acct) == false) {
			return array("passed" => false, "message" => _("The Bank Charge Account has not been set in System and General GL Setup."));
		}	
	}

//	if (isset($_POST['_ex_rate']) && !check_num('_ex_rate', 0.000001))
//	{
//		display_error(_("The exchange rate must be numeric and greater than zero."));
//		set_focus('_ex_rate');
//		return false;
//	}

	if ($payment['discount'] == "") 
	{
		$payment['discount'] = 0;
	}

	if (!is_numeric($payment['discount'])) {
		return array("passed" => false, "message" => _("The entered discount is not a valid number."));
	}

	//if ((input_num('amount') - input_num('discount') <= 0)) {
	if ($payment['amount'] <= 0) {
		return array("passed" => false, "message" => _("The balance of the amount and discount is zero or negative. Please enter valid amounts."));
	}

	if (!is_numeric($payment['bank_amount']))
	{
		return array("passed" => false, "message" => _("The entered payment amount is invalid."));
	}

        if ($payment['bank_amount'] <= 0)
	{
		return array("passed" => false, "message" => _("The entered payment amount is zero or negative."));
	}
        
	if (!db_has_currency_rates(get_customer_currency($payment['customer_id']), $payment['DateBanked'], true))
		return array("passed" => false, "message" => _("Cannot retrieve exchange rate for currency."));

	//$_SESSION['alloc']->amount = input_num('amount');

//	if (isset($_POST["TotalNumberOfAllocs"]))
//		return check_allocations();
//	else
		return array("passed" => true, "message" => _(""));
}

function read_customer_data()
{
	global $Refs;

	$myrow = get_customer_habit($_POST['customer_id']);

	$_POST['HoldAccount'] = $myrow["dissallow_invoices"];
	$_POST['pymt_discount'] = $myrow["pymt_discount"];
	//Chaitanya : 13-OCT-2011 - To support Edit feature
	//If page is called first time and New entry fetch the nex reference number
	if (!$_SESSION['alloc']->trans_no && !isset($_POST['charge'])) 
		$_POST['ref'] = $Refs->get_next(ST_CUSTPAYMENT);
}


function load_payment_data($pos_invoice,$pos_payment){
    
    $pmt['trans_no'] = 00;
    $pmt['customer_id'] = $pos_invoice['customer_id'];
    $pmt['branch_id'] = $pos_invoice['branch_id'];
    
    $payment_method = $pos_payment['payment_method'];
    
    $list_code = "POS_PAYMENTS_BANCK_ACCOUNT_MAPPING";
    
    $bank_account_name = "";
    $bank_account_id = 0;
    
    switch ($payment_method) {
        case 'Cash':
        case 'Credit Card':
        case 'Voucher':
        case 'Points':
            //case 'Customer Account':
            $myrow = get_bank_account_name($list_code,$payment_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:
    };
    
    $pmt['bank_account'] = $bank_account_id;

    $formatted_date = change_date_format("YYYYMMDD", $pos_invoice['order_date'], "MMDDYYYY");
    $pmt['DateBanked'] = $formatted_date;
    
    $pmt['reference'] = $pos_invoice['reference']."_".$pos_payment['row_id'];
    $pmt['amount'] = (float)$pos_payment['amount'];

    $pmt['charge'] = 0;
    $pmt['bank_amount'] = $pmt['amount'];
    
    $pmt['discount'] = 0;
    
    if($pos_payment['payment_method'] == "Credit Card"){
        $pmt['memo_'] = $pos_payment['card_type']." - ".$pos_payment['card_number'];
    }
    elseif($pos_payment['payment_method'] == "Voucher"){
        $pmt['memo_'] = "Voucher - ".$pos_payment['card_number'];
    }
    else{
        $pmt['memo_'] = "";
    }

    return $pmt;
}


function payment_add($pos_invoice,$pos_payment){
    
    $payment = load_payment_data($pos_invoice,$pos_payment);
    
    if(check_payment_exists($payment['reference']) == true){
        return  array("passed" => false, "message" => _("Payment record exists [".$payment['reference']."]"));
    }
    
    $validation_result = can_process($payment);
    
    if($validation_result["passed"] == false){
        return $validation_result;
    }
    //return;   
    
    if($pos_payment['payment_method'] == "Customer Account"){
        $customer_account_payment_no = add_pos_customer_account_payment($pos_invoice, $payment);
        if($customer_account_payment_no >0){
            return array("passed" => true, "message" => $customer_account_payment_no);
        }
        else{
            return array("passed" => false, "message" => _("POS customer account payment could not be added."));
        }
    }
    else{
        begin_transaction();
        $payment_no = add_payment($payment);   

        if($payment_no >0){
            $acp_msg = allocate_customer_payment($pos_invoice["trans_no"], $payment_no, $payment["amount"]);
            if($acp_msg['passed'] == true){
                commit_transaction();
                return array("passed" => true, "message" => $payment_no);
            }
            cancel_transaction();
        }
        else{
            cancel_transaction();
            return array("passed" => false, "message" => _("Customer payment could not be added."));
        }
    }
}

        
function add_payment($payment)
        {
	new_doc_date($payment['DateBanked']);

	//$new_pmt = !$_SESSION['alloc']->trans_no;
	//Chaitanya : 13-OCT-2011 - To support Edit feature
	$payment_no = write_customer_payment($payment['trans_no'], $payment['customer_id'], $payment['branch_id'],
                                            $payment['bank_account'], $payment['DateBanked'], $payment['reference'],
                                            $payment['amount'], $payment['discount'], $payment['memo_'], 
                                            0, $payment['charge'], $payment['bank_amount']);
        
        return $payment_no;

}


function add_pos_customer_account_payment($pos_invoice, $payment)
{
        $pos_customer_account_payment_no = create_pos_customer_account_payment(
                                            $payment['customer_id'], $payment['branch_id'], 
                                            $payment['DateBanked'], $payment['reference'], $pos_invoice["trans_no"], 
                                            $payment['amount']);
        
        return $pos_customer_account_payment_no;
        
}




?>