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

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

include_once($path_to_root . '/includes/ui/allocation_cart.inc');
include_once($path_to_root . '/modules/pos/includes/pos_classes.inc');
include_once($path_to_root . '/includes/session.inc');
include_once($path_to_root . '/sales/includes/sales_ui.inc');
include_once($path_to_root . '/sales/includes/ui/sales_order_ui.inc');
include_once($path_to_root . '/sales/includes/sales_db.inc');
include_once($path_to_root . '/sales/includes/db/sales_types_db.inc');
include_once($path_to_root . '/reporting/includes/reporting.inc');

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

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

$pref = get_company_prefs();

$category = $pref['pos_def_category'] == -1 ? 0 : $pref['pos_def_category'];

page(_($help_context = 'POS Entry'), false, false, '', $js, false);
add_css_file($path_to_root.'/modules/pos/css/pos_entry.css');
add_css_file($path_to_root.'/modules/pos/css/pos_payment.css');
send_css();
echo "<script type='text/javascript' src='".$path_to_root."/modules/pos/js/print.min.js'></script>";
echo "<div id='pos_loading_spinner' style='display:none; z-index:10000; position:fixed; top:0; left:0; width: 100vw; height:100vh; background-color:#000; padding-top: 10%; opacity: 0.9;'><center><img src= '".$path_to_root."/modules/pos/css/ring-alt.svg'></center></div>";

if(isset($_GET['Reload']) && $_GET['Reload'] === 'Yes') {
	if(empty($_SESSION['PosItems'])) {
		display_error(_('Missing context data'));
		display_footer_exit();
	}
	$so_type = $_SESSION['PosItems']->so_type;
	$ret = $_SESSION['PosItems']->write(1);
	complete_order($so_type);
}

if (isset($_GET['NewInvoice']) && is_numeric($_GET['NewInvoice'])) {
	if(!pos_default_payment_term()) {
		display_error(_('Please define at least one payment term with <b>After No. of Days</b> type'));
		display_footer_exit();
	}
	else
		create_cart(ST_SALESINVOICE, 0);
}

if (isset($_GET['AddedDI'])) {
	$invoice = $_GET['AddedDI'];

	if(!is_pos_trans($invoice)) {
		display_error(_('The selected transaction is not a POS transaction.'));
		display_footer_exit();
	}
	
	include_once($path_to_root . '/modules/pos/includes/ui/pos_receipt.inc');
	echo "<div id='pos_success'>";
	display_notification_centered(sprintf(_('Invoice # %d has been entered.'), $invoice));

	if ((isset($_GET['Type']) && $_GET['Type'] == 1))
		submenu_option(_('Enter a &New Template Invoice'), '/sales/inquiry/sales_orders_view.php?InvoiceTemplates=Yes');
	else
		submenu_option(_('&Next Order').' >>', '/modules/pos/manage/sales_entry.php?NewInvoice=0', 'pos_next_order');

	submenu_view(_('&View This Invoice'), ST_SALESINVOICE, $invoice);

	submenu_print(_('&Print Sales Invoice'), ST_SALESINVOICE, $invoice.'-'.ST_SALESINVOICE, 'prtopt');
	submenu_print(_('&Email Sales Invoice'), ST_SALESINVOICE, $invoice."-".ST_SALESINVOICE, null, 1);
	set_focus('prtopt');

	display_note(get_gl_view_str(ST_SALESINVOICE, $invoice, _('View the GL &Journal Entries for this Invoice')),0, 1);

	if($row === false) //$row from pos_receipt.inc
		submenu_option(_('Entry &customer payment for this invoice'), '/sales/customer_payments.php?SInvoice='.$invoice);

	submenu_option(_('Add an Attachment'), '/admin/attachments.php?filterType='.ST_SALESINVOICE.'&trans_no='.$invoice);
	echo '</div>';

	end_page();
	if(!empty($pref['pos_prompt_receipt_print'])) {
		echo "<script type='text/javascript'>";
		echo "document.getElementById('pos_loading_spinner').style.display = 'block';";
		echo "setTimeout(function(){document.getElementById('receipt_container').getElementsByClassName('printlink')[0].click();";
		if(empty($pref['pos_receipt_print_silent']))
			echo "document.getElementById('pos_loading_spinner').style.display = 'none';";
		echo "}, 1000)";
		echo "</script>";
	}
	exit;
}

