<?php
/**********************************************************************
    Copyright (C) FrontAccounting, LLC.
	Released under the terms of the GNU General Public License, GPL, 
	as published by the Free Software Foundation, either version 3 
	of the License, or (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
    See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
***********************************************************************/
$page_security = 'SA_SALESPAYMNT';
$path_to_root = "..";
include_once($path_to_root . "/includes/ui/allocation_cart.inc");
include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/banking.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/sales/includes/sales_db.inc");
include_once($path_to_root . "/reporting/includes/reporting.inc");

$js = "";
if ($SysPrefs->use_popup_windows) {
	$js .= get_js_open_window(900, 500);
}
if (user_use_date_picker()) {
	$js .= get_js_date_picker();
}
//add_js_file('payalloc.js');

page(_($help_context = "Reverse Customer Payment"), false, false, "", $js);

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

check_db_has_customers(_("There are no customers defined in the system."));

check_db_has_bank_accounts(_("There are no bank accounts defined in the system."));

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

if (!isset($_GET['trans_no']) || empty($_GET['trans_no'])) {
    display_error('No payment has been selected');
    return;
}
if (!isset($_POST['DateBanked'])) {
	$_POST['DateBanked'] = new_doc_date();
	if (!is_date_in_fiscalyear($_POST['DateBanked'])) {
		$_POST['DateBanked'] = end_fiscalyear();
	}
}


if (isset($_GET['AddedID'])) {
	$payment_no = $_GET['AddedID'];

	display_notification_centered(_("The customer payment has been successfully entered."));

	submenu_print(_("&Print This Receipt"), ST_CUSTPAYMENT, $payment_no."-".ST_CUSTPAYMENT, 'prtopt');

	submenu_view(_("&View this Customer Payment"), ST_CUSTPAYMENT, $payment_no);

	submenu_option(_("Enter Another &Customer Payment"), "/sales/customer_payments.php");
	submenu_option(_("Enter Other &Deposit"), "/gl/gl_bank.php?NewDeposit=Yes");
	submenu_option(_("Enter Payment to &Supplier"), "/purchasing/supplier_payment.php");
	submenu_option(_("Enter Other &Payment"), "/gl/gl_bank.php?NewPayment=Yes");
	submenu_option(_("Bank Account &Transfer"), "/gl/bank_transfer.php");

	display_note(get_gl_view_str(ST_CUSTPAYMENT, $payment_no, _("&View the GL Journal Entries for this Customer Payment")));

	display_footer_exit();
}

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

function can_process()
{
	global $Refs;

	
	if (!isset($_POST['DateBanked']) || !is_date($_POST['DateBanked'])) {
		display_error(_("The entered date is invalid. Please enter a valid date for the payment."));
		set_focus('DateBanked');
		return false;
	} elseif (!is_date_in_fiscalyear($_POST['DateBanked'])) {
		display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
		set_focus('DateBanked');
		return false;
	}

	if (!check_reference($_POST['ref'], ST_CUSTPAYMENT, @$_POST['trans_no'])) {
		set_focus('ref');
		return false;
	}
	
        

	$_SESSION['alloc']->amount = -1 * input_num('amount');
}

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

if (get_post('AddPaymentItem') && can_process()) {

	new_doc_date($_POST['DateBanked']);

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

	$_SESSION['alloc']->trans_no = $payment_no;
        clear_allocation_items();
        add_item(ST_CUSTPAYMENT, $payment_no, $_POST['DateBanked'], $_POST['DateBanked'], $_SESSION['alloc']->amount, 0, 
		$_SESSION['alloc']->amount, $_POST['ref']);
	$_SESSION['alloc']->write();

	unset($_SESSION['alloc']);
	meta_forward($_SERVER['PHP_SELF'],  "AddedID=$payment_no" );
}

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

function read_customer_data()
{
	global $Refs;

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

	$_POST['HoldAccount'] = $myrow["dissallow_invoices"];
	$_POST['pymt_discount'] = $myrow["pymt_discount"];
	// 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, null, array(
			'customer' => get_post('customer_id'), 'date' => get_post('DateBanked')));
}

//----------------------------------------------------------------------------------------------
$new = 1;

// To support Edit feature
if (isset($_GET['trans_no']) && $_GET['trans_no'] > 0 )
{
	$_POST['trans_no'] = $_GET['trans_no'];

	$new = 0;
	$myrow = get_customer_trans($_POST['trans_no'], ST_CUSTPAYMENT);
	$_POST['customer_id'] = $myrow["debtor_no"];
	$_POST['customer_name'] = $myrow["DebtorName"];
	$_POST['BranchID'] = $myrow["branch_code"];
	$_POST['PayRef'] =  $myrow["reference"];
	$_POST['PayID'] =  $myrow["trans_no"];
	$_POST['bank_account'] = $myrow["bank_act"];
	$charge = get_cust_bank_charge(ST_CUSTPAYMENT, $_POST['trans_no']);
	$_POST['charge'] =  price_format($charge * -1);
	$_POST['PayDate'] =  sql2date($myrow['tran_date']);
	$_POST["amount"] = price_format( ($myrow['Total'] - $myrow['ov_discount'] - $myrow['whtax']) * -1);
	$_POST["bank_amount"] = price_format(($myrow['bank_amount']+$charge) * -1) ;
	$_POST["discount"] = price_format($myrow['ov_discount'] * -1);
	$_POST["whtax"] = price_format($myrow['whtax'] * -1);
        
	//Prepare allocation cart 
	if (isset($_POST['trans_no']) && $_POST['trans_no'] > 0 )
		$_SESSION['alloc'] = new allocation(ST_CUSTPAYMENT,$_POST['trans_no']);
}

