<?php
/**
 * @package admin
 * @copyright Copyright 2003-2011 Zen Cart Development Team
 * @copyright Portions Copyright 2003 osCommerce
 * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
 * @version $Id: category_product_listing.php 18695 2011-05-04 05:24:19Z drbyte $
 */
if (!defined('IS_ADMIN_FLAG')) {
  die('Illegal Access');
}

if (isset($_GET['set_display_categories_dropdown'])) {
  $_SESSION['display_categories_dropdown'] = $_GET['set_display_categories_dropdown'];
}
if (!isset($_SESSION['display_categories_dropdown'])) {
  $_SESSION['display_categories_dropdown'] = 0;
}
?>
<script language="javascript" type="text/javascript" src="../ajax/jquery.js"></script>
<script language="javascript" type="text/javascript" src="../ajax/jquery.form.js"></script>
<script language="javascript" type="text/javascript" src="../ajax/products_with_attributes_stock_ajax.js"></script>
<script language="javascript" type="text/javascript">

$('.searchTxtfieldC').bind('keyup', function(e) {
    if ( e.keyCode === 13 ) { // 13 is enter key
		$("#searchTxtfieldC").submit();
    }
});

$('.searchTxtfieldI').bind('keyup', function(e) {
    if ( e.keyCode === 13 ) { // 13 is enter key
		$("#searchTxtfieldI").submit();
    }

});

$('.searchTxtfieldM').bind('keyup', function(e) {
    if ( e.keyCode === 13 ) { // 13 is enter key
		$("#searchTxtfieldM").submit();
    }

});

$('.searchTxtfieldB').bind('keyup', function(e) {
    if ( e.keyCode === 13 ) { // 13 is enter key
		$("#searchTxtfieldB").submit();
    }

});


</script>
<style>
.searchform{
float:right;
}
td{
	font-size:150%;
	font-weight:bold;
}
</style>


    <table border="0" width="100%" cellspacing="0" cellpadding="2">

      <tr>
        <td><table border="0" width="100%" cellspacing="0" cellpadding="0">
          <tr>
            <td valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2">

