<?php
 include ("header.inc");
 include ("config.php");
 include ("style.css");
 include ("functions.inc");
 if (isset($_GET['sortby']))
 $sortwith = $_GET['sortby']; // this be the real magic
 else if (isset($sortby)) $sortwith = $sortby;
 else $sortwith = "units_sold";
 if (isset($_GET['partType']))
 $partType = $_GET['partType']; // this be the real magic
 
 if (isset($_GET['orderType']))
 $orderType = $_GET['orderType']; // this be the real magic
 
 if (isset($_GET['showsku']))
 $showsku = $_GET['showsku']; // this be the real magic
 
 if (isset($partType)) $showType = $partType;
 else $showType = "all";
 
 if (isset($orderType)) $showOrderType = $orderType;
 else $showOrderType = "all";
 
 if (isset($_GET['partSupplier']))
 $partSupplier = $_GET['partSupplier']; // this be the real magic
 
 if (isset($partSupplier)) $showSupplier = $partSupplier;
 else $showSupplier = "all";
 
//echo "show: " . $showType . "partType: " . $partType . "<br>";
//Inactive
if(isset($_GET['inactive_filter']) && $_GET['inactive_filter'] == 'Yes')
{
$inactive_checked = "checked";
$inactive_filter_cnd = " AND `parts`.`active` = 1 ";
}
else
{
$inactive_checked = "";
$inactive_filter_cnd = "";
}
//Weekly Sales filter
if(isset($_GET['weekly_filter']) && $_GET['weekly_filter'] == 'Yes')
{
$weekly_checked = "checked";
$weekly_filter_cnd = " AND `parts`.`weekly_units_sold` > 0 ";
}
else
{
$weekly_checked = "";
$weekly_filter_cnd = "";
}
if ($showType != "" && $showType != "all")
{
$show_type = "AND `parts`.`ProductType` = '$showType' ";
$messageHeader = "Type  - $showType";
}
else {
$show_type = "";
$messageHeader = "Type  - All";
}
if ($showOrderType != "" && $showOrderType != "all")
{
$show_order_type = "AND `parts`.`ordertype` = '$showOrderType' ";
$messageHeader .= " Order Type  - $showOrderType";	
}
else {
$show_order_type = "";
$messageHeader .= " Order Type  - All";
}
if ($showSupplier != "" && $showSupplier != "all")
{
	if ($showSupplier == "novendor")
	{
	$show_supplier = "AND (`parts`.`supplier` = '') "; 
	$messageHeader .= " Supplier  - No Set Supplier";
	}
	else
	{
	$show_supplier = "AND (`parts`.`supplier` = '$showSupplier') ";  // ||  `parts`.`supplier` = ''
	$messageHeader .= " Supplier  - $showSupplier";	
	}
}
else {
$show_supplier = "";
$messageHeader .= " Supplier - All";
}
 if (isset($_GET['showsku']) && $showsku != "") //	$show_sku = "AND `itemID` LIKE '%$showsku%' ";
{
	$show_sku = "AND (`parts`.`pnchina` LIKE '%$showsku%' ||  `parts`.`partno` LIKE '%$showsku%')";
$messageHeader .= " Search for - $showsku";
}
else 
{
$show_sku = "";
}
 if (isset($_GET['triger1']))
 $avg_sale_tr = $_GET['triger1'];
 else $avg_sale_tr = 0;
 if (isset($_GET['triger2']))
 $total_sale_tr = $_GET['triger2'];
 else $total_sale_tr = 30;
 if (isset($_GET['triger3']))
 $qty_sold_tr = $_GET['triger3'];
 else $qty_sold_tr = 3;
 if (isset($_GET['factor']) && $_GET['factor'] != "")
 $factor = $_GET['factor'];
 else $factor = 1;
 $current_month = date(m);
 $current_month = str_pad($current_month, 2, '0', STR_PAD_LEFT);
 if ($current_month != 12) 
 {
 $next_month = $current_month + 1;
 $next_month = str_pad($next_month, 2, '0', STR_PAD_LEFT);
 }
 else
 {
 $next_month = 01;
 $next_month = str_pad($next_month, 2, '0', STR_PAD_LEFT);
 }
 ?>
 <body onLoad="initdt(document.create_order);">
    <style>
#PicStyle {
position:absolute;
/*visibility:hidden;
*/border:solid 1px #CCC;
padding:5px;
}
</style>
<script language="Javascript">
<!--
function ShowPicture(id,Source) {
if (Source=="1"){
if (document.layers) document.layers[''+id+''].visibility = "show"
else if (document.all) document.all[''+id+''].style.visibility = "visible"
else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "visible"
}
else
if (Source=="0"){
if (document.layers) document.layers[''+id+''].visibility = "hide"
else if (document.all) document.all[''+id+''].style.visibility = "hidden"
else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "hidden"
}
}
//-->
</script>
<br><br>
 <form style="text-align:left;" name="sorting" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="get">
 Filter Inactive?
    <input type="checkbox" name="inactive_filter" value="Yes" <?php echo $inactive_checked;?> />
 Show Only Items Sold this week?
    <input type="checkbox" name="weekly_filter" value="Yes" <?php echo $weekly_checked;?> />
 Sort By:
 <select name="sortby" size="1" style="margin: 0px; padding: 0px; width: 75px; font-size: 11px;">
 <option value="units_sold" <? if($sortwith=="units_sold") echo "selected=\"selected\"";?> >Units Sold</option>
 <option value="sales"  <? if($sortwith=="sales") echo "selected=\"selected\"";?>>Sales</option>
  <option value="ARS"  <? if($sortwith=="ARS") echo "selected=\"selected\"";?>>ARS</option>
 </select> 
 &nbsp;&nbsp;
 Avg Sale over: <input name="triger1" style="margin: 0px; padding: 0px; width: 30px; font-size: 11px;" type="text" value="<?php echo $avg_sale_tr; ?>">
 &nbsp;&nbsp;
  Total Sales over: <input name="triger2" style="margin: 0px; padding: 0px; width: 30px; font-size: 11px;" type="text" value="<?php echo $total_sale_tr; ?>">
 &nbsp;&nbsp;
 Qty Sold over: <input name="triger3" style="margin: 0px; padding: 0px; width: 30px; font-size: 11px;" type="text" value="<?php echo $qty_sold_tr; ?>">
 &nbsp;&nbsp;
 Divide sales by: <input name="factor" style="margin: 0px; padding: 0px; width: 30px; font-size: 11px;" type="text" value="<?php echo $factor; ?>">
<br><br>
 Search Size &amp; Part Number: <input name="showsku" style="margin: 0px; padding: 0px; width: 75px; font-size: 11px;" type="text" value="<?php echo $showsku; ?>">
 &nbsp;&nbsp;
 Product Type:
 <select name="partType" size="1" style="margin: 0px; padding: 0px; width: 75px; font-size: 11px;">