//----------------------------------------------------------------------------------------------
$new = !$_SESSION['alloc']->trans_no;
start_form();

hidden('trans_no');

start_outer_table(TABLESTYLE2, "width='60%'", 5);

table_section(1);

$bank_row = get_bank_account($_POST['bank_account']);
label_row(_("Into Bank Account:"), $bank_row['bank_name'], null, true);


label_cells(_("From Customer:"), $_SESSION['alloc']->person_name, "class='label'");
hidden('customer_id', $_POST['customer_id']);

if (db_customer_has_branches($_POST['customer_id'])) {
    $branch_row = get_cust_branch($_POST['customer_id'], $_POST['BranchID']);
	label_row(_("Branch:"), $branch_row['br_name'], 'BranchID', null, true);
} else {
	hidden('BranchID', ANY_NUMERIC);
}


read_customer_data();

set_global_customer($_POST['customer_id']);
if (isset($_POST['HoldAccount']) && $_POST['HoldAccount'] != 0)	
	display_warning(_("This customer account is on hold."));
$display_discount_percent = percent_format($_POST['pymt_discount']*100) . "%";

table_section(2);

label_row(_("Payment ID:"), $_POST['PayID']);
label_row(_("Payment Reference:"), $_POST['PayRef']);
label_row(_("Payment Date:"), $_POST['PayDate']);

table_section(3);

$comp_currency = get_company_currency();
$cust_currency = $_SESSION['alloc']->set_person($_POST['customer_id'], PT_CUSTOMER);
if (!$cust_currency)
	$cust_currency = $comp_currency;
$_SESSION['alloc']->currency = $bank_currency = get_bank_account_currency($_POST['bank_account']);

if ($cust_currency != $bank_currency)
{
	amount_row(_("Payment Amount:"), 'bank_amount', null, '', $bank_currency);
}

label_row(_("Bank Charge:"), $_POST['charge']);
ref_row(_("Reference:"), 'ref','' , null, '', ST_CUSTPAYMENT);
date_row(_("Reverse Date:"), 'DateBanked', '', true, 0, 0, 0, null, true);

end_outer_table(1);

div_start('alloc_tbl');
show_allocated(FALSE);
div_end();

start_table(TABLESTYLE, "width='60%'");

label_row(_("Customer prompt payment discount :"), $display_discount_percent);

label_row(_("Amount of Discount:"), 'discount', null, '', $cust_currency);

label_row(_("Withholding tax Amount:"), $_POST['whtax'], null, '', $cust_currency);

label_row(_("Amount:"), $_POST['amount'], null, '', $cust_currency);

textarea_row(_("Memo:"), 'memo_', null, 22, 4);
end_table(1);


	submit_center('AddPaymentItem', _("Reverse Payment"), true, '', 'default');

br();

end_form();
end_page();


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

function show_allocated($show_totals) {

	global $systypes_array;
	
    $k = $total_allocated = 0;

	$cart = $_SESSION['alloc'];
	$supp_ref = in_array($cart->type, array(ST_SUPPCREDIT, ST_SUPPAYMENT, ST_BANKPAYMENT));

	if (count($cart->allocs)) 
	{
		display_heading(sprintf(_("Allocated amounts in %s:"), $cart->person_curr));
		start_table(TABLESTYLE, "width='60%'");
   		$th = array(_("Transaction Type"), _("#"), $supp_ref ? _("Supplier Ref"): _("Ref"), _("Date"), _("Due Date"), _("Amount"),
   			 _("This Allocation"));

	   	table_header($th);

		foreach ($cart->allocs as $id => $alloc_item)
		{
		    if (floatcmp(abs($alloc_item->amount), $alloc_item->amount_allocated) && $alloc_item->current_allocated <> 0)
		    {
				alt_table_row_color($k);
    			label_cell($systypes_array[$alloc_item->type]);
	   			label_cell(get_trans_view_str($alloc_item->type, $alloc_item->type_no), "nowrap align='right'");
		   		label_cell($alloc_item->ref);
    			label_cell($alloc_item->date_, "align=right");
    			label_cell($alloc_item->due_date, "align=right");
	    		amount_cell(abs($alloc_item->amount));

		    	$_POST['amount' . $id] = price_format($alloc_item->current_allocated);

	    		
    			amount_cell($alloc_item->current_allocated, false,'', "amount" . $id);//, input_num('amount' . $id));
				
				end_row();

   	    		$total_allocated += input_num('amount' . $id);
		   	}
		}
		
		end_table(1);
	}
	hidden('TotalNumberOfAllocs', count($cart->allocs));
}
