<?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_AGING_REPORT';
// ----------------------------------------------------------------
// $ 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_Inventory_Aging_report();

function getInventoryAgingReport($from, $stock_id, $location, $stock_category_id)
{
	// display_error($stock_category_id);
	$date = date2sql($from);
	// $fromdate = date2sql($from);
	// $todate = date2sql($to);

	$sql = "SELECT item.category_id,
			category.description AS cat_description,
			item.stock_id,
			item.units,
			item.description, item.inactive,
			move.loc_code,
			move.tran_date,
			move.qty,
			move.price,
			move.batch_no,
			category.dflt_units,
			SUM(move.qty) AS QtyOnHand, 
			item.material_cost AS UnitCost,
			move.price,
			SUM(move.qty) * item.material_cost AS ItemTotal";
			// if($kv_batch)
				$sql .= ", move.batch_no";
			// elseif($kv_exp_date)
			// 	$sql .= ", move.batch_no, move.exp_date";
		$sql .="	FROM "
			.TB_PREF."stock_master item,"
			.TB_PREF."stock_category category,"
			.TB_PREF."stock_moves move
		WHERE item.stock_id=move.stock_id
		AND item.category_id=category.category_id
		AND item.mb_flag<>'D' AND mb_flag <> 'F' 
		AND move.tran_date <= '$date' AND move.type!=16 ";
		if ($stock_id != '')
			$sql .= " AND move.stock_id = ".db_escape($stock_id);

		if ($stock_category_id != -1)
			$sql .= " AND category.category_id = ".db_escape($stock_category_id);
		


		if ($location != '')
			$sql .= " AND move.loc_code = ".db_escape($location);

		$sql .= " GROUP BY  move.stock_id , ";

		if ($location)
			$sql .= "move.loc_code, ";
		// if($kv_batch || $kv_exp_date)
			$sql .="move.batch_no";


		$sql .= "  HAVING ROUND(SUM(move.qty),4)!=0";

		// $sql .= " AND move.tran_date >=".db_escape($fromdate)." AND move.tran_date<=".db_escape($todate);

		$sql .= " ORDER BY move.tran_date";

	
    // display_error($sql);
    return db_query($sql,"No transactions were returned");
}

function get_qty_purch_manuf($stock_id, $batch_no)
{
	$sql = " SELECT * FROM ".TB_PREF."stock_moves WHERE stock_id=".db_escape($stock_id) ." AND batch_no=".db_escape($batch_no);
	$sql .= " AND qty !=0 ";
	$sql .= " ORDER BY tran_date,trans_id  ASC ";
	  // display_error($sql);
		// return db_query($sql,"No transactions were returned");
		$result = db_query($sql);
		return db_fetch($result);
}

  	

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