<?php
$resultType = mysql_query ("SELECT * FROM `product_type`"); ?>
 <option value="all" <? if($showType=="all") echo "selected=\"selected\"";?>>All</option>
 <?php
 if ($rowType = mysql_fetch_array($resultType)) {
   do {
    $selected = "" ;
     if ($rowType["type"] == $showType)
		$selected="selected";
   		print "<option $selected value=\"" . $rowType["type"]."\">" . $rowType["type"]."\r";
	 } while($rowType = mysql_fetch_array($resultType));
}
?>
 </select>
  &nbsp;&nbsp;
 Preffered Supplier:
 <?php
 $resultSupplier = mysql_query ("SELECT * FROM `organization` WHERE `active` = 1");
 echo "<select name=\"partSupplier\">\r"; ?>
 <option value="all" <? if($showSupplier=="all") echo "selected=\"selected\"";?>>All</option>
 <option value="novendor" <? if($showSupplier=="novendor") echo "selected=\"selected\"";?>>No Vendor Set</option> 
 <?php if ($rowSupplier = mysql_fetch_array($resultSupplier)) {
   do {
		   if ($rowSupplier["organization"] == $showSupplier)
		   $selected = "selected=\"selected\"";
		   else $selected = "";
   		print "<option $selected value=\"" . $rowSupplier["organization"]."\">" . $rowSupplier["organization"]."\r";
	 } while($rowSupplier= mysql_fetch_array($resultSupplier));
	 }
	 ?>
	 </select>
 &nbsp;&nbsp;
 Order Type:
 <select name="orderType" size="1" style="margin: 0px; padding: 0px; width: 75px; font-size: 11px;">
<?php
$resultType = mysql_query ("SELECT * FROM `ordertype`"); ?>
 <option value="all" <? if($showOrderType=="all") echo "selected=\"selected\"";?>>All</option>
 <?php
 if ($rowType = mysql_fetch_array($resultType)) {
   do {
    $selected = "" ;
     if ($rowType["type"] == $showOrderType)
		$selected="selected";
   		print "<option $selected value=\"" . $rowType["type"]."\">" . $rowType["type"]."\r";
	 } while($rowType = mysql_fetch_array($resultType));
}
?>
 </select>
  &nbsp;&nbsp;
 <input type="submit" name="submitreport" value="Run Report"/>
 </form>
 &nbsp;&nbsp; <button onClick="window.location='demand_excel.php?sortby=<?= $sortwith; ?>&triger1=<?= $avg_sale_tr; ?>&triger2=<?= $total_sale_tr; ?>&triger3=<?= $qty_sold_tr; ?>&factor=<?= $factor; ?>&showsku=<?= $showsku; ?>&type=<?= $showType; ?>&ordertype=<?= $showOrderType; ?>&supplier=<?= $showSupplier; ?>'">Download Excel</button>
 </tr>
 </table>
</td></tr></table>
 <form name="create_order" action="order-creator.php" method="post" onLoad> 
 <?php
 
table_header_peachtree_new("Demand Planning Report - $messageHeader", $factor);
 $countItems = 1;
 
 //$query1 = "SELECT * FROM `peachtree` JOIN `parts` ON `itemID` = `partno` WHERE `itemID` = 'VG485' ORDER BY `peachtree`.`$sortwith` DESC";
// $query1 = "SELECT * FROM `peachtree` JOIN `parts` ON `itemID` = `partno` WHERE `itemID` NOT LIKE 'X%' AND `parts`.`active` = 1 $show_type $show_order_type $show_supplier $inactive_filter_cnd $weekly_filter_cnd $show_sku ORDER BY `peachtree`.`$sortwith` DESC"; 
//`itemID` NOT LIKE '%FR-%' AND 
// `itemID` = 'VG415' `itemID` NOT LIKE 'X%' 
 $query1 = "SELECT * FROM `parts` JOIN `peachtree` ON `partno` = `itemID` WHERE 1=1 $show_type $show_order_type $show_supplier $inactive_filter_cnd $weekly_filter_cnd $show_sku ORDER BY `peachtree`.`$sortwith` DESC";
