<?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_SALESTRANSVIEW';

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/date_functions.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 . "/inventory/includes/db/items_category_db.inc");

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

print_shift_revenue_list();

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

function GetPosSalesTrans($from, $to, $shift=false, $pos_id=false) {

	$sql = "SELECT DISTINCT trans.*,
			ov_amount+ov_discount+ov_gst AS InvoiceTotal,
			cust.name AS DebtorName,
			cust.curr_code,
			pos.pos_name,
			sorder.customer_ref,
			pt.*, 
			shift.* 
		FROM ".TB_PREF."debtor_trans trans,
			 ".TB_PREF."debtors_master cust,
			 ".TB_PREF."sales_orders sorder,
			 ".TB_PREF."cust_branch branch,
			 ".TB_PREF."pos_trans pt, 
			 ".TB_PREF."pos_shift shift, 
			 ".TB_PREF."sales_pos pos 
		WHERE sorder.order_no=trans.order_
		    AND sorder.branch_code = branch.branch_code
		    AND sorder.trans_type = ".ST_SALESORDER."
		    AND trans.trans_no = pt.trans_no
		    AND trans.debtor_no = cust.debtor_no
		    AND (trans.type=".ST_SALESINVOICE." OR trans.type=".ST_CUSTCREDIT.")
		    AND TIME_FORMAT(pt.trans_time, '%H:%i:%s') BETWEEN shift.start_time AND shift.end_time 
		    AND pos.id = pt.pos_id 
		    AND trans.tran_date >= '".date2sql($from)."'
		    AND trans.tran_date <= '".date2sql($to)."'";
		if(!empty($shift))
			$sql .= " AND shift.id = ".db_escape($shift);
		if(!empty($pos_id))
			$sql .= " AND pt.pos_id = ".db_escape($pos_id);

		$sql .= " ORDER BY trans.trans_no, trans.tran_date";

	return db_query($sql, 'Error getting order details');
}

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

function print_shift_revenue_list() {
	global $path_to_root, $security_areas;

	$shift = $_POST['PARAM_0'];
	$sales_point = $_POST['PARAM_1'];
	$from = $_POST['PARAM_2'];
	$to = $_POST['PARAM_3'];
	$zeros = $_POST['PARAM_4'];
	$comments = $_POST['PARAM_5'];
	$orientation = $_POST['PARAM_6'];

	$all_shifts = get_pos_shifts($shift);
	$pos_row = get_sales_point($sales_point);

	include_once($path_to_root.'/reporting/includes/pdf_report.inc');

	$orientation = ($orientation ? 'L' : 'P');

	$dec = user_price_dec();

	$cols = array(0, 45, 100, 280, 370, 450, 515);

	$headers = array(_('Trans#'), _('Type'), _('Customer'), _('POS'),
		_('Inv Date'),	_('Total'));

	$aligns = array('left', 'left',	'left', 'left', 'left', 'right');

    $params = array(0 => $comments,
	    			1 => array('text' => _('Period'), 'from' => $from, 'to' => $to),
	    			2 => array('text' => _('Shift'),'from' => $shift == 0 ? _('All Shifts') : $all_shifts['shift_name'], 'to' => ''),
	    			3 => array('text' => _('Sales Point'), 'from' => $sales_point == 0 ? _('All sales points') : $pos_row['pos_name'], 'to' => '')
	    		);

	$rep = new FrontReport(_('Shift Revenue Listing'), "shiftListning", user_pagesize(), 9, $orientation);

    if ($orientation == 'L')
    	recalculate_cols($cols);

	$rep->Font();
	$rep->Info($params, $cols, $headers, $aligns);

	$rep->NewPage();

	$subtotal = 0;
	$total = 0;
	$temp = 0;

	$result = GetPosSalesTrans($from, $to, $shift, $sales_point);

	foreach($all_shifts as $k=>$shift_row) {

		foreach($result as $myrow) {

			$trans_time = strtotime(explode(' ', $myrow['trans_time'])[1]);

			if($trans_time >= strtotime($shift_row['start_time']) && $trans_time <= strtotime($shift_row['end_time'])) {
				if($myrow['type'] == ST_SALESINVOICE)
					$temp += $myrow['InvoiceTotal'] * $myrow['rate'];
				else
					$temp -= $myrow['InvoiceTotal'] * $myrow['rate'];
			}
		}

		if($temp == 0 && $zeros == 0)
			continue;

		$rep->NewLine(0, 2, false, $k);
		$rep->Font('bold');
		$rep->TextCol(0, 2,	$shift_row['shift_name']);
		$rep->AmountCol(5, 6, $temp, $dec);
		$rep->Font();
		$rep->NewLine();

		foreach($result as $myrow) {

			$trans_time = strtotime(explode(' ', $myrow['trans_time'])[1]);

			if($trans_time >= strtotime($shift_row['start_time']) && $trans_time <= strtotime($shift_row['end_time'])) {

				$amt = $myrow['InvoiceTotal'] * $myrow['rate'];

				if($myrow['type'] == ST_CUSTCREDIT)
					$amt = -$amt;

				$rep->TextCol(0, 1,	$myrow['trans_no']);
				$rep->TextCol(1, 2,	$myrow['type'] == ST_SALESINVOICE ? _('Invoice') : _('Return'));
				$rep->TextCol(2, 3,	$myrow['DebtorName']);
				$rep->TextCol(3, 4,	$myrow['pos_name']);
				$rep->DateCol(4, 5,	$myrow['tran_date'], true);
				$rep->AmountCol(5, 6, $amt, $dec);
				$rep->NewLine();

				$subtotal += $amt;
			}
		}

		$rep->Line($rep->row+5);
		$rep->NewLine();
		$total += $subtotal;
		$subtotal = 0;
		$temp = 0;
	}

	$rep->fontSize += 2;
	$rep->Font('bold');
	$rep->TextCol(0, 3, _('Grand Total'));
	$rep->fontSize -= 2;
	$rep->AmountCol(5, 6, $total, $dec);
	$rep->Line($rep->row  - 4);
	$rep->NewLine();
	$rep->Font();
	$rep->End();
}

