<?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_REP_INVENTORY_MOVEMENT';
// ----------------------------------------------------------------
// $ Revision:	2.0 $
// Creator:	Joe Hunt
// date_:	2005-05-19
// Title:	Sales Summary Report
// ----------------------------------------------------------------
$path_to_root="..";

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 . "/gl/includes/gl_db.inc");

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


print_sales_summary_report();

function get_stock_movements_reports($stock_id, $StockLocation, $AfterDate,	$BeforeDate)
{
	$before_date = date2sql($BeforeDate);
	$after_date = date2sql($AfterDate);
	
  	$sql = "SELECT move.*, IF(ISNULL(supplier.supplier_id), debtor.name, supplier.supp_name) name";

	if(!$StockLocation) {
		 $sql .= ", move.loc_code";
	}
  	$sql.=    " FROM ".TB_PREF."stock_moves move
				LEFT JOIN ".TB_PREF."supp_trans credit ON credit.trans_no=move.trans_no AND credit.type=move.type
				LEFT JOIN ".TB_PREF."grn_batch grn ON grn.id=move.trans_no AND 25=move.type
				LEFT JOIN ".TB_PREF."suppliers supplier ON IFNULL(grn.supplier_id, credit.supplier_id)=supplier.supplier_id
				LEFT JOIN ".TB_PREF."debtor_trans cust_trans ON cust_trans.trans_no=move.trans_no AND cust_trans.type=move.type
				LEFT JOIN ".TB_PREF."debtors_master debtor ON cust_trans.debtor_no=debtor.debtor_no
		WHERE";

  	if ($StockLocation!='') {
    	$sql.= " move.loc_code=".db_escape($StockLocation)." AND";
	}else{
			if ($_SESSION["wa_current_user"]->to_location!='')
		 $sql.="  move.loc_code IN (".$_SESSION["wa_current_user"]->to_location.") AND";
	}

	$sql.= " move.tran_date >= '". $after_date . "'
		AND move.tran_date <= '" . $before_date . "'
		AND move.stock_id = ".db_escape($stock_id) . " ORDER BY move.tran_date, move.trans_id";

  	return db_query($sql, "could not query stock moves");
}

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

function print_sales_summary_report()
{
	global $path_to_root;
	
	$from = $_POST['PARAM_0'];
	$to = $_POST['PARAM_1'];
	$location = $_POST['PARAM_2'];
	$stock_id = $_POST['PARAM_3'];
	$comments = $_POST['PARAM_4'];
	$orientation = $_POST['PARAM_5'];
	$destination = $_POST['PARAM_6'];

	if(!$stock_id){
		display_error(_("Item must be select for check inventory movement report."));
		exit();
	}

	if ($destination)
		include_once($path_to_root . "/reporting/includes/excel_report.inc");
	else
		include_once($path_to_root . "/reporting/includes/pdf_report.inc");
	$orientation = ($orientation ? 'L' : 'P');

	if ($location == '')
		$loc = _('All');
	else
		$loc = get_location_name($location);
	if ($stock_id == '')
			$itm = _('All');
		else
			$itm = $stock_id;
	
	$rep = new FrontReport(_('Inventory Item Movement'), "InventoryReport", user_pagesize(), 9, $orientation);

    $params =   array( 	0 => $comments,
    				    1 => array('text' => _('Period'),'from' => $from, 'to' => $to),
    				    2 => array('text' => _('Location'), 'from' => $loc, 'to' => ''),
    				    3 => array('text' => _('Item'), 'from' => $itm, 'to' => ''));

	$cols = array(0, 90, 150, 210, 260, 330, 400, 455, 510);

	$headers = array(_("Type"), _("Reference"), _('Location'), _("Date"), _("Detail"), _("Batch No"), _("Qty In"), _("Qty Out"), _("Qty On Hand"));
	$aligns = array('left', 'left', 'left', 'left', 'left', 'left', 'left', 'left','left');
    if ($orientation == 'L')
    	recalculate_cols($cols);

	$rep->Font();
	$rep->Info($params, $cols, $headers, $aligns);
	$rep->NewPage();
	
	$transactions = get_stock_movements_reports($stock_id, $location, $from, $to);
	$before_qty = get_qoh_on_date($stock_id, $location, add_days($from, -1));
	$after_qty = $before_qty;
	$rep->Font('bold');
	$rep->TextCol(1, 4,	 _("Quantity on hand before"). " " . $from);	
	$rep->TextCol(8, 9,	 number_format2($before_qty, $dec));	
	$rep->Font();
	$rep->NewLine(2);
	$newrow=array();
	while ($trans=db_fetch($transactions))
	{	
		global $systypes_array;

		$type_name = $systypes_array[$trans["type"]];
		$trandate = sql2date($trans["tran_date"]);
		if ($trans["qty"] > 0)
		{
			$quantity_formatted = number_format2($trans["qty"], $dec);
			$total_in += $trans["qty"];
		}
		else
		{
			$quantity_formatted = number_format2(-$trans["qty"], $dec);
			$total_out += -$trans["qty"];
		}
		$after_qty += $trans["qty"];

		$rep->TextCol(0, 1,	$type_name, -2);	
		$rep->TextCol(1, 2,	$trans["reference"]);		
		$oldrow2 = $rep->row;
		$rep->TextColLines(2, 3,	get_item_location($trans['loc_code'])['location_name']);	
		$newrow[] = $rep->row;
		$rep->row = $oldrow2;
		$rep->TextCol(3, 4,	$trandate);	
		$oldrow = $rep->row;
		$rep->TextColLines(4, 5,	$trans['name']);	
		$newrow[] = $rep->row;
		$rep->row = $oldrow;
		$rep->TextCol(5, 6,	$trans['batch_no']);	

		$rep->TextCol(6, 7,	(($trans["qty"] >= 0) ? $quantity_formatted : '-'));	
		$rep->TextCol(7, 8,	(($trans["qty"] < 0) ? $quantity_formatted : '-'));	
		$rep->TextCol(8, 9,	$after_qty);	
		$rep->row = min($newrow);
        unset($newrow);

		if ($rep->row < $rep->bottomMargin + $rep->lineHeight)
		{
			$rep->Line($rep->row - 2);
			$rep->NewPage();
		}
	}

	$rep->Font('bold');
	$rep->NewLine();
	$rep->TextCol(1, 4,	 _("Quantity on hand after"). " " . $to);	
	$rep->TextCol(8, 9,	 number_format2($after_qty, $dec));	
	$rep->Font();
	$rep->End();
}