//echo $query1;
// $query1 = "SELECT * FROM `peachtree` JOIN `parts` ON `itemID` = `partno` WHERE `itemID` LIKE '%MON%' AND `parts`.`active` = 1 ORDER BY `peachtree`.$sortwith DESC";
 	//echo $query1;
	//TOTAL COST & QTY
 	$totalCost = 0;
 	$totalInv = 0; 
 $result = mysql_query($query1);
 while($myrow = mysql_fetch_array($result))
      {
$gross_margin = 0;
$avg_price = 0;
$costOnHand = 0;
$units_sold = 0;
$sales = 0;
$qty_on_hand = 0;
$qty_available = 0;
$recomended_qty = 0;
$ARS = 0;
$qty_remaining = 0;
$cogs_sold = 0;
// $partid = $myrow["itemID"];
 $partid = $myrow["partno"];
 $supplier = $myrow["supplier"];
 $weekly_units_sold = $myrow["weekly_units_sold"];
 
 $weeklySalesMsg = "";
		/***********Early Order PT - Start***********/
		if ($weekly_units_sold > 0) 
		{
		$weeklySalesMsg = "<br><b Style=\"font-size:10px;color:#0c6e15;\">Last Week Sales: " . round($weekly_units_sold,0) . "</b>";	
		}
 $future_event = "";
$totalUnitsBackorder = 0;
$totalUnitsOnEvent = 0;
$totalUnitsAmazon = 0;
$totalMyhabitOnEvent = 0;
 mysql_select_db($dbname2,$db);
	$queryCount = "SELECT qty, `SKU` FROM `fullfilment` WHERE `SKU` LIKE '%" . $partid . "%' AND `status` = 'Backorder';"; // GROUP BY `SKU`;"; // GROUP BY `SKU`
	//echo $queryCount . "<br>";
								$resultCount = mysql_query($queryCount);
								while ($rowCount = mysql_fetch_array($resultCount))
								{
								//echo $queryCount;
								$framepn =  $rowCount[1];
								$frame_units = $rowCount[0];
								
								$totalUnitsBackorder += $frame_units;	
													
								/*if ($countBackorder > 0)
								$future_event .= "<div style=\"float:right;padding:10px;\"><img src=\"images/alert.png\" align=\"right\" style=\"margin-top:10px; margin-right:10px; margin-bottom:10px;\"><a href=\"https://www.overstockart.net/ccm/fullfilment.php?q=" . $frameid . "&status=Backorder\" target=\"_blank\" style=\"color:#ae0011;font-weight:bold;\">" . $countBackorder . " On Backorder!</a></div>";*/
								}
		$now = time();
		$twomonth = strtotime("+2 month", $now);
		
		if (substr($partid,0,3) == 'FR-' || substr($partid,0,4) == 'GALW' || substr($partid,0,3) == 'STR')
		$checkTable = "frameSKU";
		else
		$checkTable = "artSKU";
  
		$queryCount = "SELECT `eventItems`.`qty`, `eventItems`.`SKU`, `eventItems`.`DateEnd`, `saleEvents`.`Type`, `saleEvents`.`Company`, `saleEvents`.`DateStart`, `eventItems`.`eventID` FROM `eventItems` LEFT JOIN `saleEvents` ON `eventItems`.`eventID` = `saleEvents`.`eventID` WHERE `eventItems`.`$checkTable` = '" . $partid . "' AND `eventItems`.`DateEnd` > $now;";
		//echo $queryCount;
								$resultCount = mysql_query($queryCount);
								while ($rowCount = mysql_fetch_array($resultCount))
								{
								//AND `DateEnd` < $twomonth
								//AND `DateEnd` > $now
								//echo $queryCount;
								$framepn =  $rowCount[1];
								$frame_units = $rowCount[0];
								$endEvent = $rowCount[2];
								$typeEvent = $rowCount[3];
								$companyEvent = $rowCount[4];
								$startEvent = $rowCount[5];
								
								if($typeEvent == 6) continue;
								//$totalMyhabitOnEvent += $frame_units;
								else if($startEvent < $twomonth)
									{  //1401771600 < 1400170231
//echo $companyEvent . " DATE:" . date("m-d-Y",$startEvent) . " PN: " . $framepn  . " COUNT: " . $frame_units . "<BR>";
									$totalUnitsOnEvent += $frame_units;
									}
								//echo $queryCount;
								}
								/*if ($countEventItems > 0)
								$future_event .= "<div style=\"clear: both\";></div><div style=\"float:right;padding:10px;\"><img src=\"images/clock.svg\" align=\"right\" style=\"margin-top:10px; margin-right:10px; margin-bottom:10px;\"><a href=\"eventItems.php?partnosearch=" . $frameid . "\" target=\"_blank\" style=\"color:#293b74;font-weight:bold;\">" . $countEventItems . " On Hold for Events</a></div>";*/
		
		mysql_select_db($dbname3,$db);
		
		//CVG centers are for myhabit POs...
/*$queryCount = "SELECT avo.qty AS sumQty, avo.qtyReceived AS sumRec, avo.qtyShipped AS sumShip, avo.qtyCanceled AS sumCanceled, avo.`SKU`, avo.`shipDate`, avsi.qty AS sumInCarton, avsi.`carton_id` FROM `amazonvOrders` AS avo LEFT JOIN amazonvShipItem AS avsi ON avo.`primary` = avsi.amazonvOrderID WHERE avo.`SKU` LIKE '%" . $partid . "%' AND avo.`fulfillmentCenter` <> 'CVG1' AND avo.`fulfillmentCenter` <> 'CVG2';";*/ 
$queryCount = "SELECT avo.qty AS sumQty, avo.qtyReceived AS sumRec, avo.qtyShipped AS sumShip, avo.qtyCanceled AS sumCanceled, avo.`SKU`, avo.`shipDate`, SUM(avsi.qty) AS sumInCarton, avsi.`carton_id`, avo.`primary` FROM `amazonvOrders` AS avo LEFT JOIN amazonvShipItem AS avsi ON avo.`primary` = avsi.amazonvOrderID WHERE avo.`SKU` LIKE '%" . $partid . "%' AND avo.`fulfillmentCenter` <> 'CVG1' AND avo.`fulfillmentCenter` <> 'CVG2' GROUP BY avo.`primary`;"; 
//echo $queryCount;
// GROUP BY `SKU`";
//AND (`qty` - `qtyCanceled`) > (`qtyReceived` + `qtyShipped`)
//echo $queryCount . "<br>";
								/*$resultCount = mysql_query($queryCount);
								$rowCount = mysql_fetch_array($resultCount);*/
								$resultCount = mysql_query($queryCount);
						while ($rowCount = mysql_fetch_array($resultCount))
						{
								$countAmazonOrder = $rowCount[0];
								$countAmazonRec = $rowCount[1];
								$countAmazonShip = $rowCount[2];
								$countAmazonCancel = $rowCount[3];
								$framepn =  $rowCount[4];								
								$shipDate = strtotime($rowCount[5]);
								$sumInCarton =  $rowCount[6];
								$cartonnumber =  $rowCount[7];
								
								if($cartonnumber < 1) $sumInCarton = 0;
								//echo $rowCount[3] . " = " . $shipDate . "<BR>";
								$frame_units =  ($countAmazonOrder) - ($countAmazonRec + $sumInCarton + $countAmazonCancel);
								if ($frame_units > 0 && $shipDate < $twomonth)
								{
								//echo $queryCount;
								$totalUnitsAmazon += $frame_units;
								}
							}
							
							
							/*$queryCount = "SELECT avo.qty AS sumQty, avo.qtyReceived AS sumRec, avo.qtyShipped AS sumShip, avo.qtyCanceled AS sumCanceled, avo.`SKU`, avo.`shipDate`, avsi.qty AS sumInCarton, avsi.`carton_id` FROM `amazonvOrders` AS avo LEFT JOIN amazonvShipItem AS avsi ON avo.`primary` = avsi.amazonvOrderID WHERE avo.`SKU` LIKE '%" . $partid . "%' AND (avo.`fulfillmentCenter` = 'CVG1' OR avo.`fulfillmentCenter` = 'CVG2');"; */
							
$queryCount = "SELECT avo.qty AS sumQty, avo.qtyReceived AS sumRec, avo.qtyShipped AS sumShip, avo.qtyCanceled AS sumCanceled, avo.`SKU`, avo.`shipDate`, SUM(avsi.qty) AS sumInCarton, avsi.`carton_id`, avo.`primary` FROM `amazonvOrders` AS avo LEFT JOIN amazonvShipItem AS avsi ON avo.`primary` = avsi.amazonvOrderID WHERE avo.`SKU` LIKE '%" . $partid . "%' AND (`fulfillmentCenter` = 'CVG1' OR `fulfillmentCenter` = 'CVG2') GROUP BY avo.`primary`;";
// GROUP BY `SKU`";
//AND (`qty` - `qtyCanceled`) > (`qtyReceived` + `qtyShipped`)
//echo $queryCount . "<br>";
								/*$resultCount = mysql_query($queryCount);
								$rowCount = mysql_fetch_array($resultCount);*/
								$resultCount = mysql_query($queryCount);
						while ($rowCount = mysql_fetch_array($resultCount))
						{
								$countAmazonOrder = $rowCount[0];
								$countAmazonRec = $rowCount[1];
								$countAmazonShip = $rowCount[2];
								$countAmazonCancel = $rowCount[3];
								$framepn =  $rowCount[4];								
								$shipDate = strtotime($rowCount[5]);
								$sumInCarton =  $rowCount[6];
								$cartonnumber =  $rowCount[7];
								
								if($cartonnumber < 1) $sumInCarton = 0;
								//echo $rowCount[3] . " = " . $shipDate . "<BR>";
								$frame_units =  ($countAmazonOrder) - ($countAmazonRec + $sumInCarton + $countAmazonCancel);
								if ($frame_units > 0 && $shipDate < $twomonth)
								{
								//echo $queryCount;
								$totalMyhabitOnEvent += $frame_units;
								}
							}
								
								/*$future_event .= "<div style=\"clear: both\";></div><div style=\"float:right;padding:10px;\"><img src=\"images/amazon.png\" align=\"right\" style=\"margin-top:10px; margin-right:10px; margin-bottom:10px;\"><a href=\"http://www.overstockart.net/sorter/amazon-sku-list.php?qty_filter=Yes&sortby=date_for_sort&filterPO=all&filterFC=all&filter1=" . $partno . "&submitreport=Run+Items\" target=\"_blank\" style=\"color:#333333;font-weight:bold;\">" . $countAmazonItems . " On Order by Amazon</a></div>";*/
 mysql_select_db($dbname,$db);
 $queryMon = "SELECT * FROM `pn-monthly` where itemID = '" . $partid . "';";
 //echo $queryMon;
 $monResult = mysql_query($queryMon);
 if (mysql_num_rows($monResult) > 0)
	 {
		while($rowMonthly = mysql_fetch_array($monResult))
		{
			if ( $rowMonthly[0] != NULL )
			{
			$current = "qty_" . $current_month;
			$next = "qty_" . $next_month;
			$current_monthly_sales = $rowMonthly["$current"];
			$next_monthly_sales = $rowMonthly["$next"];
			}
		}
	}
	
 //START - ADD QTY ON ORDER AND ACCEPTED
 	$queryTrans = "SELECT partid, unit_sold, sales, qty_on_hand, qty_available, active, artimage, closeout, outofstock, CountDays FROM parts WHERE partno ='" . $partid . "' LIMIT 1;";
 	$transResult = mysql_query($queryTrans);
	if (mysql_num_rows($transResult) > 0)
	 {
 	$rowTrans = mysql_fetch_array($transResult);
 	if ( $rowTrans[0] != "" )
 	{
		$partid1 = $rowTrans[0];
		$active =  $rowTrans[5];
		$units_sold = intval($rowTrans[1]);
		$sales = floatval($rowTrans[2]);
		$qty_on_hand = intval($rowTrans[3]);
		$qty_available = intval($rowTrans[4]);
		$closeout = $rowTrans[7];
		$outofstock = $rowTrans[8];
		$avgPT = $rowTrans[9];
		if($avgPT < 1) $avgPT = 46;
		$query1 = "SELECT cost FROM `orderlines` WHERE partid='" . $partid1 . "' or partid= '" . $partid . "' ORDER BY `line_id` DESC LIMIT 1;";
		//echo $query1;
		 $result3 = mysql_query($query1);
		while($rowOnOrder = mysql_fetch_array($result3))
		 {
				$costOnHand = $rowOnOrder[0];
		 }
		
		//Dollars in Inventory
		$inventory_dollars = $costOnHand*$qty_available;
		
		if ($units_sold > 0)
 		$avg_price = number_format(($sales/$units_sold),2,'.','');
 		else
 		$avg_price = 0;
		
		 if ($units_sold < $qty_sold_tr || $avg_price < $avg_sale_tr || $sales < $total_sale_tr) continue;
 	
 	$query1 = "SELECT quantity,qtyaccepted,qtyReceived,cost FROM `orderlines` WHERE STATUS <> 'Closed' AND STATUS <> 'Cancelled' AND (partid='" . $partid1 . "' or partid= '" . $partid . "');";
 	//echo $query1;
    $result3 = mysql_query($query1,$db);
 	//$rowOnOrder = mysql_fetch_array($result3, MYSQL_NUM);
 	$qty_on_order = 0;
 	$qty_accept = 0;
 	$qty_received = 0;
 	while($rowOnOrder = mysql_fetch_array($result3))
      {
 		    if ( $rowOnOrder[0] != NULL )
 			{
 			$qty_on_order += $rowOnOrder[0];
 			$qty_accept += $rowOnOrder[1];
 			$qty_received += $rowOnOrder[2];
 			$costOnHand = $rowOnOrder[3];
 			}
 	  }
	  
 	//******************* INVENTORY DAYS ********************************  
 	$priorDay = "";
	$noCount = 0;
	$markFirst = "";
	$timeNow = time();
	//$timeSixMonths =  time() - (6 * 4.35 * 7 * 24 * 60 * 60);  //6 months back
	$timeYear =  time() - (52 * 7 * 24 * 60 * 60);  //1 year back
	$queryDays = "SELECT * FROM `parts_timeline` WHERE partno ='" . $partid . "' AND dateChange > $timeYear ORDER BY dateChange ASC;"; //$timeSixMonths
	//echo $queryDays . "<br>";
	$resultDays = mysql_query($queryDays);
	$totalRowDays = mysql_num_rows($resultDays);
	//echo "Total rows: " . $totalRows . "<br>";
	
	 //checking if new product...
	 $queryDaysBf = "SELECT * FROM `parts_timeline` WHERE partno ='" . $partid . "' AND dateChange < $timeYear ORDER BY dateChange DESC LIMIT 1;";  //$timeSixMonths
			//	echo $queryDaysBf . "<BR>";
	$resultDaysBf = mysql_query($queryDaysBf);
	$totalRowsBf = mysql_num_rows($resultDaysBf);
	
	$countDays = inventory_days($resultDays,$totalRowsBf,$totalRowDays);
	}
 	//echo "total days: " . $countDays . "<br>";
	//$units_sold_6m = round($units_sold/2);  //find the average sales in the past 6 months
 	//echo $units_sold_6m . "<br>";
 	if($countDays > 0)
 	$ARS = $units_sold/$countDays; // $units_sold_6m/$countDays
 	else $ARS = 0;
 	//echo $ARS . "<br>";
	
 	if ($ARS > 0 && $qty_on_hand > 0)
 	$days_until_out = round($qty_on_hand/$ARS);
 	else $days_until_out = 0;
 
/* 	if ($ARS > 0 && $qty_available > 0)
 	$days_until_out = round($qty_available/$ARS);
 	else $days_until_out = 0;
*/
  //echo $days_until_out . "<br>";
	$date_when_0 = 0;
  	$date_when_max = 0;
	$real_count_days = 0;
	$eoQtyReal = 0;
	if ($qty_available < 1)
		{	
			$real_count_days = 	number_of_days($last0,$lastInc);		
		}
		  
  		$qty_remaining = $qty_on_order - $qty_received; //remove the qty received from order
		
 		/**days until the stock will run out including the on order qty**/
 		if ($ARS > 0 && $qty_remaining > 0)
 		$days_with_on_order = round($qty_remaining/$ARS) + $days_until_out;
 		else $days_with_on_order = $days_until_out;
 		/**days until the stock will run out including the on order qty**/
   //*********************  INVENTORY DAYS  *************************
   
 	}
 	
 	else { 
 		$qty_on_order = 0;
 		$qty_accept = 0;
 		$qty_received = 0;
 		}
		
		$earlyOrderMsg = "";
		/***********Early Order PT - Start***********/
		
		if ($ARS > 0) //changed from 0.1 
		{
		$earlyOrderMsg = "<br><b Style=\"font-size:10px;color:#AE0011;\">Early Order Item " . round($eoQtyReal,0) . "</b>";	
		$qtyShipped = 0;
		//grab the start date of the order:
		$query4 = "SELECT  ol.`line_id`, ol.`orderid`, ol.`cost`, ol.`status`, ol.`quantity`,  o.`organization`, o.`startdate`
FROM `orderlines` AS ol
LEFT JOIN  `orders` AS o ON `ol`.`orderid` =  `o`.`orderid` 
WHERE ol.`partid` =  '" . $partid1 . "' AND  ol.`status` != 'Cancelled' AND ol.`status` != 'Closed'
ORDER BY  ol.`line_id` DESC"; 
//echo $query4;
$oResult4 = mysql_query($query4,$db);
while($row4 = mysql_fetch_array($oResult4))
		{
			$orderlineClosed = $row4["line_id"];
			$productionStart = $row4["startdate"];
			$orderidIn = $row4["orderid"];
			$partOrg = $row4["organization"];
			if($olOrg == "")
			{
			$olOrg = $partOrg;
			}
			else if ($olOrg != $partOrg) continue;
			
			$query3 = "SELECT * FROM shipment_line WHERE orderline_id = '" . $orderlineClosed. "';"; 
			//echo $query2;
			$oResult2 = mysql_query($query3,$db);
			while($row2 = mysql_fetch_array($oResult2))
			{
			/*echo "orderlines: " . $orderlineClosed . " order id: " . $orderidIn . " Qty: " . $row2["qty"] . "<br>";*/
				$qtyShipped += $row2["qty"];
			}
		}
		$olOrg = "";
		$countOrderIDs = 0;
		$sumPT = 0;
		$productionTime = 0;
				//grab the start date of the order:
		$query4 = "SELECT  ol.`line_id`, ol.`orderid`, ol.`cost`, ol.`status`, ol.`quantity`,  o.`organization`, o.`startdate`
FROM `orderlines` AS ol
LEFT JOIN  `orders` AS o ON `ol`.`orderid` =  `o`.`orderid` 
WHERE ol.`partid` =  '" . $partid1 . "'
AND  (ol.`status` = 'Shipped' || ol.`status` = 'Closed')
ORDER BY  ol.`line_id` DESC"; 
		//echo $query4;
		$oResult4 = mysql_query($query4,$db);
		while($row4 = mysql_fetch_array($oResult4))
		{
			$orderlineClosed = $row4["line_id"];
			$productionStart = $row4["startdate"];
			$orderidIn = $row4["orderid"];
			$partOrg = $row4["organization"];
			if($olOrg == "")
			{
			$olOrg = $partOrg;
			}
			else if ($olOrg != $partOrg) continue;
			
			/*$query3 = "SELECT * FROM shipment_line WHERE orderline_id = '" . $orderlineClosed. "';"; 
			//echo $query2;
			$oResult2 = mysql_query($query3,$db);
			while($row2 = mysql_fetch_array($oResult2))
			{
			echo "orderlines: " . $orderlineClosed . " order id: " . $orderidIn . " Qty: " . $row2["qty"] . "<br>";
				$qtyShipped += $row2["qty"];
			}*/
		
			$query5 = "SELECT  sl.`orderline_id`, sl.`shipid`, sl.`qty`, s.`organization`, s.`startdate` 
FROM  `shipment_line` AS sl
LEFT JOIN `shipment` AS s ON sl.`shipid` =  s.`shipid` 
WHERE sl.`orderline_id` = '" . $orderlineClosed . "'
ORDER BY `lineid` ASC LIMIT 1"; 
			//echo $query2;
			$oResult5 = mysql_query($query5,$db);
			while($row5 = mysql_fetch_array($oResult5))
			{
				$productionEnd = $row5["startdate"];
				$shipEnd = $row5["shipid"];
			}
			
			//production time...
			$productionTime = dateDiff($productionStart,$productionEnd);
			
			//remove anomolies
			if($productionTime > 100 || $productionTime < 10) continue;
			 
			//echo $partno . " PT = " . $productionTime . " ORDER ID=" . $orderidIn . " SHIP ID=" . $shipEnd . "<br>";
			$sumPT += $productionTime;
			$countOrderIDs++;		
        }
			
			//***Amitai Change to set Production Time of 42 days****//
			if($countOrderIDs > 0)
			$avgPT = round($sumPT/$countOrderIDs,2);
			else $avgPT = 46;
			//David had an idea to offer a 46 days set PT		
			//$avgPT = 46;
			
			//if 6 month sales qty is smaller then order just 6 MOnths sales qty...
			if($avgPT*$ARS*2 > 180*$ARS)
			$eoQty = 180*$ARS;
			else
			$eoQty = $avgPT*$ARS*2;
			
			/*echo "avgPT = " . $avgPT . "<br>";			
			echo "eoQty = avgPT * ARS * 2 = " . $avgPT . " * " . $ARS . " * 2 =  " . $eoQty . "<br>";*/
			 $qtyInRoute = 0;
			if ($qtyShipped > $qty_received)
			 $qtyInRoute = ($qtyShipped - $qty_received); 
			/*else if ($qtyShipped < $qty_received)
			 $qtyShipped = $qty_received; */
			
			/*echo "qty_on_order = " . $qty_on_order . "<br>";
			echo "qtyShipped = " . $qtyShipped . "<br>";
			echo "qtyReceived = " . $qty_received . "<br>";
			echo "qtyInRoute = " . $qtyInRoute . "<br>";
			echo "qty_on_hand = " . $qty_on_hand . "<br>";*/
				//CREATE AN EARLY ORDER WHEN QTY_ON_ORDER + QTY_ON_HAND < PT*ARS + 14*ARS - 14 DAY BUFFER ADDED.
				if(($qty_remaining + $qty_on_hand) < round(($avgPT*$ARS*1.5),0)) //+round(14*$ARS,0)))
				{
				//echo "eoQtyReal = eoQty - qty_on_hand + (14*ARS) => " . $eoQty . " - " . $qty_on_hand . " + (14*" . $ARS . ")";
				//$eoQtyReal = $eoQty - ($qty_on_hand + ($qty_on_order  - $qtyShipped) + $qtyInRoute);
				//David also wanted to try eoQtyReal = eoQty - (qty_on_hand - 14*ARS)
				$eoQtyReal = $eoQty - $qty_on_hand - $qtyInRoute + (14*$ARS);
								
				//echo "eoQtyReal = eoQty - (qty_on_hand + (qty_on_order  - qtyShipped) + qtyInRoute) = " . $eoQtyReal . "<br>";
				$earlyOrderMsg = "<br><b Style=\"font-size:10px;color:#AE0011;\">Early Qty = " . round($eoQtyReal,0) . "</b>";
				}
			//}
		/********PT - End*************/
		}
		
		$name = $myrow["name"];
		
/****** took out to improve performance... Jan 2012
 //updating peachtree and parts tables on DB... 
$query_peachtree = "UPDATE `peachtree` SET `qty_on_order` = '$qty_on_order',`qty_accept` = '$qty_accept', `qty_receive` = '$qty_received', `ARS` = '" . round($ARS,5) . "' WHERE `itemID` = '$partid' LIMIT 1";
 //echo $query_peachtree;
 		mysql_query($query_peachtree) or die("Couldn't add row2 query: $query_peachtree");
 $query_parts = "UPDATE `parts` SET `qty_on_order` = '$qty_on_order',`qty_accept` = '$qty_accept', `qty_receive` = '$qty_received', `ARS` = '" . round($ARS,5) . "' WHERE `partno` = '$partid' LIMIT 1";
 //echo $query_peachtree;
 		mysql_query($query_parts) or die("Couldn't add row2 query: $query_parts");
//END - ADDING THE QTY ON ORDER AND ACCEPTED
*****/ 		
/*********************
EXPLANATION FOR BINS LOGIC:
Bin is based on production time.  It is 1.5XPTXARS.  This makes it logical as we are saying we have a buffer of half the production time or about 30 days (average of 60 days PT)
The amount to order is based on sales 90XARS – (QOH+QOO-(AZN+MYH+BO+PT X ARS)).  This means that we are ordering based on our expected sales.  Since we are ordering every week the sales is what determines our need not the PT.  Based on this algorithm we will have available to us 90 day supply by the time the order is dry and ready.
*********************/
 		//$units_sold = $myrow["units_sold"];
 		//echo $partid . " " . $units_sold . "<br>";
 		//$sales = $myrow["sales"]; //number_format($myrow["sales"],2,'.',',');
 		//$qty_on_hand = $myrow["qty_on_hand"];
 		
 		/*if( ($qty_on_hand + $qty_remaining ) < ($units_sold/$factor))
 		  $flag = "#ae0011; font-weight:bold;";
 		else $flag = "#000000";*/
		if( ($qty_available + $qty_remaining ) < ($units_sold/$factor))
 		  $flag = "#ae0011; font-weight:bold;";
 		else $flag = "#000000";
 		
 		if( $days_with_on_order < 120) //assuming 120 days supply
 		  $flag = "#1c9327; font-weight:bold;";
 		else $flag = "#000000";
 		
 		//recomended qty to order based on 2 motnhs + 35% growth supply time (90 days)
 		/*$recomended_qty = round(($ARS * 1.35) * 90) - (($qty_on_hand + $qty_remaining) - round($ARS * 90));
 		if ($recomended_qty > 3)
 		{  $flag = "#1c9327; font-weight:bold;"; }
		else if ($recomended_qty <= 3 && $recomended_qty >= 1)
 		{ $recomended_qty = $recomended_qty; }
 		else $recomended_qty = 0;*/
		/*** formula up to May 2013 
		$recomended_qty = round(($ARS * 1.35) * 90) - (($qty_available + $qty_remaining) - round($ARS * 90));
		$recomended_qty = round(($ARS) * 45) - (($qty_available + $qty_remaining) - round($ARS * 45));
		$recomended_qty = round(($ARS) * 45) - ($qty_available + $qty_remaining);
		****/
		//recomended qty to order based on 2 motnhs + 35% growth supply time (90 days)
		$two_month_of_sales = round(($ARS) * 60); //changed to 2 motnhs...
		//echo "month_of_sales = " . $month_of_sales . "<br>";
		$qty_reserved_on_events = $totalUnitsOnEvent; ///2; 
		if ($two_month_of_sales > $qty_reserved_on_events)
		$qty_needed = $two_month_of_sales;
		else
		$qty_needed = $qty_reserved_on_events;
	
	if($qty_on_hand < 1) 
	$qty_on_hand_bin = 0;
	else
	$qty_on_hand_bin = $qty_on_hand;
	
	$qty_in_bin = $qty_on_hand_bin + $qty_remaining;
	$needed_bin_qty = 90*$ARS - ($qty_in_bin - $totalUnitsAmazon - $totalMyhabitOnEvent - $totalUnitsBackorder - $ARS*$avgPT);
	if ($needed_bin_qty < 1) $needed_bin_qty = 0;
	
	if($units_sold <= 3 && $qty_remaining >= 5) $needed_bin_qty = 0;
	else if($units_sold <= 3 && $needed_bin_qty >= 5) $needed_bin_qty = 5 - $qty_remaining; //order up to 5
	
	$needed_bin_qty_ro = 30*$ARS - ($qty_in_bin - $totalUnitsAmazon - $totalMyhabitOnEvent - $totalUnitsBackorder - $ARS*$avgPT);
	if ($needed_bin_qty_ro < 1) $needed_bin_qty_ro = 0;
	 // $needed_bin_qty2 = 30*$ARS - ($qty_on_hand_bin-$ARS*$avgPT);
	if($units_sold <= 3 && $qty_remaining >= 5) $needed_bin_qty_ro = 0;
	else if($units_sold <= 3 && $needed_bin_qty >= 5) $needed_bin_qty_ro = 5 - $qty_remaining; //order up to 5
	
	$recomended_qty =  $qty_needed + $totalUnitsAmazon + $totalMyhabitOnEvent + $totalUnitsBackorder - ($qty_on_hand_bin + $qty_remaining);
	
//echo "recomended_qty: " . $recomended_qty;
//changed on April 1st 2014...
//		$recomended_qty = round(($ARS) * 60) - ($qty_available + $qty_remaining);
 		
		if ($recomended_qty >= 1)
 		{  $flag = "#1c9327; font-weight:bold;"; }
		/*else if ($recomended_qty <= 3 && $recomended_qty >= 1)
 		{ $recomended_qty = $recomended_qty; }*/
 		else $recomended_qty = 0;
		$fullBin = round($ARS * $avgPT * (1.5),2); //Full Bin system
		//if ($fullBin > $totalUnitsAmazon) //,$qty_reserved_on_events
		$totalBin = $fullBin + $totalUnitsAmazon + $totalMyhabitOnEvent + $totalUnitsBackorder;
		//max($fullBin,$totalUnitsAmazon)
		if (($qty_on_hand_bin + $qty_remaining) >= $totalBin) //green
		$binColor = "#2a9914";
		else if (($qty_on_hand_bin + $qty_remaining) >= 0.8*$totalBin) //yellow
		$binColor = "#f5f812";
		else //if (($qty_on_hand_bin + $qty_remaining) <= 0.5*$totalBin) //red
		$binColor = "#db1334"; 		
 		
 		/*$queryTrans = "SELECT partid,closeout FROM parts WHERE partno ='" . $partid . "' LIMIT 1;";
 		$transResult = mysql_query($queryTrans,$db);
 		$row = mysql_fetch_array($transResult, MYSQL_NUM);*/
 		if($partid1 == "")
 		  $border = "#293b74";
 		else $border = "#FFFFFF";
 		
 		if($closeout == '1')
 		$closeoutdisplay = "<br><b style=\"color:#293b74\">closeout</b>";
 		else
 		$closeoutdisplay = "";
 		
 $borderOnHand = ""; //BORDER FOR MESSAGED PARTS
 // Here we will get it to show the replies
 // This query selects the replies from the database where the thread ID matches the thread $_GET value.
 $sqlM = "SELECT * FROM `replies-parts` WHERE thread = '" . $partid1 . "' ORDER BY `id` DESC LIMIT 1";
 $resultM = mysql_query($sqlM);
 $date2 = time(); //time now
 $days3 = 3*24*60*60; //3 days
 // Now we are getting our results and making them an array
 /*******************************/
 if (mysql_num_rows($resultM) > 0)
 {
	 while($r = mysql_fetch_array($resultM)) {
	 $posted = $r[posted]; //the date posted
	 //if time now - change in inventory is smaller then 3 days then note a change in inventory
		if ($date2 - $posted < $days3)
		{
		  //$borderOnHand = "border: medium #000066 dashed;";rgba(0, 0, 102, 0.5)
			$borderOnHand = "background:none repeat scroll 0 0 rgba(0, 0, 102, 0.3);";
		}
		else
		{
		 $borderOnHand = "";
		}
	 // End of Array
	 }
 }
 
 //changed $qty_on_hand
 	if ($qty_available > 0)
 	{
 	 $borderOutofStock = "";
 	 $boldOutofStock = "#000000;";
 	}
 	else
 	{
 	//echo "less then 1" . ;
 	 //$borderOutofStock = "border: medium #ae0011 dashed;";
	 $borderOutofStock = "background:none repeat scroll 0 0 rgba(174, 0, 17, 0.3)";
 	 $boldOutofStock = "#ae0011;";
 	}
 		
 	//TOTAL	QTY & COSTS
 	if ($qty_on_hand > 0)
 	{
 			$totalCostOnHand = $costOnHand * $qty_on_hand; 	
 			$totalCost += $totalCostOnHand;
 			$totalInv += $qty_on_hand;
 	}
	/*if ($qty_available > 0)
 	{
 			$totalCostOnHand = $costOnHand * $qty_available; 	
 			$totalCost += $totalCostOnHand;
 			$totalInv += $qty_available;
 	}*/
 		
	if ($units_sold > $qty_sold_tr && $avg_price > $avg_sale_tr && $sales > $total_sale_tr) //
	{
	$units_sold_period = number_format($units_sold/$factor,0,'.',''); //units sold in the period...
 		
 	//******************* EARN & TURN  ********************************/
	if ($costOnHand > 0)
	{
 	$gross_margin = (($avg_price - $costOnHand)/$avg_price)*100; //GROSS MARGIN
 	$cogs_sold = $costOnHand*$units_sold; //COST OF GOOD SOLD
 	/*$queryAvg = "SELECT AVG(qty_on_hand) AS avg_on_hand FROM `parts_timeline` WHERE `partno` = '" . $partid . "' AND dateChange > " . $timeYear . ";";
 	$resultAvg = mysql_query($queryAvg);
    $rowAvg = mysql_fetch_array($resultAvg);
 	$on_hand_avg = $rowAvg["avg_on_hand"];
 	
		if($on_hand_avg > 0)
		{	
		//echo "on_hand_avg = " . $on_hand_avg . " * costOnHand = " . $costOnHand;
		$avg_inv_cost = $on_hand_avg * $costOnHand; //Average Inv Costs
		
		$earnNturn = $gross_margin * ($cogs_sold / $avg_inv_cost);
		}
		else
		{
		$onHandMessage = "NO AVERAGE ON HAND";
		}*/
	}
	else
	{
	$costMessage = "NO COST INFORMATION";
	}
 	//echo "<br>" . $partid . " EN= " . $earnNturn . " = " . "GROSSMARGIN(" . $gross_margin . ") * (COGS" . $cogs_sold  . " / " . $avg_inv_cost . " AVG INV)";
 	//******************* END EARN & TURN ******************************/
 	
 		$i == 0 ? $color = "#FFFFFF" : $color = "#DDDDDD";
 		$i == 0 ? $class = "normal" : $class = "normal2";
         $i == 0 ? $i = 1 : $i = 0;
 		?>		
 <tr onMouseOver=this.className='highlight' onMouseOut=this.className="<? echo $class; ?>" bgcolor="<? echo $color; ?>" style="color:<?php echo $flag; ?>; ">
<td>
 <div style="width:80px;text-align: center;">
 <?php echo $countItems; //"<input type='checkbox' name='check" . $partid . "' value='" . $partid . "'>"; ?>
 </div>
   <div bgcolor="<?php echo $border; ?>" style=" <?= $borderOnHand; ?> width:90px;">
   <? 
   echo "<a target=_blank href=\"viewparts.php?partid=$partid1\">" . $partid . "</a>" . $closeoutdisplay; 
   if($supplier != "") echo "<br>Supplier: " . $supplier;
  echo "<br><b style=\"font-size:10px;color:#197c12\">Cost: $" . round($costOnHand,2) . "<br>Inv. Dollars: $" . round($inventory_dollars,2). "</b>";
   ?>
  
   </div>
   <div  style="width:92px;"><? echo $name; //"<a href=\"#\" onMouseOver=\"ShowPicture('PicStyle" . $countItems . "',1)\" onMouseOut=\"ShowPicture('PicStyle" . $countItems . "',0)\">" . $name . "</a>"; 
    if ($qty_on_hand < 1)
 	{
   echo "<br><span style=\"font-size:8px;font-weight:bold;\">" . "Qty 0 on: " . date("m.d.y",$last0) . "<br>Qty " . $qtyInc . " on " . date("m.d.y",$lastInc) . "<br>Days until out: " . $real_count_days . "</span>";
   }
   ?>
 <!--  <div class="PicStyle" id="PicStyle<?= $countItems; ?>"><img src="<?php echo "files/thumb/" . $artimage ?> "></div>-->
  <?php 
  if($active == '0')
		echo "<br><b style=\"color:#ae0011\">DISCONTINUED!</b>";
  else
  {
  echo '<br /><a href="#" onClick="removeComm(' . $partid1 . ')" style="color:#AE0011; font-size:10px; font-weight:bold;">
  [discontinue]</a>';
  }
  
   if($outofstock == '1')
  {
		echo "<br><br><b style=\"color:#ae0011;font-size:8px;\">OUT OF STOCK AT VENDOR!</b>";
		  echo '<br><a href="#" onClick="markOut(' . $partid1 . ',0)" style="color:#293b74; font-size:10px; font-weight:bold;">[mark back in stock &raquo;]</a>'; 
	} 
  else
  {
  echo '<br><br><b style=\"color:#12a23b;font-size:10px;\">IN STOCK AT VENDOR!</b><br><a href="#" onClick="markOut(' . $partid1 . ',1)" style="color:#AE0011; font-size:10px; font-weight:bold;">[set vendor out of stock &raquo;]</a>';
  }
 ?>
   </div>
  <!-- <td width="60"><? echo $current_monthly_sales ; ?></td>
     <td width="60"><? echo $next_monthly_sales ; ?></td> -->
   <div style="width:92px;text-align: center;"><? echo "<a href=\"javascript:GlobalPopUp('monthly-current-pn.php?partno=$partid&total=$units_sold',800,200);\">" . $units_sold_period . "</a>"; ?></div>
   <div style="width:92px;"><span style="font-size:10px; font-weight:normal;">
<? echo "$" . $sales ; 
echo "<br>PT: " . $avgPT . " days";
echo "<br>2 Mo. qty: " . $two_month_of_sales;
echo "<br>Event qty: " . $qty_reserved_on_events;  
echo "<br>BO qty: " . $totalUnitsBackorder;
//echo "<br>Total Units on Events = " . $totalUnitsOnEvent;
echo "<br>AMZ qty: " . $totalUnitsAmazon;
echo "<br>MyHb qty: " . $totalMyhabitOnEvent;
?></span>
    <br> 
		   <?php 
		   /*if ($costOnHand > 0)
			{
			  if($on_hand_avg > 0)
			  {
		if ($earnNturn >100) echo "color:#293b74;"; 
		else echo "color:#AE0011;";?>  font-size:10px; font-weight:bold;">E&T $<?= number_format($earnNturn,1,'.',','); 
			  }
			  else
			  {
			  echo "font-size:10px; font-weight:bold;\">" . $onHandMessage;
			  }
			   
		   }
		   else
		   {
		   echo "font-size:10px; font-weight:bold;\">" . $costMessage;
		   }*/
		   ?>
  </div>
  <div style="<?= $borderOutofStock; ?>; font-size:8px;width:88px;"><b style="color:<?php echo $boldOutofStock; ?>;"><? echo "On Hand: " . $qty_on_hand ; 
  ?>
  <ul style="font-size:9px;list-style-type:none;padding:0; margin:3;color:<?=$binColor?>;">
<? echo "<li>Full Bin: " . $fullBin . "</li>";
    echo "<li>Total Bin: " . $totalBin . "</li>";
	   echo "<li>Qty in Bin: " . $qty_in_bin . "<br></li>"; 
  echo "<li><u>Need Bin(EO) : " . round($needed_bin_qty) . "</u></li>";
  echo "<li><u>Need Bin(RO) : " . round($needed_bin_qty_ro) . "</u></li>";
  // echo "<li><u>Qty Bin : " . $needed_bin_qty2 . "</u></li>";
 // }
  
?></ul>
<?php
  if($qty_on_hand > $qty_available)
  echo "<br>Available: " . $qty_available;
  ?>
  </b></div>
   <div style="width:90px;text-align: center;"><? echo $qty_remaining; //echo " " . $qty_remaining . " = " . $qty_on_order . " - " . $qty_received; ?></div>
   <div  style="width:90px;text-align: center;"><? echo  $countDays;  ?></div>
   <div  style="width:92px;text-align: center;"><? echo  $units_sold; ?></div>
   <div style="width:92px;text-align: center;"><? echo  number_format($ARS,2,'.',','); 
    if ($qty_on_hand < 1 && $real_count_days > 0)
 	{
   echo "<br><span style=\"font-size:10px;font-weight:bold;\">Real ARS: " . number_format($qtyInc/$real_count_days,2,'.',',') . "</span>";
   }
   ?></div>
   <div style="width:90px;text-align: center;"><b><? echo  $days_until_out; ?></b></div>
   <div  style="width:90px;text-align: center;"><b><? echo  $days_with_on_order; ?></b></div>
     <div  style="width:92px;text-align: center;"><b><? echo  $recomended_qty;
	 echo $earlyOrderMsg; 
	 echo $weeklySalesMsg; ?></b></div>
   <div style="width:92px;text-align: center;"> <?php echo "<input type='text' size='3' name='qty" . $partid . "' value='0'>"; ?></div>
</td>
 </tr>
 <?php 
 $countItems++;
 	}
 }
 ?>
 <script language="Javascript" src="cal/calendar.js">
 </script>
 </table>  
 </div>
     </td>
   </tr>
   </table>
   