function create_cart($type, $trans_no) { 
	global $Refs, $SysPrefs;

	if (!$SysPrefs->db_ok)
		return;

	processing_start();
	$_SESSION['PosItems'] = new PosCart($type, array($trans_no));
}

function complete_order($so_type) {
	global $Refs, $messages;

	if (count($messages)) { // abort on failure or error messages are lost
		$Ajax->activate('_page_body');
		display_footer_exit();
	}
	$trans_no = key($_SESSION['PosItems']->trans_no);
	$trans_type = $_SESSION['PosItems']->trans_type;
	new_doc_date($_SESSION['PosItems']->document_date);

	if(!empty(get_company_pref('pos_commission'))) { // save salesman trans details if use POS commission
		foreach($_SESSION['commissions'] as $k => $details) {
			if(!empty($details['salesman']))
				save_salesman_trans_details($details['salesman'], $trans_no, $details['item'], $details['qty'], $details['price'], $details['commission']);
		}
	}

	$bill_discount = 0;

	foreach ($_SESSION['payment_items'] as $pay) { // Allocations starts
		$_SESSION['alloc'] = new allocation(ST_CUSTPAYMENT, 0, $_SESSION['PosItems']->customer_id);
		$inv = get_customer_trans($trans_no, ST_SALESINVOICE);
		$_POST['bank_account'] = $pay['bank'];

		$_POST['customer_id'] = $inv['debtor_no'];
		$_SESSION['alloc']->set_person($inv['debtor_no'], PT_CUSTOMER);
		$_SESSION['alloc']->read();
		$_POST['BranchID'] = $inv['branch_code'];
		$_POST['DateBanked'] = sql2date($inv['tran_date']);
		$_POST['ref'] = $Refs->get_next(ST_CUSTPAYMENT, null, array('customer' => get_post('customer_id'), 'date' => get_post('DateBanked')));
		$_POST['discount'] = $pay['discount'];
		$_POST['bank_amount'] = 0;
		$_POST['charge'] = 0;
		$_POST['memo_'] = '';

		foreach($_SESSION['alloc']->allocs as $line => $trans) {
			if ($trans->type == ST_SALESINVOICE && $trans->type_no == $trans_no) {
				$un_allocated = $trans->amount - $trans->amount_allocated;
				if ($un_allocated){
					$_SESSION['alloc']->allocs[$line]->current_allocated = $pay['amount'];
					$_POST['amount'] = $_POST['amount'.$line] = $pay['amount']-$_POST['discount'];
				}
				break;
			}
		}
		unset($inv);

		new_doc_date($_POST['DateBanked']);

		$new_pmt = !$_SESSION['alloc']->trans_no;

		$payment_no = write_customer_payment($_SESSION['alloc']->trans_no, $_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('amount')));

		$bank_trans = db_fetch(get_bank_trans(ST_CUSTPAYMENT, $payment_no))[0];

		$_SESSION['alloc']->trans_no = $payment_no;
		$_SESSION['alloc']->date_ = $_POST['DateBanked'];
		$_SESSION['alloc']->amount = input_num('amount');
		$_SESSION['alloc']->write();

		$bill_discount += input_num('discount');

		unset($_SESSION['alloc']);
	} // Allocations ends

	save_pos_trans($trans_no, $_SESSION['cash'], $bill_discount, $_SESSION['order_type'], $_SESSION['table'], date('Y-m-d H:i:s'), $_SESSION['wa_current_user']->pos);

	save_pos_bank_trans($bank_trans, $trans_no, ST_SALESINVOICE);
	
	delete_table_order($_SESSION['wa_current_user']->pos, $_SESSION['table']);
	unset($_SESSION['cash']);
	unset($_SESSION['order_type']);
	unset($_SESSION['table']);

	processing_end();
	if($trans_type == ST_SALESINVOICE)
		pos_meta_forward($_SERVER['PHP_SELF'], 'AddedDI='.$trans_no.'&Type='.$so_type);
}

