<?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_PURCHASE_ANALAYSIS_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_purchase_analaysis();

// function getTaxTransactions($from, $to, $stock_id, $order_num, $batch_no , $item_group){
// 	$fromdate = date2sql($from);
// 	$todate = date2sql($to);
// 	$sql = " SELECT wo.*, sm.*, stm.* FROM ".TB_PREF."workorders as wo, ".TB_PREF."stock_moves as sm, ".TB_PREF."stock_master as stm, ".TB_PREF."wo_manufacture as wom WHERE wom.workorder_id=wo.id AND wom.id=sm.trans_no AND sm.type=29  AND stm.stock_id=sm.stock_id";
// 			 $sql .= " AND wo.date_ >=".db_escape($fromdate)." AND wo.date_<=".db_escape($todate);
// 			 if ($stock_id != '')
// 			 $sql .= " AND sm.stock_id =".db_escape($stock_id);
// 			if ($order_num != '')
// 			 $sql .= " AND wo.id =".db_escape($order_num);
// 			if ($batch_no != '')
// 			 $sql .= " AND sm.batch_no =".db_escape($batch_no);
// 			if ($item_group != '')
// 			 $sql .= " AND stm.item_group_id =".db_escape($item_group);
// 			 // display_error($sql);
// 			 $result = db_query($sql);
// 			 return $result;
// }
// new 
function get_purchase_analaysis_report($from, $to, $location = '', $stock_id='', $fromsupp='')
{
	// $fromdate = date2sql($from);
	// $todate = date2sql($to);

	// $before_date = date2sql($BeforeDate);
	// $after_date = date2sql($AfterDate);
	// if($exp_date == null)
	// 	$exp_date = Today();
	// $exp_date = date2sql($exp_date);

	$from = date2sql($from);
	$to = date2sql($to);

	
	
  	$sql = "SELECT sm.*, SUM(pod.unit_price * pod.quantity_ordered) as total , SUM(pod.quantity_ordered) as qty";

	// if(!$StockLocation) {
	// 	 $sql .= ", move.loc_code";
	// }
  	$sql.=    " FROM ".TB_PREF."purch_orders po
				LEFT JOIN ".TB_PREF."purch_order_details pod ON po.order_no=pod.order_no
				LEFT JOIN ".TB_PREF."stock_master sm ON pod.item_code=sm.stock_id
		WHERE  stock_id!=''  	AND po.ord_date>='$from'
		AND po.ord_date<='$to' ";

  	if ($location !='') {
    	$sql.= " AND po.into_stock_location=".db_escape($location);
	}else{
			if ($_SESSION["wa_current_user"]->to_location!='')
		 $sql.=" AND  po.into_stock_location IN (".$_SESSION["wa_current_user"]->to_location.") ";
	}
	// new

		 if ($stock_id != '')
			 $sql .= " AND pod.stock_id =".db_escape($stock_id);

			 if ($fromsupp != '')
			 $sql .= " AND po.supplier_id =".db_escape($fromsupp);

			
	
  $sql .="  GROUP BY sm.stock_id ORDER BY  po.ord_date,sm.stock_id ";
	// display_error($sql);
  	return db_query($sql, "could not query stock moves");
}

function get_items_name($stock_id)
{
	$sql = "SELECT description FROM ".TB_PREF."stock_master WHERE stock_id=".db_escape($stock_id);
	// display_error($sql);
	$result = db_query($sql);
	$row = db_fetch_row($result);
	return is_array($row) ? $row[0] : false;
}

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

function print_purchase_analaysis()
{
	global $path_to_root;
	
		$from = $_POST['PARAM_0'];
		$to = $_POST['PARAM_1'];
		$stock_id = $_POST['PARAM_2'];
		$fromsupp = $_POST['PARAM_3'];
		$location = $_POST['PARAM_4'];
		$po_no = $_POST['PARAM_5'];
		$orientation = $_POST['PARAM_6'];
		$destination = $_POST['PARAM_7'];
	// $from = $_POST['PARAM_0'];
	// $to = $_POST['PARAM_1'];
	// $batch_no = $_POST['PARAM_4'];
	// $item_group = $_POST['PARAM_5'];

	

	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 ($fromsupp == ALL_TEXT)
		$supp = _('All');
	else
		$supp = get_supplier_name($fromsupp);

	

	$rep = new FrontReport(_('Purchase Analaysis Report'), "PurchasAnalaysisReport", 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 Stock'),'from' => $stock_id,'to' => ''),
						4 =>  array('text' => _('Supplier'), 'from' => $supp, 'to' => ''),
						// 2 => array( 'text' => _('Customer Id'),'from' => $cust,'to' => ''),
						// 4 => array( 'text' => _('Sales Person'),'from' => $sale_Prsn,'to' => ''),
						// 6 => array( 'text' => _('Items Group'),'from' => $item_group,'to' => ''),
						// 7 => array( 'text' => _('Sales Type'),'from' => $type,'to' => '')
					);
						

	$cols = array(0, 300, 380, 490, 560); //, 680

	$headers = array(_('Item Details'),_('Unit'), _('Purc. Qty'), _('Purc. Amt'));
	$aligns = array('left', 'left',  'left', 'left', 'right'); //, 'left'
    if ($orientation == 'L')
    	recalculate_cols($cols);

	$rep->Font();
	$rep->Info($params, $cols, $headers, $aligns);
	$rep->NewPage();
	
	$totalnet = 0.0;
	$transactions = get_purchase_analaysis_report($from, $to, $location ,$stock_id, $fromsupp);

	$rep->NewLine(2);

	$total_qty = 0;
	$dec=2;
	$total_amt = 0;
	while ($trans=db_fetch($transactions))
	{
			
			
				$oldrow = $rep->row;
				$rep->TextColLines(0, 1, $trans['description'], -2);
				$newrow = $rep->row;
				$rep->row = $oldrow;
				$rep->TextCol(1, 2, $trans['units']);


			
				$rep->AmountCol(2, 3,	$trans["qty"],$dec);
				$rep->AmountCol(3, 4,	$trans["total"],$dec);
		
				$rep->row = $newrow;


              $total_qty+=	$trans["qty"];

              $total_amt+=	$trans["total"];
				
//-------------------------------------------------------------------------------------------------------------------------------------------
				
				// $rep->NewLine();

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

	$rep->Font('bold');
	$rep->NewLine();
	$rep->Line($rep->row + $rep->lineHeight);
	$rep->TextCol(0, 2,	_("Total"));
	$rep->AmountCol(2, 3, $total_qty, $dec);
	$rep->AmountCol(3, 4, $total_amt, $dec);
	$rep->Line($rep->row - 5);
	$rep->Font();
	$rep->End();
}