<table cellspacing="0" cellpadding="1" border="1" width="100%">
  <tr valign="top">
 	  <td valign="top">
 	<table cellspacing="0" cellpadding="1" border="1" width="100%">
 		<tr>
 	  <td width="100"><b>total qty:</b></td>
 		<td width="100"><b><? echo number_format($totalInv,2,'.',','); ?></b></td>
 		  <td width="100"><b>total cost:</b></td>
 		<td width="100"><b><? echo "$" . number_format($totalCost,2,'.',','); ?></b></td>
 		</tr>
 	</table>
</td></tr></table>
<table cellspacing="0" cellpadding="1" border="1" width="100%">
 <tr valign="top">
     <td valign="top">
 	<table cellspacing="0" cellpadding="1" border="1" width="100%">
 <tr>
 <td class=menu>Order Number:<br> <input size="10" type="Text" name="ordernumber"></td>
 <td class=menu>Organization: <br>
 <?php 
 $result1 = mysql_query ("SELECT * FROM `organization` WHERE `active` = 1");
 echo "<select name=\"organization\">\r";
 if ($row = mysql_fetch_array($result1)) {
   do {
   if ($row["organization"] == $showSupplier)
		   $selected = "selected=\"selected\"";
		   else $selected = "";
   print "<option $selected value=\"" . $row["organization"]."\">" . $row["organization"]."\r";
	 } while($row = mysql_fetch_array($result1));
}
?>
</td>
 <td class=menu >Order Date: <br><input size="10" style="margin-right:10px;" type="Text" name="startdate" ><a href="javascript: void(0);" onClick="return getCalendar(document.create_order.startdate);" ><img src="cal/calendar.png" border="0" /></a>
 </td>
 <td class=menu>Delivery Date: <br><input size="10" style="margin-right:10px;" type="Text" name="enddate"><a href="javascript: void(0);" onClick="return getCalendar(document.create_order.enddate);"><img src="cal/calendar.png" border="0" /></a></td>
 <td class=menu>Status: <br>
 <?php
 $result1 = mysql_query ("select * from `status`");
  echo "<select name=\"status\">\r";
  if ($row = mysql_fetch_array($result1)) {
    do {
     $selected = "" ;
      if ($row["status"] == "Review")
 		  $selected="selected";
    print "<option $selected value=\"" . $row["status"]."\">" . $row["status"]."\r";
 	 } while($row = mysql_fetch_array($result1));
 }
 ?>
 </td>
 <td class=menu>Order Type:<br>
<?
$resultType = mysql_query ("SELECT * FROM ordertype");
 echo "<select name=\"orderType\">\r";
 if ($rowType = mysql_fetch_array($resultType)) {
   do {
/*	  $selected = "" ;
     if ($row["type"] == $selecttype)
	   $selected="selected";
*/   print "<option value=\"". $rowType["type"]."\" >". $rowType["type"]."\r";
	 } while($rowType = mysql_fetch_array($resultType));
}
?>
  </td>
 <td class=menu>
 <!--<input type="hidden" name="status" value="Initiated" />-->
 <input type="hidden" name="stage" value="Details Received" />
 <!-- <input type="hidden" name="orderType" value="Regular" />-->
 <input onClick="return confirm('Are you sure you want to Create this Order?')" type='submit' NAME='createOrder' value='Create Order' ></td>
  </tr>
 </table>
</td></tr></table>
 </form>
 <center><br><br>
 <button onClick="window.location='index.php'">Back to Main Menu</button> 
 <? include ("footer.inc"); 
 ?>
 