function list_catogries() {
	global $category;
	$sql = "SELECT category_id, description FROM ".TB_PREF."stock_category WHERE !inactive";
	$result = db_query($sql, _('Could not get stock category'));
	
	echo "<div id='cate_container'>";

	while($row = db_fetch($result)) {

		$count = 0;
		$items_txt = '';
		$items = get_pos_items($row['category_id']);
		$selected_cat = '';
		if($row['category_id'] == $category)
			$selected_cat = ' selected_cat';
		
		while ($item = db_fetch($items)) {
			if($count == 0)
				$items_txt .= $item['stock_id'];
			else
				$items_txt .= "&".$item['stock_id'];
			$count ++;
		}
		if($items_txt != '')
			echo "<div data='".$items_txt."' cat=".$row['category_id']." class='categories_link".$selected_cat."'>".$row['description']."</div>";
	}
	$items_txt2 = '';
	$count2 = 0;
	$items = get_pos_items();
	while ($item = db_fetch($items)) {

		$items_txt2 .= ($count2 == 0) ? $item['stock_id'] : "&".$item['stock_id'];
		$count2 ++;
	}
	$selected_cat = $category == 0 ? ' selected_cat' : '';

	echo "<div data='".$items_txt2."' cat=0 class='categories_link".$selected_cat."'>"._('All')."</div>";
	echo "</div>";
}

function list_stocks($category=false) {
	global $Ajax, $path_to_root, $pref;

	$result = get_pos_items();
	$stock_img_path = company_path().'/images/';
	$sales_type = get_company_pref('pos_def_sales_type');
	$sales_types_db = get_sales_type($sales_type);
	$tax_included = $sales_types_db['tax_included'];
	
	echo "<center>".text_input('itemCode', null, 20, 20, _('Item Code'), "placeholder='"._('Enter Item Code or Scan Barcode').":'")."</center><br>";

	if($pref['pos_restaurant_mode'] == '1') {

		div_start('order_type_table');

		$def_method = get_company_pref('pos_def_restaurant_order_type');
		$def_1 = ''; $def_2 = ''; $def_3 = '';

		if($def_method == 0 || $def_method == 1)
			$def_1 = 'default';
		elseif($def_method == 2)
			$def_2 = 'default';
		else
			$def_3 = 'default';
		
		echo "<div id='pos_take_away' class='pos_order_type_btn' orderType='2' ".$def_2.">"._('Take Away')."</div>";
		echo "<div id='pos_delivery' class='pos_order_type_btn' orderType='3' ".$def_3.">"._('Delivery')."</div>";
		echo "<div id='pos_dine_in' class='pos_order_type_btn' orderType='1' ".$def_1.">"._('Dine-In')."</div>";
		echo "<div id='pos_table_seat' class='pos_table_selector'>"._('Table:').'&nbsp;'."<div id='curTable'></div></div>";

		div_end();

		echo "<div id='pos_table_list'>";
		for($i=1; $i<=$pref['pos_table_number']; $i++) {

			$table_details = get_table_order_details($_SESSION['wa_current_user']->pos, $i);
			$item_data = array();
			$user_id = '';
			foreach($table_details as $row) {
				$price = get_pos_item_price_after_taxes($row['item_code'], $row['price']*(1 - $row['discount_percent']), $tax_included);
				$tax = $price == $row['price'] ? 0 : (($price - $row['price']) / ($row['price']/100))/100;
				$item_data[] = array('item_code'=>$row['item_code'], 'item_description'=>$row['item_description'], 'units'=>$row['units'], 'quantity'=>$row['quantity'], 'std_price'=>$row['price'], 'price'=>$price, 'tax'=>$tax, 'discount_percent'=>$row['discount_percent'], 'created_time'=>$row['created_time']);
				$user_id = $row['user_id'];
			}
			$selected_class = count($item_data) ? ' pos_open_table' : '';
			$data = count($item_data) ? " data = '".htmlspecialchars(json_encode($item_data), ENT_QUOTES, 'UTF-8')."'" : '';
			$user = count($item_data) ? " user = ".$user_id : '';

			echo "<div class='pos_table_box".$selected_class."' table=".$i.$user.$data."><span>"._('Table')."</span><center>".$i."</center></div>";
		}
		echo "</div>";
	}
	echo "<div id='retail_items_container'>";
	
	while($row = db_fetch($result)) {
	
		if (file_exists($stock_img_path.$row['item_code'].".jpg"))
			$stock_img_link = "<img id='stock_img_".$row['item_code']."' alt = '[".$row['item_code'].".jpg"."]' src='".$stock_img_path.$row['item_code'].".jpg?nocache=".rand()."'>";
		else
			$stock_img_link = '';

		$user_pos = $_SESSION['PosItems']->pos;
		$low_stock = get_qoh_on_date($row['item_code'], $user_pos['pos_location']) <= 0 ? 'low_stock' : '';
		$item_qty = $row['is_foreign'] == 1 ? $row['quantity'] : 1;
		$price = get_pos_item_price_after_taxes($row['stock_id'], $row['price'], $tax_included);
		$tax = $price == $row['price'] ? 0 : (($price - $row['price']) / ($row['price']/100))/100;

		if($row['kit'] == 0 && $row['item_code'] == $row['stock_id'])
			echo "<div id='pos_item_".$row['item_code']."' class='pos_item_box ".$low_stock." hide_menu' data = '".$row['item_code']."' kit = '".$row['kit']."' isForeign = '".$row['is_foreign']."' ItemCode = '".$row['item_code']."' unit='".$row['units']."'><span class='pos_item_desc'>".$row['description']."</span>".$stock_img_link."<span class='pos_item_price item_price'>".price_format($row['price'])."/".$row['units']."</span><i data = '".$row['stock_id']."' std_price = '".$row['price']."' price='".$price."' tax='".$tax."' unit='".$row['units']."' quantity = '".$item_qty."' desc = '".$row['description']."' hidden></i></div>";
		else {
			$kit = get_item_kit($row['item_code']);
			$kit_price = get_pos_item_price($row['item_code']);
			if($kit_price == 0)
				$kit_price = $row['price'];
			$factor = $row['price'] ? $kit_price/$row['price'] : 1;

			echo "<div id='pos_item_".$row['item_code']."' class='pos_item_box ".$low_stock."' kit = '".$row['kit']."' foreignCode = '".$row['item_code']."' data='".$row['item_code']."'><span class='pos_item_desc'>".$row['description']."</span>".$stock_img_link."<span class='pos_item_price item_price'>".price_format($kit_price).'/'._('Kit')."</span>";

			while($item = db_fetch($kit)) {
				$std_price = get_pos_item_price($item['stock_id']);
				$item_price = round2($std_price * $factor, user_price_dec());
				$price2 = get_pos_item_price_after_taxes($item['stock_id'], $item_price, $tax_included);
				$tax2 = $price2 == $item_price ? 0 : (($price2 - $item_price) / ($item_price/100))/100;
				echo "<i data = '".$item['stock_id']."' std_price = '".$item_price."' price='".$price2."' tax='".$tax2."' unit='".$item['units']."' quantity = '".$item['quantity']."' desc = '".$item['comp_name']."' hidden></i>";
			}

			echo "</div>";
		}
	}

	echo "</div>";
	echo "<center id='code_input_hint'>"._('Items with Red border have zero or negative quantity in stock.')."</center>";
}