function print_Inventory_Aging_report()
{
	global $path_to_root;

	$from = $_POST['PARAM_0'];
	// $to = $_POST['PARAM_1'];
	$stock_id = $_POST['PARAM_1'];
	$location = $_POST['PARAM_2'];
	// display_error($location);
	$stock_category_id = $_POST['PARAM_3'];
	$days = $_POST['PARAM_4'];
	$orientation = $_POST['PARAM_5'];
	$destination = $_POST['PARAM_6'];

	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');
	$orientation = ($orientation ? 'L' : 'L');


	if ($stock_id == '')
		$stock = _('All');
	else
		$stock = get_item($stock_id)['description'];
	// display_error($stock);

	if ($location == '')
		$loc = _('All');
	else
		$loc = get_location_name($location);

	if ($stock_category_id == '')
		$cat = _('All');
	else
		$cat = get_category_name($stock_category_id);


	if ($days == '')
		$Day = _('All');
	else
		$Day = $days;

	$dec = user_price_dec();

	$rep = new FrontReport(_('Inventory Aging Report'), "InventoryAgingReport", user_pagesize(), 8, $orientation);

	$params =   array( 	0 => $comments,
						1 => array('text' => _('Period'), 'from' => $from, 'to' => $to),
						2 => array( 'text' => _('Item Name'),'from' => $stock,'to' => ''),
						3 => array( 'text' => _('Location'),'from' => $loc,'to' => ''),
						4 => array( 'text' => _('Stock Category'),'from' => $cat,'to' => ''),
						5 => array( 'text' => _('Days greater then'),'from' => $Day,'to' => ''),
						// 6 => array( 'text' => _('Items Group'),'from' => $item_group,'to' => ''),
						// 7 => array( 'text' => _('Sales Type'),'from' => $type,'to' => '')
					);

	$cols = array(0, 60, 170, 220, 280, 320, 380, 440, 480, 540, 600);

$headers = array(_('Date of P/M'), _('Item'), _('Location'), _('Batch NO'), _('QTY P/M'), _('Unit'), _('QOH'), _('Rate'), _('Invt Value in Hand'), _('Aging Days'));
	$aligns = array('left', 'left', 'left', 'left', 'center', 'center', 'left', 'left', 'left', 'left', 'left');
    if ($orientation == 'L')
    	recalculate_cols($cols);

	$rep->Font();
	$rep->Info($params, $cols, $headers, $aligns);
	$rep->NewPage();
	
	// $totalnet = 0.0;
	$transactions = getInventoryAgingReport($from, $stock_id, $location, $stock_category_id);

	$rep->NewLine(2);
	
	$amt_total = 0;
	$qty_total = 0;
	$dec=4;
	while ($trans=db_fetch($transactions))
	{
		// display_error($trans['description'].'=='. 'in');
		$data = Today();
				$qty_purchase = get_qty_purch_manuf($trans['stock_id'], $trans['batch_no']);
		$numberDays = date_diff2(sql2date($qty_purchase['tran_date']), $data, 'd');
		if ($days != '') {
			// display_error($days);
			if (abs($numberDays) < $days) 
			continue;
		}
		
				$rep->TextCol(0, 1, $trans['tran_date']);
                if ($destination)
                $rep->TextCol(1, 2, $trans['stock_id']." - ".$trans['description']);
                else{
                
                $oldrow = $rep->row;
                $rep->TextColLines(1, 2, $trans['stock_id']." - ".$trans['description']);
                $newrow = $rep->row;
                $rep->row = $oldrow;
                }
				$rep->TextCol(2, 3,	get_location_name($trans['loc_code']));
				$rep->TextCol(3, 4,	$trans['batch_no']);
				$rep->TextCol(4, 5,	number_format2($qty_purchase['qty'],$dec) );
				// $data = get_sales_parent_numbers(ST_SALESINVOICE, $trans['trans_no']);
				$rep->TextCol(5, 6, $trans['units']);
				$rep->TextCol(6, 7,	number_format2($trans['QtyOnHand'],$dec ) );
				$trans['price'] = get_betch_price($trans['batch_no'],$trans['stock_id'],true);
				$rep->TextCol(7, 8,	number_format2($trans['price'],$dec) );
				$inv_value = ($trans['price']*$trans['QtyOnHand']);
				// display_error($qty_purchase['qty'].'=='. 'dsfasd');
				$rep->TextCol(8, 9,	number_format2($inv_value,$dec) );
				$rep->TextCol(9, 10, abs($numberDays));
				// $total = $trans['']; //($trans['quantity']*$trans['unit_price']) * $trans['rate'] ;
				// $rep->AmountCol(10, 11, $total, $dec);
				if (!$destination)
				$rep->row = $newrow;


				
				$rep->NewLine();

				if ($rep->row < $rep->bottomMargin + $rep->lineHeight)
				{
					$rep->Line($rep->row - 2);
					$rep->NewPage();
				}
		
	$qty_purch += $qty_purchase['qty']; 
	$QOH_tot += $trans['QtyOnHand'];
	$price_total +=$inv_value;
	// display_error($amt_total);
	}

	$rep->Font('bold');
	$rep->NewLine();
	$rep->Line($rep->row + $rep->lineHeight);
	$rep->TextCol(0, 2,	_("Total"));
	$rep->AmountCol(4, 5, $qty_purch, $dec);
	$rep->AmountCol(6, 7, $QOH_tot, $dec);
	$rep->AmountCol(8, 9, $price_total, $dec);
	$rep->Line($rep->row - 5);
	$rep->Font();

	$rep->End();
}

