<?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>.
***********************************************************************/
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/banking.inc");
include_once($path_to_root . "/includes/inventory.inc");

include_once($path_to_root . "/inventory/includes/db/items_category_db.inc");
include_once($path_to_root . "/inventory/includes/db/items_trans_db.inc");
include_once($path_to_root . "/inventory/includes/db/items_prices_db.inc");
include_once($path_to_root . "/inventory/includes/db/items_purchases_db.inc");
include_once($path_to_root . "/inventory/includes/db/items_codes_db.inc");
include_once($path_to_root . "/inventory/includes/db/items_db.inc");
include_once($path_to_root . "/inventory/includes/db/items_locations_db.inc");
include_once($path_to_root . "/inventory/includes/db/items_adjust_db.inc");
include_once($path_to_root . "/inventory/includes/db/items_transfer_db.inc");
include_once($path_to_root . "/inventory/includes/db/items_units_db.inc");
include_once($path_to_root . "/inventory/includes/db/item_packing_unit_db.inc");

function item_img_name($stock_id)
{
	$stock_id = strtr($stock_id, "><\\/:|*?", '________');
	return clean_file_name($stock_id);
}

function get_stock_movements($stock_id, $StockLocation,	$BeforeDate, $AfterDate, $batch_no=null, $filterType=null, $exp_date=null)
{
	$before_date = date2sql($BeforeDate);
	$after_date = date2sql($AfterDate);
	if($exp_date == null)
		$exp_date = Today();
	$exp_date = date2sql($exp_date);
	
	
  	$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";
	}


	if($batch_no)
		$sql .= " move.batch_no LIKE " . db_escape("%" . $batch_no. "%") . " AND";

	if($filterType){
		if($filterType == 1)
			$sql .=" move.exp_date >= ". db_escape($exp_date). "	AND ";
		elseif($filterType == 2)
			$sql .=" move.exp_date <= ". db_escape($exp_date) . "	AND ";
		elseif($filterType == 3)
			$sql .=" move.exp_date <> ". db_escape($exp_date) . "	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 get_batch_movements($stock_id, $batch_no=null, $filterType=null, $exp_date=null, $loc_code=null) {
	
	if($exp_date == null)
		$exp_date = Today();
	$exp_date = date2sql($exp_date);
	
  	$sql = "SELECT move.*, IF(ISNULL(supplier.supplier_id), debtor.name, supplier.supp_name) name 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 1 ";
  	
	if($batch_no)
		$sql .= " AND move.batch_no LIKE " . db_escape("%" . $batch_no. "%");
	if($loc_code != null)
		$sql .=" AND move.loc_code = ".db_escape($loc_code);
	else{
			if ($_SESSION["wa_current_user"]->to_location!='')
		 $sql.=" AND move.loc_code IN (".$_SESSION["wa_current_user"]->to_location.") ";
	}


	if($filterType){

		if($filterType == 1)
			$sql .=" AND move.tran_date >= '". $exp_date . "' ";
		elseif($filterType == 2)
			$sql .="AND move.tran_date <= '". $exp_date . "'	 ";
		elseif($filterType == 3)
			$sql .=" AND move.tran_date <> '". $exp_date . "' ";
	}	
	
	$sql.= " AND move.stock_id = ".db_escape($stock_id) . " ORDER BY move.tran_date, move.trans_id";
	//display_error($sql);
  	return db_query($sql, "could not query stock moves");
}

function calculate_reorder_level($location, $line, &$st_ids, &$st_names, &$st_num, &$st_reorder)
{
	$sql = "SELECT stock.*, loc.location_name, loc.email
		FROM ".TB_PREF."loc_stock stock,"
			.TB_PREF."locations loc
		WHERE stock.loc_code=loc.loc_code
		AND stock.stock_id = '" . $line->stock_id . "'
		AND stock.loc_code = '" . $location . "'";
	$res = db_query($sql,"a location could not be retreived");
	$loc = db_fetch($res);
	if ($loc['email'] != "")
	{
		$qoh = get_qoh_on_date($line->stock_id, $location);
		$qoh -= get_demand_qty($line->stock_id, $location);
		$qoh -= get_demand_asm_qty($line->stock_id, $location);
		$qoh -= $line->quantity;
		if ($qoh < $loc['reorder_level'])
		{
			$st_ids[] = $line->stock_id;
			$st_names[] = $line->item_description;
			$st_num[] = $qoh - $loc['reorder_level'];
			$st_reorder[] = $loc['reorder_level'];
		}
	}
	return $loc;
}

function send_reorder_email($loc, $st_ids, $st_names, $st_num, $st_reorder)
{
	global $path_to_root;

	require_once($path_to_root . "/reporting/includes/class.mail.inc");
	$company = get_company_prefs();
	$mail = new email($company['coy_name'], $company['email']);
	$to = $loc['location_name'] . " <" . $loc['email'] . ">";
	$subject = _("Stocks below Re-Order Level at " . $loc['location_name']);
	$msg = "\n";
	for ($i = 0; $i < count($st_ids); $i++)
		$msg .= $st_ids[$i] . " " . $st_names[$i] . ", " . _("Re-Order Level") . ": " . $st_reorder[$i] . ", " . _("Below") . ": " . $st_num[$i] . "\n";
	$msg .= "\n" . _("Please reorder") . "\n\n";
	$msg .= $company['coy_name'];
	$mail->to($to);
	$mail->subject($subject);
	$mail->text($msg);
	return $mail->send();
}