function calculator_panel() {
	global $pref, $path_to_root;

	echo "<div id='pos_bill'>";

	start_table(TABLESTYLE_NOBORDER, "id='pos_bill_table'");
	$th = array(
		_('Item')."<span class='pos_check_all' id='pos_select_all_items' hidden>"._('Check All')."</span><span class='pos_check_all' id='pos_uncheck_all_items' hidden>"._('Uncheck All')."</span>", 
		_('Qty'), 
		_('Line total')
	);
	table_header($th);
	end_table();

	echo "</div>";
	
	start_table(TABLESTYLE_NOBORDER, "id='pos_bill_footer'");
	start_row();
	echo "<th>"._('TOTAL ORDER :')."</th><th id='bill_total'></th>";
	end_row();
	end_table();

	if($pref['pos_restaurant_mode'] == '1') {
		echo "<div id='transfer_table'>";
		echo "<div id = 'btn_transfer_select' class='transfer_merge_blur'>"._('Select Items')."</div>";
		echo "<div id = 'btn_to_table' class='transfer_merge_blur'>"._('Transfer To')."</div>";
		echo "<div id = 'btn_cancel_select' class='transfer_merge_blur'>"._('Cancel Transfer')."</div>";
		echo "</div>";
	}

	start_table(TABLESTYLE_NOBORDER, "id='customer_select'");
	start_row();
	
	echo "<td><img src=".$path_to_root."/modules/pos/css/full_screen.png id='pos_menu_toggle' title='"._('Full Screen')."' alt='full screen' width=20/></td>";
	end_row();
	start_row();
	echo "<td align=center>";
	echo customer_list('customer_id', $pref['pos_def_customer'], false, false, false, true);
	hidden('branch_id', $_POST['customer_id']);
	echo "</td>";
	end_row();
	start_row();
	echo "<td><div class='pos_add_btn' id='process_order'>"._('Process Order')."</div></td>";
	end_row();
	end_table();

	start_table(TABLESTYLE2, "id='pos_calculator'");
	start_row();
	echo "<td class='pos_cal_btn' btn='1'>"._('1')."</td>";
	echo "<td class='pos_cal_btn' btn='2'>"._('2')."</td>";
	echo "<td class='pos_cal_btn' btn='3'>"._('3')."</td>";
	echo "<td class='pos_cal_btn' btn='qty'>"._('Qty')."</td>";
	end_row();
	start_row();
	echo "<td class='pos_cal_btn' btn='4'>"._('4')."</td>";
	echo "<td class='pos_cal_btn' btn='5'>"._('5')."</td>";
	echo "<td class='pos_cal_btn' btn='6'>"._('6')."</td>";
	echo "<td class='pos_cal_btn' btn='disc'>"._('Disc')."</td>";
	end_row();
	start_row();
	echo "<td class='pos_cal_btn' btn='7'>"._('7')."</td>";
	echo "<td class='pos_cal_btn' btn='8'>"._('8')."</td>";
	echo "<td class='pos_cal_btn' btn='9'>"._('9')."</td>";
	echo "<td class='pos_cal_btn' btn='price'>"._('Price')."</td>";
	end_row();
	start_row();
	echo "<td class='pos_cal_btn' btn='00'>"._('00')."</td>";
	echo "<td class='pos_cal_btn' btn='0'>"._('0')."</td>";
	echo "<td class='pos_cal_btn' btn='.'>.</td>";
	echo "<td class='pos_cal_btn' btn='del'>&larr;</td>";
	end_row();

	end_table();
}

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

