<?php
/*=======================================================\
|                 Point of Sales Module                  |
|--------------------------------------------------------|
|   Creator: Phương                                      |
|   Date :   18-Dec-2017                                 |
|   Description: ERP Point of Sales Extension            |
|   Website: http://notrinos.com                         |
|                                                        |
\=======================================================*/

$page_security = 'SA_SALESCREDITINV';
$path_to_root = '../../..';

include_once($path_to_root.'/includes/ui/items_cart.inc');
include_once($path_to_root.'/sales/includes/cart_class.inc');
include_once($path_to_root.'/includes/session.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.'/sales/includes/sales_ui.inc');
include_once($path_to_root.'/reporting/includes/reporting.inc');
add_access_extensions();

include_once($path_to_root.'/modules/pos/includes/pos_ui.inc');
include_once($path_to_root.'/modules/pos/includes/pos_db.inc');

$js = '';
if ($SysPrefs->use_popup_windows)
	$js .= get_js_open_window(900, 600);
if (user_use_date_picker())
	$js .= get_js_date_picker();

if (isset($_GET['ModifyCredit'])) {
	$_SESSION['page_title'] = sprintf(_('Modifying Credit Invoice # %d.'), $_GET['ModifyCredit']);
	$help_context = 'Modifying Credit Invoice';
	processing_start();
}
elseif (isset($_GET['InvoiceNo'])) {
	$_SESSION['page_title'] = _($help_context = 'Credit all or part of an Invoice');
	processing_start();
}

page($_SESSION['page_title'], false, false, '', $js);
$restaurant_mode = get_company_pref('pos_restaurant_mode');
$debtors_act = get_company_pref('debtors_act');

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

if (isset($_GET['AddedID'])) {

	$credit_no = $_GET['AddedID'];
	$trans_type = ST_CUSTCREDIT;

	display_notification_centered(_('Credit Note has been processed'));
	display_note(get_customer_trans_view_str($trans_type, $credit_no, _('&View This Credit Note')), 0, 0);
	display_note(print_document_link($credit_no."-".$trans_type, _('&Print This Credit Note'), true, $trans_type), 1);
	display_note(print_document_link($credit_no."-".$trans_type, _('&Email This Credit Note'), true, $trans_type, false, "printlink", "", 1), 1);
 	display_note(get_gl_view_str($trans_type, $credit_no, _('View the GL &Journal Entries for this Credit Note')), 1);

 	if (isset($_GET['BankTransNo'])) {
   		display_notification_centered(sprintf(_('Payment %d has been entered'), $_GET['BankTransNo']));
		display_note(get_gl_view_str(ST_BANKPAYMENT, $_GET['BankTransNo'], _("&View the GL Postings for this Payment")), 1);
	}

	hyperlink_params($path_to_root.'/admin/attachments.php', _('Add an Attachment'), 'filterType='.$trans_type.'&trans_no='.$credit_no);

	display_footer_exit();
}
elseif (isset($_GET['UpdatedID'])) {
	$credit_no = $_GET['UpdatedID'];
	$trans_type = ST_CUSTCREDIT;

	display_notification_centered(_('Credit Note has been updated'));

	display_note(get_customer_trans_view_str($trans_type, $credit_no, _('&View This Credit Note')), 0, 0);

	display_note(print_document_link($credit_no."-".$trans_type, _('&Print This Credit Note'), true, $trans_type),1);
	display_note(print_document_link($credit_no."-".$trans_type, _('&Email This Credit Note'), true, $trans_type, false, "printlink", "", 1), 1);

 	display_note(get_gl_view_str($trans_type, $credit_no, _('View the GL &Journal Entries for this Credit Note')), 1);

	display_footer_exit();
}
else
	check_edit_conflicts(get_post('cart_id'));

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

function can_process() {
	global $Refs, $debtors_act;

	if(is_bank_account($debtors_act) && empty($_POST['pay_later'])) {
		display_error(_('The default customer receiveable account is bank account, please set up another account or choose Pay Later.'));
		return false;
	}
	if (!is_date($_POST['CreditDate'])) {
		display_error(_('The entered date is invalid.'));
		set_focus('CreditDate');
		return false;
	}
	elseif (!is_date_in_fiscalyear($_POST['CreditDate'])) {
		display_error(_('The entered date is out of fiscal year or is closed for further data entry.'));
		set_focus('CreditDate');
		return false;
	}
    if ($_SESSION['PosItems']->trans_no==0) {
		if (!$Refs->is_valid($_POST['ref'], ST_CUSTCREDIT)) {
			display_error(_('You must enter a reference.'));
			set_focus('ref');
			return false;
		}
    }
	if (!check_num('ChargeFreightCost', 0)) {
		display_error(_('The entered shipping cost is invalid or less than zero.'));
		set_focus('ChargeFreightCost');
		return false;
	}
	if (!check_quantities()) {
		display_error(_('Selected quantity cannot be less than zero nor more than quantity not returned yet.'));
		return false;
	}
	return true;
}

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

if (isset($_GET['InvoiceNo']) && $_GET['InvoiceNo'] > 0) {
    $_SESSION['PosItems'] = new Cart(ST_SALESINVOICE, $_GET['InvoiceNo'], true);
	copy_from_cart();
	create_pay_items_cart();
}
elseif( isset($_GET['ModifyCredit']) && $_GET['ModifyCredit']>0) {
	$_SESSION['PosItems'] = new Cart(ST_CUSTCREDIT, $_GET['ModifyCredit']);
	copy_from_cart();
}
elseif (!processing_active()) {
	/* This page can only be called with an invoice number for crediting*/
	die (_('This page can only be opened if an invoice has been selected for crediting.'));
}
elseif (!check_quantities())
	display_error(_('Selected quantity cannot be less than zero nor more than quantity not returned yet.'));

function check_quantities() {
	$ok =1;
	foreach ($_SESSION['PosItems']->line_items as $line_no=>$itm) {
		if ($itm->quantity == $itm->qty_done)
			continue; // this line was fully credited/removed

		if (isset($_POST['Line'.$line_no])) {
			if (check_num('Line'.$line_no, 0, $itm->quantity))
				$_SESSION['PosItems']->line_items[$line_no]->qty_dispatched = input_num('Line'.$line_no);
			else
				$ok = 0;
	  	}
		if (isset($_POST['Line'.$line_no.'Desc'])) {
			$line_desc = $_POST['Line'.$line_no.'Desc'];
			if (strlen($line_desc) > 0)
				$_SESSION['PosItems']->line_items[$line_no]->item_description = $line_desc;
	  	}
	}
	return $ok;
}

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

function copy_to_cart() {
	$cart = &$_SESSION['PosItems'];
	$cart->ship_via = $_POST['ShipperID'];
	$cart->freight_cost = input_num('ChargeFreightCost');
	$cart->document_date =  $_POST['CreditDate'];
	$cart->Location = (isset($_POST['Location']) ? $_POST['Location'] : '');
	$cart->Comments = $_POST['CreditText'];
	if ($_SESSION['PosItems']->trans_no == 0)
		$cart->reference = $_POST['ref'];
}

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

function copy_from_cart() {
	$cart = &$_SESSION['PosItems'];
	$_POST['ShipperID'] = $cart->ship_via;
	$_POST['ChargeFreightCost'] = price_format($cart->freight_cost);
	$_POST['CreditDate']= $cart->document_date;
	$_POST['Location']= $_SESSION['wa_current_user']->pos;
	$_POST['CreditText']= $cart->Comments;
	$_POST['cart_id'] = $cart->cart_id;
	$_POST['ref'] = $cart->reference;
}

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

function create_pay_items_cart() {
	global $Refs, $restaurant_mode;

	if (isset($_SESSION['pay_items']))
		unset ($_SESSION['pay_items']);

	$pay_cart = new items_cart(ST_BANKPAYMENT);
    $pay_cart->order_id = 0;

	$pay_cart->reference = $Refs->get_next($pay_cart->trans_type, null, $pay_cart->tran_date);
	$pay_cart->tran_date = new_doc_date();
	if (!is_date_in_fiscalyear($pay_cart->tran_date))
		$pay_cart->tran_date = end_fiscalyear();

	$cur_pos = $_SESSION['wa_current_user']->pos;

	$pos_row = get_sales_point($cur_pos);
	$cash_account = $pos_row['pos_account'];

	$_POST['memo_'] = $pay_cart->memo_;
	$_POST['bank_ref'] = $pay_cart->reference;
	$_POST['date_'] = $pay_cart->tran_date;

	$_POST['bank_account'] = $cash_account;
	$_POST['person_id'] = $_SESSION['PosItems']->customer_id;
	$_POST['PersonDetailID'] = $_SESSION['PosItems']->Branch;

	$_SESSION['pay_items'] = &$pay_cart;
}

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

if (isset($_POST['ProcessCredit']) && can_process()) {
	$new_credit = ($_SESSION['PosItems']->trans_no == 0);

	if (!isset($_POST['WriteOffGLCode']))
		$_POST['WriteOffGLCode'] = 0;

	copy_to_cart();
	if ($new_credit) 
		new_doc_date($_SESSION['PosItems']->document_date);

	$credit_no = $_SESSION['PosItems']->write($_POST['WriteOffGLCode']);

	if ($credit_no == -1) {
		display_error(_('The entered reference is already in use.'));
		set_focus('ref');
	}
	elseif($credit_no) {

		$new_bank_trans = false;
		
		if(empty($_POST['pay_later'])) {

			$total_itm = $_SESSION['PosItems']->get_items_total_dispatch();
    		$pay_taxes = $_SESSION['PosItems']->get_taxes(input_num($_POST['ChargeFreightCost']));
    		$tax_total = display_edit_tax_items($pay_taxes, $colspan=7, $_SESSION['PosItems']->tax_included);
    		$pay_total = $total_itm + input_num('ChargeFreightCost') + $tax_total;
    		$debtors_act = get_company_pref('debtors_act');
			$_SESSION['pay_items']->add_gl_item($debtors_act, $dimension_id=0, $dimension2_id=0, $pay_total);

			begin_transaction();

			$_SESSION['pay_items'] = &$_SESSION['pay_items'];
			$new_bank_trans = $_SESSION['pay_items']->order_id == 0;

			add_new_exchange_rate(get_bank_account_currency(get_post('bank_account')), get_post('date_'), input_num('_ex_rate'));

			$bank_trans = write_bank_transaction($_SESSION['pay_items']->trans_type, $_SESSION['pay_items']->order_id, $_POST['bank_account'], $_SESSION['pay_items'], $_POST['date_'], PT_CUSTOMER, $_POST['person_id'], get_post('PersonDetailID'), $_POST['bank_ref'], $_POST['memo_'], true, input_num('settled_amount', null));

			$bank_trans_type = $bank_trans[0];
   			$bank_trans_no = $bank_trans[1];
			new_doc_date($_POST['date_']);

			$_SESSION['pay_items']->clear_items();
			unset($_SESSION['pay_items']);

			$bank_trans_row = db_fetch(get_bank_trans($bank_trans_type, $bank_trans_no, PT_CUSTOMER));

			save_pos_bank_trans($bank_trans_row[0], $credit_no, ST_CUSTCREDIT);

			commit_transaction();
		}
		processing_end();

		if ($new_credit)
			meta_forward($_SERVER['PHP_SELF'], 'AddedID='.$credit_no.($new_bank_trans ? '&BankTransNo='.$bank_trans_no : ''));
		else
			meta_forward($_SERVER['PHP_SELF'], 'UpdatedID='.$credit_no);
	}
}

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

if (isset($_POST['Location']))
	$_SESSION['PosItems']->Location = $_POST['Location'];

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

function display_credit_items() {
    start_form();
	hidden('cart_id');

	start_table(TABLESTYLE2, "width='80%'", 5);
    start_row();

    label_cells(_('Customer'), $_SESSION['PosItems']->customer_name, "class='tableheader2'");

    if ($_SESSION['PosItems']->trans_no==0) {
		ref_cells(_('Reference'), 'ref', '', null, "class='tableheader2'", false, ST_CUSTCREDIT,
		array('customer' => $_SESSION['PosItems']->customer_id,
			'branch' => $_SESSION['PosItems']->Branch,
			'date' => get_post('CreditDate')));
	}
	else
		label_cells(_('Reference'), $_SESSION['PosItems']->reference, "class='tableheader2'");
	
    label_cells(_('Crediting Invoice'), get_customer_trans_view_str(ST_SALESINVOICE, array_keys($_SESSION['PosItems']->src_docs)), "class='tableheader2'");

	if (!isset($_POST['ShipperID']))
		$_POST['ShipperID'] = $_SESSION['PosItems']->ship_via;

	hidden('ShipperID', $_POST['ShipperID']);
    hidden('CreditDate', Today());
    hidden('bank_account');
    hidden('date_', Today());
    hidden('person_id');
    hidden('PersonDetailID');
    hidden('bank_ref');
    hidden('memo_');

    end_row();
	end_table(1);

	div_start('credit_items');
    start_table(TABLESTYLE, "width='80%'");
    $th = array(_('Item'), _('Invoiced'), _('Units'), _('Returned'), _('This Return'), _('Price'), _('Discount %'), _('Total'));
    table_header($th);

    $k = 0;

    foreach ($_SESSION['PosItems']->line_items as $line_no=>$ln_itm) {

		if ($ln_itm->quantity == $ln_itm->qty_done)
			continue; // this line was fully credited/removed
		
		alt_table_row_color($k);

    	label_cell($ln_itm->stock_id.' - '.$ln_itm->item_description);
    	hidden('Line'.$line_no.'Desc', $ln_itm->item_description);

		$dec = get_qty_dec($ln_itm->stock_id);
    	qty_cell($ln_itm->quantity, false, $dec);
    	label_cell($ln_itm->units);
    	qty_cell($ln_itm->qty_done);

    	if(is_returnable_item($ln_itm->stock_id)) {
    		label_cell(_('Non Returnable'));
    		hidden('Line'.$line_no, 0);
    	}
    	else
			amount_cells(null, 'Line'.$line_no, number_format2($ln_itm->qty_dispatched, $dec), null, null, $dec);

    	$line_total =($ln_itm->qty_dispatched * $ln_itm->price * (1 - $ln_itm->discount_percent));

    	amount_cell($ln_itm->price);
    	percent_cell($ln_itm->discount_percent*100);
    	amount_cell($line_total);
    	end_row();
    }

    if (!check_num('ChargeFreightCost'))
    	$_POST['ChargeFreightCost'] = price_format($_SESSION['PosItems']->freight_cost);
    
	$colspan = 7;
	start_row();
	label_cell(_('Credit Shipping Cost'), 'colspan='.$colspan.' align=right');
	small_amount_cells(null, 'ChargeFreightCost', price_format(get_post('ChargeFreightCost', 0)));
	end_row();

    $inv_items_total = $_SESSION['PosItems']->get_items_total_dispatch();

    $display_sub_total = price_format($inv_items_total + input_num($_POST['ChargeFreightCost']));
    label_row(_('Sub-total'), $display_sub_total, 'colspan='.$colspan.' align=right', 'align=right');

    $taxes = $_SESSION['PosItems']->get_taxes(input_num($_POST['ChargeFreightCost']));
    $tax_total = display_edit_tax_items($taxes, $colspan, $_SESSION['PosItems']->tax_included);
    $display_total = price_format(($inv_items_total + input_num('ChargeFreightCost') + $tax_total));

    label_row(_('Credit Note Total'), $display_total, 'colspan='.$colspan.' align=right', 'align=right');

    end_table();
	div_end();
}

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

function display_credit_options() {
	global $Ajax, $restaurant_mode;
	br();

	if (isset($_POST['_CreditType_update']))
		$Ajax->activate('options');

 	div_start('options');
	start_table(TABLESTYLE2);

	credit_type_list_row(_('Credit Note Type'), 'CreditType', null, true);

	if ($_POST['CreditType'] == 'Return') {
		/*if the credit note is a return of goods then need to know which location to receive them into */
		if (!isset($_POST['Location']))
			$_POST['Location'] = $_SESSION['PosItems']->Location;
	   	pos_sales_point_list_row(_('Return to Location'), 'Location', $_POST['Location'], false, false, false, true);
	}
	else {
		/* the goods are to be written off to somewhere */
		gl_all_accounts_list_row(_('Write off the cost of the items to'), 'WriteOffGLCode', null);
	}
	// Fixme, pay later option will not save pos_bank_trans data so the later bank payment will not be considered as a pos transaction
	// check_row(_('Pay Later'), 'pay_later');
	hidden('pay_later', 0);

	textarea_row(_('Memo'), 'CreditText', null, 35, 5);
	echo '</table>';
	div_end();
}

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

if (get_post('Update')) {
	copy_to_cart();
	$Ajax->activate('_page_body');
}

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

display_credit_items();
display_credit_options();

echo '<br><center>';
submit('Update', _('Update'), true, _('Update credit value for quantities entered'), true);
echo "&nbsp";
submit('ProcessCredit', _('Process Credit Note'), true, '', 'default');
echo '</center>';

end_form();
// var_dump($_SESSION['PosItems']);
// var_dump($_SESSION['pay_items']);
end_page();