function delete_transfer_inquery($type, $trans_no)
{
	// display_error($trans_no);exit();
	$sql = "DELETE FROM ".TB_PREF."transfer_trans WHERE type=$type AND trans_no=" . db_escape($trans_no);
	// display_error($sql);
	db_query($sql, "Inventory transfer successfully deleted");
}


function get_sql_for_transfer_inquiry($loc_code, $from, $to, $approed=false, 
	$StkLocation='', $receive_loc='', $reference='',$stock_id='')
{
	// display_error($StkLocation.'=='.$receive_loc);exit();




// $sql = "SELECT loc_from.trans_no ,loc_from.reference ,loc_from.tran_date ,loc_from.from_name, loc_to.to_name  ,loc_from.from_loc, loc_to.to_loc 
// 		 FROM	
// 		  (SELECT trans_no, type, tran_date, reference, move.loc_code as from_loc, loc.location_name as from_name
// 			FROM ".TB_PREF."stock_moves move
// 				LEFT JOIN ".TB_PREF."locations loc ON loc.loc_code=move.loc_code
// 			WHERE type=".ST_LOCTRANSFER." AND   tran_date >= '" . date2sql($from) . "'
// 			AND tran_date <= '" . date2sql($to) . "'  AND qty<0  GROUP BY trans_no) loc_from,

// 		(SELECT trans_no, move.loc_code as to_loc, loc.location_name as to_name
// 			FROM ".TB_PREF."stock_moves move
// 				LEFT JOIN ".TB_PREF."locations loc ON loc.loc_code=move.loc_code
// 			WHERE type=".ST_LOCTRANSFER."  AND tran_date >= '" . date2sql($from) . "'
// 			AND tran_date <= '" . date2sql($to) . "'   AND qty<0   GROUP BY trans_no ) loc_to WHERE  loc_from.trans_no=loc_to.trans_no ";

 $sql ="SELECT sm.trans_no,sm.reference,sm.tran_date,tt.from_loc,tt.to_loc FROM ".TB_PREF."stock_moves sm LEFT JOIN ".TB_PREF."transfer_trans tt ON sm.trans_no=tt.trans_no AND sm.type=tt.type AND  sm.type=".ST_LOCTRANSFER." WHERE   sm.tran_date >= '" . date2sql($from) . "' AND sm.tran_date <= '" . date2sql($to) . "' AND sm.qty<>0";

//   if ($StkLocation == '' && $receive_loc == '')
//   {


     if ($_SESSION["wa_current_user"]->location!='' && $_SESSION["wa_current_user"]->to_location)
      $sql.=" AND ( tt.from_loc IN (".$_SESSION["wa_current_user"]->location.") OR  tt.to_loc  IN (".$_SESSION["wa_current_user"]->location.") ) ";


// 	if ($_SESSION["wa_current_user"]->location!='')
// 		 $sql.=" AND ( tt.from_loc IN (".$_SESSION["wa_current_user"]->to_location.") OR  tt.to_loc  IN (".$_SESSION["wa_current_user"]->to_location.") ) ";
// 	if ($_SESSION["wa_current_user"]->location!='')
// 		  $sql.=" OR ( tt.from_loc IN (".$_SESSION["wa_current_user"]->location.") OR tt.to_loc IN (".$_SESSION["wa_current_user"]->location.") ) ";
//   }
   


	if ($reference != "")
	{
		$sql .= " AND sm.reference LIKE ".db_escape("%". $reference . "%");
	}else{

	if ($StkLocation != '')
    $sql .= " AND tt.from_loc = ".db_escape($StkLocation);

	if ($receive_loc != '')
    $sql .= " AND tt.to_loc = ".db_escape($receive_loc);

	}


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



    $sql .= " GROUP BY sm.trans_no";
//  	display_error($sql);

// print_r($_SESSION['wa_current_user']->location);
			// $user_loc = explode(',', $_SESSION['wa_current_user']->location);
			// display_error(count($user_loc));

	// if ($order)
	// {
	// 	$sql .= " AND reference LIKE ".db_escape("%". $order . "%");
	// } else {

	// 	if ($dim == 1)
	// 		$sql .= " AND type_=1";

	// 	if ($open)
	// 		$sql .= " AND closed=0";

	// 	if ($type > 0)
	// 		$sql .= " AND type_=".db_escape($type);

	// 	if ($overdue)
	// 	{
	// 		$today = date2sql(Today());

	// 		$sql .= " AND due_date < '$today'";
	// 	}

	// }
			// display_error($sql);
	return $sql;
}