if(isset($_POST['update']))
	$Ajax->activate('_page_body');

if (isset($_POST['process_payment'])) {

	$so_type = $_SESSION['PosItems']->so_type;
	$_SESSION['PosItems']->payment = pos_default_payment_term();

	$order_obj = serialize($_SESSION['PosItems']);

	if (!$SysPrefs->allow_negative_stock() && ($low_stock = $_SESSION['PosItems']->check_qoh())) {
		display_error(_("This document cannot be processed because there is insufficient quantity for items marked."));
		return false;
	}

	$ret = $_SESSION['PosItems']->write(1);
	if ($ret == -1) {
		display_error(_('The entered reference is already in use.'));
		$ref = $Refs->get_next($_SESSION['PosItems']->trans_type, null, array('date' => Today()));
		if ($ref != $_SESSION['PosItems']->reference) {
			unset($_POST['ref']); // force refresh reference
			display_error(_('The reference number field has been increased. Please save the document again.'));
		}
		set_focus('ref');
	}
	elseif($ret == 0) {
		unset($_SESSION['PosItems']);
		$_SESSION['PosItems'] = unserialize($order_obj);

		pos_meta_forward($_SERVER['PHP_SELF'], 'Reload=Yes');
	}
	else
		complete_order($so_type);
}

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

start_form();

echo "<div class='pos_wrapper'>";
echo "<div class='pos_body_left'>";
list_catogries();
list_stocks($category);
set_focus('itemCode');

echo "<p><b>";
echo "</b></p>";
echo "</div>";
echo "<div class='pos_body_right'>";
calculator_panel();
echo "</div>";

include_once($path_to_root.'/modules/pos/includes/ui/pos_payment.inc');

echo "</div>";

echo "<script type='text/javascript' src='".$path_to_root."/modules/pos/js/jquery-check.js'></script>";
echo "<script type='text/javascript' src='".$path_to_root."/modules/pos/js/pos.js'></script>";

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