<?php
    switch ($_SESSION['categories_products_sort_order']) {
      case (0):
        $order_by = " order by c.sort_order, cd.categories_name";
        break;
      case (1):
        $order_by = " order by cd.categories_name";
      case (2);
      case (3);
      case (4);
      case (5);
      case (6);
      }

    $categories_count = 0;
    $rows = 0;
	switch ($_SESSION['categories_products_sort_order']) {
      case (0):
        $order_by = " order by p.products_sort_order, pd.products_name";
        break;
      case (1):
        $order_by = " order by pd.products_name";
        break;
      case (2);
        $order_by = " order by p.products_model";
        break;
      case (3);
        $order_by = " order by p.products_quantity, pd.products_name";
        break;
      case (4);
        $order_by = " order by p.products_quantity DESC, pd.products_name";
        break;
      case (5);
        $order_by = " order by p.products_price_sorter, pd.products_name";
        break;
      case (6);
        $order_by = " order by p.products_price_sorter DESC, pd.products_name";
        break;
      }
	

		$products_query_raw = ("select p.products_id,p.products_type, pd.products_name, p.products_quantity,p.products_quantity_b1,p.products_quantity_b2,p.products_point,
                                       p.products_image, p.products_price, p.products_date_added,p.suppliers_id,p.manufacturers_id,products_warrenty,
                                       p.products_last_modified, p.products_date_available,
									   p.barcode,
										p.reorder_stock,
										p.min_stock,
										p.note,
										p.location,
										p.flagstatus as pfstatus,
										p.flagstatus2 as pfstatus2,
										att.flagstatus as afstatus,
										att.flagstatus2 as afstatus2,
										att.stock_attributes,
										att.quantity as aquantity,
										att.location as alocation,
                                       p.products_status, p2c.categories_id,
                                       p.products_model, products_weight, cost_price,
                                       p.products_quantity_order_min, p.products_quantity_order_units, p.products_priced_by_attribute,p.preorder,
                                       p.product_is_free, p.product_is_call, p.products_quantity_mixed, p.product_is_always_free_shipping,
                                       p.products_quantity_order_max, p.products_sort_order,
                                       p.master_categories_id
                                from " . TABLE_PRODUCTS . " p left outer join zen_products_with_attributes_stock att on att.products_id = p.products_id, " . TABLE_PRODUCTS_DESCRIPTION . " pd, "
                                       . TABLE_PRODUCTS_TO_CATEGORIES . " p2c
                                       
                                where p.products_id = pd.products_id
                                and pd.language_id = '" . (int)$_SESSION['languages_id'] . "'
                                and (p.products_id = p2c.products_id
                                and p.master_categories_id = p2c.categories_id)
                                and (p.flagstatus !=0
								or p.flagstatus2 !=0
								or att.flagstatus2 !=0
								or att.flagstatus !=0
								)
                                order by pfstatus2,afstatus2,pfstatus,afstatus" );

    
// Split Page
// reset page when page is unknown
if (($_GET['page'] == '1' or $_GET['page'] == '') and $_GET['pID'] != '') {
  $old_page = $_GET['page'];
  $check_page = $db->Execute($products_query_raw);
  
  if($check_page->RecordCount() == 0)
  {
	echo("<h3>No Data</h3>");
	die;
  }
  
  if ($check_page->RecordCount() > MAX_DISPLAY_RESULTS_CATEGORIES) {
    $check_count=1;
    while (!$check_page->EOF) {
      if ($check_page->fields['products_id'] == $_GET['pID']) {
        break;
      }
      $check_count++;
      $check_page->MoveNext();
    }
    $_GET['page'] = round((($check_count/MAX_DISPLAY_RESULTS_CATEGORIES)+(fmod_round($check_count,MAX_DISPLAY_RESULTS_CATEGORIES) !=0 ? .5 : 0)),0);
    $page = $_GET['page'];
    if ($old_page != $_GET['page']) {
//      zen_redirect(zen_href_link(FILENAME_CATEGORIES, 'cPath=' . $_GET['cPath'] . '&pID=' . $_GET['pID'] . (isset($_GET['page']) ? '&page=' . $_GET['page'] : '')));
    }
  } else {
    $_GET['page'] = 1;
  }
}

    $products_split = new splitPageResults($_GET['page'], MAX_DISPLAY_RESULTS_CATEGORIES, $products_query_raw, $products_query_numrows);
    $products = $db->Execute($products_query_raw);
// Split Page
if(file_exists(DIR_WS_CLASSES . 'products_with_attributes_stock.php'))
{
	require(DIR_WS_CLASSES . 'products_with_attributes_stock.php');
	$stock = new products_with_attributes_stock;
	$attributeenabled = true;
}else{
	$attributeenabled = false;
}


    while (!$products->EOF) {
      $products_count++;
      $rows++;
		?>
	  
				
					
				<tr class="dataTableRow" >
				
				<table width="100%">
				<tr>
				<td class="dateTableContent" rowspan="2" width="20%">
				<?php 		
				if ($products->fields['products_image'] != '') {
				 echo ''. zen_image(DIR_WS_CATALOG . DIR_WS_IMAGES . $products->fields['products_image'] , $order->products[$i]['name'], 100, 100) . '</a>&nbsp';
				}
                else {echo '<img src="images/noimage.gif">' ;} ?>
				</td>
				
				
          		<td colspan="4" class="dataTableContent" ><?php echo $products->fields['products_name']; ?></td>
				</tr>
				<tr>
				<td class="dataTableContent" width="40%" align="left">(<?php echo $products->fields['products_id']; ?>)</td>
				<td></td>
				
				<td class="dataTableContent" align="right" colspan="2"><?php echo str_replace("<br />","",str_replace("Product is Call for Price","",str_replace("http://black-tactical.com/store/includes/templates/template_default/images/call_for_prices.gif","",str_replace('http://migration.black-tactical.com/store/includes/templates/template_default/images/call_for_prices.gif',"",zen_get_products_display_price($products->fields['products_id']))))); ?></td>
				</tr>
				
				<?php
					//check is it attribute or main ?
					if($products->fields['pfstatus'] !=0 || $products->fields['pfstatus2'] !=0)	//main
					{
				?>
				
				<tr>
				<td colspan="2">&nbsp;</td>
				
				<td class="dataTableContent " align="right" <?php echo('id="qtyid-'.$products->fields['products_id'].'"'); ?>>
				<input  style="padding:5px;width:45px;font-size:120%;" onkeypress="javascript: if(event.keyCode == 13) update_quantity(this.value,'<?php echo('qtyid-'.$products->fields['products_id']); ?>',this)" type="text" name="<?php echo('qtyid-'.$products->fields['products_id']); ?>" id="<?php echo('qtyid-'.$products->fields['products_id']); ?>" value="<?php echo $products->fields['products_quantity'];?>" size="8"/>
				
				</td>
				<td class="dataTableContent " align="center" <?php echo('id="locationid-'.$products->fields['products_id'].'"'); ?>>
				
				<input onkeypress="javascript: if(event.keyCode == 13){ update_location(this.value,'<?php echo('locationid-'.$products->fields['products_id']); ?>',this); }" type="text" name="<?php echo('locationid-'.$products->fields['products_id']); ?>" id="<?php echo('locationid-'.$products->fields['products_id']); ?>" value="<?php
						if($products->fields['location'] == ""){echo("?");}else{
							echo $products->fields['location'];} ?>" size="8" style="padding:5px;width:50px;font-size:120%;"/>
				
				
				</td>
				<td class="dataTableContent stockAttributesCellAlert" style="white-space: nowrap;" align="right" <?php echo('id="alertid-'.$products->fields['products_id'].'"'); ?>>
					<?php if($products->fields['pfstatus'] ==1 ){
					?>
						<input style="background-color:blue;text-align:center;font-weight:bold;" onclick="update_flag('alertid-<?= $products->fields['products_id']?>','0',this,'1');" type="button" value="P"/>
					<?php
					}
					if($products->fields['pfstatus2'] ==1 )
					{
					?>
						<input style="background-color:green;text-align:center;font-weight:bold;" onclick="update_flag('alertid-<?= $products->fields['products_id']?>','0',this,'2');" type="button" value="R"/>
					<?php	
					}?>
				
				</td>
				</tr>
				<?php
				}else if($products->fields['afstatus'] !=0 || $products->fields['afstatus2'] !=0){
				?>
				
				<tr>
				<td colspan="2">
				<?php
							
				
							if (strpos($products->fields['stock_attributes'], ',') !== false)
							{
								$attlist = explode( "," , $products->fields['stock_attributes'] );
								$firstatt = true;
								foreach($attlist as $attid)
								{
									$query = 'select pval.products_options_values_name as pname
									from '.TABLE_PRODUCTS_ATTRIBUTES.' as patrib, '.TABLE_PRODUCTS_OPTIONS.' as popt, '.TABLE_PRODUCTS_OPTIONS_VALUES.' as pval
									where patrib.products_attributes_id = "'.$attid.'"
									AND patrib.options_id = popt.products_options_id
									AND popt.language_id = "1"
									and popt.language_id = pval.language_id
									and patrib.options_values_id = pval.products_options_values_id';
									
									$attributes = $db->Execute($query);
									if($firstatt)
									{
										$firstatt = false;
									}else{
										$attname .= " : ";
									}
									
									$attname .= $attributes->fields["pname"];
									
								}
							}
							else
							{
								$query = 'select pval.products_options_values_name as pname
								from '.TABLE_PRODUCTS_ATTRIBUTES.' as patrib, '.TABLE_PRODUCTS_OPTIONS.' as popt, '.TABLE_PRODUCTS_OPTIONS_VALUES.' as pval
								where patrib.products_attributes_id = "'.$products->fields['stock_attributes'].'"
									AND patrib.options_id = popt.products_options_id
									AND popt.language_id = "1"
									and popt.language_id = pval.language_id
									and patrib.options_values_id = pval.products_options_values_id';
									
									$attributes = $db->Execute($query);
									$attname = $attributes->fields["pname"];
							}
							echo("(".$products->fields['stock_attributes'].") - ".$attname);
				?>
				
				</td>
				
					<td class="dataTableContent " align="right" <?php echo('id="stockid-'.$products->fields['stock_attributes'].'"'); ?>>
					
					<input  style="padding:5px;width:45px;font-size:120%;" onkeypress="javascript: if(event.keyCode == 13) update_quantity(this.value,'<?php echo('stockid-'.$products->fields['stock_attributes']); ?>',this)" type="text" name="<?php echo('stockid-'.$products->fields['stock_attributes']); ?>" id="<?php echo('stockid-'.$products->fields['stock_attributes']); ?>" value="<?php echo $products->fields['aquantity']; ?>" size="8"/>
						
					
					<td class="dataTableContent " align="center" <?php echo('id="stockid-'.$products->fields['stock_attributes'].'"'); ?>><input onkeypress="javascript: if(event.keyCode == 13) update_location(this.value,'<?php echo('stockid-'.$products->fields['stock_attributes']); ?>',this)" type="text" name="<?php echo('stockid-'.$products->fields['stock_attributes']); ?>" id="<?php echo('stockid-'.$products->fields['stock_attributes']); ?>" value="<?php
						if($products->fields['alocation'] == ""){echo("?");}else{
							echo $products->fields['alocation'];} ?>" size="8" style="padding:5px;width:50px;font-size:120%;"/>
						
					</td>

				
				<td class="dataTableContent stockAttributesCellAlert" style="white-space: nowrap;" align="right" <?php echo('id="alertid-'.$products->fields['products_id'].'"'); ?>>
					<?php if($products->fields['afstatus'] ==1 ){
					?>
						<input style="background-color:blue;text-align:center;font-weight:bold;" onclick="update_flag('stockid-<?= $products->fields['stock_attributes']?>','0',this,'1');" type="button" value="P"/>
					<?php
					}
					
					if($products->fields['afstatus2'] ==1 )
					{
					?>
						<input style="background-color:green;text-align:center;font-weight:bold;" onclick="update_flag('stockid-<?= $products->fields['stock_attributes']?>','0',this,'2'); " type="button" value="R"/>
					<?php	
					}?>
				</td>
				</tr>
				
				
				<?php
				}
				?>
				</table>
				
				</tr>
				<tr><td><hr/></td></tr>
				
				
				
				
				
				
			
<?php
      $products->MoveNext();
    }

    $cPath_back = '';
    if (sizeof($cPath_array) > 0) {
      for ($i=0, $n=sizeof($cPath_array)-1; $i<$n; $i++) {
        if (empty($cPath_back)) {
          $cPath_back .= $cPath_array[$i];
        } else {
          $cPath_back .= '_' . $cPath_array[$i];
        }
      }
    }

    $cPath_back = (zen_not_null($cPath_back)) ? 'cPath=' . $cPath_back . '&' : '';
?>


            </table>
			
			</td>

<script>
function update_location(stock_value, stock_id, obj)
{

	if (window.ActiveXObject) 
      httpObject =  new ActiveXObject("Microsoft.XMLHTTP");
   else if (window.XMLHttpRequest) 
      httpObject =  new XMLHttpRequest();
   else {
      httpObject = null;
   }
   if (httpObject != null) {
		httpObject.open("GET", "update_location.php?stock_attribute="+stock_id+"&stock_location="+stock_value, true);

      httpObject.send(null);

      httpObject.onreadystatechange = function (){
		if(httpObject.readyState == 4){
			$(obj).css("background-color", "#81F7BE");
			//obj.parentNode.innerHTML = stock_value;
		}else{
			$(obj).css("background-color", "#F78181");
		}
	  }
   }
}

function update_quantity(stock_value, stock_id,obj )
{
	if (window.ActiveXObject) 
      httpObject =  new ActiveXObject("Microsoft.XMLHTTP");
   else if (window.XMLHttpRequest) 
      httpObject =  new XMLHttpRequest();
   else {
      httpObject = null;
   }
   if (httpObject != null) {
		httpObject.open("GET", "update_attribute.php?stock_attribute="+stock_id+"&stock_quantity="+stock_value, true);

      httpObject.send(null);

      httpObject.onreadystatechange = function (){
		if(httpObject.readyState == 4){
			$(obj).css("background-color", "#81F7BE");
		}else{
			$(obj).css("background-color", "#F78181");
		}
	  }
   }
}

function update_flag(stock_id, stock_value , obj,index)
{

	if (window.ActiveXObject) 
      httpObject =  new ActiveXObject("Microsoft.XMLHTTP");
   else if (window.XMLHttpRequest) 
      httpObject =  new XMLHttpRequest();
   else {
      httpObject = null;
   }
   if (httpObject != null) {
		httpObject.open("GET", "update_flag.php?stock_attribute="+stock_id+"&action="+stock_value+"&index="+index, true);

      httpObject.send(null);

      httpObject.onreadystatechange = function (){
		if(httpObject.readyState == 4){
			window.location.reload();
			obj.style.backgroundColor = "grey";
		
		}
			
		}
   }
   
}
</script>