<?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="http://code.jquery.com/jquery-1.7.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_sc.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;
}

.stockAttributesCellLocation{
	cursor:pointer;
}

.stockAttributesCellLocation:hover{
	cursor:pointer;
}

</style>
<div style="padding:10px;">
<form>
<input type="text" placeholder="Search Name/Model/ID" name="search" style="width:100%;height:40px"/>
</form>
</div>

    <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;
      }
	
    if (isset($_GET['search'])) {
      $search = zen_db_prepare_input($_GET['search']);
	  $searchtype = $_GET['searchType'];
	  
	  
		$products_query_raw = ("select DISTINCT 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,
										p.flagstatus2,
                                       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.barcode = '" . zen_db_input($_GET['search']) . "'
                                or att.attribute_barcode = '" . zen_db_input($_GET['search']) . "'
                                or p.products_model like '%" . zen_db_input($_GET['search']) . "%'
                                or att.attribute_model like '%" . zen_db_input($_GET['search']) . "%'
								or pd.products_id = '" . zen_db_input($_GET['search']) . "'
								or pd.products_name like '%" . zen_db_input($_GET['search']) . "%'
								)
                                ".$order_by);
	}else{
	
	echo("<h3>Please Perform A Search</h3>");
	
	die;
	
	}
    
// 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() > 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
				//first check if stock have attributes
				if($attributeenabled)
				{
					//$checkstock = $stock->get_products_attributes($products->fields['products_id']);
					
					$checkstock = $db->EXECUTE("SELECT a.stock_attributes AS id, a.attribute_model,a.attribute_barcode, a.quantity, a.quantity_b1, a.quantity_b2, a.reorder_stock, a.min_stock, a.note,a.location,a.flagstatus,a.flagstatus2
					FROM zen_products_with_attributes_stock AS a
					LEFT JOIN zen_products_attributes AS b ON a.stock_attributes = b.products_attributes_id
					INNER JOIN zen_products_options_values as c ON b.options_values_id = c.products_options_values_id
					WHERE a.products_id = '".$products->fields['products_id']."' AND b.products_attributes_id order by c.products_options_values_sort_order asc");	
				}
				
				//have some attributes
				
				if($checkstock != null && $checkstock->resource->num_rows !=0){
					while(!$checkstock->EOF)
					{
					?>
						<tr>
						<td  colspan="2"><?php
							$attname = "";
							if (strpos($checkstock->fields['id'], ',') !== false)
							{
								$attlist = explode( "," , $checkstock->fields['id'] );
								$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 = "'.$checkstock->fields['id'].'"
									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("(".$checkstock->fields['id'].") - ".$attname);
						
						?></td>
						
						<td class="dataTableContent " align="right" <?php echo('id="stockid-'.$checkstock->fields['id'].'"'); ?>>
						
						<input  style="padding:5px;width:45px;font-size:120%;" onkeypress="javascript: if(event.keyCode == 13) update_quantity(this.value,'<?php echo('stockid-'.$checkstock->fields['id']); ?>',this)" type="text" name="<?php echo('stockid-'.$checkstock->fields['id']); ?>" id="<?php echo('stockid-'.$checkstock->fields['id']); ?>" value="<?php echo $checkstock->fields['quantity']; ?>" size="8"/>
						
						

						</td>
						<td class="dataTableContent " style="cursor: pointer;" align="center" <?php echo('id="stockid-'.$checkstock->fields['id'].'"'); ?>>
						
						<input onkeypress="javascript: if(event.keyCode == 13) update_location(this.value,'<?php echo('stockid-'.$checkstock->fields['id']); ?>',this)" type="text" name="<?php echo('stockid-'.$checkstock->fields['id']); ?>" id="<?php echo('stockid-'.$checkstock->fields['id']); ?>" value="<?php
						if($checkstock->fields['location'] == ""){echo("?");}else{
							echo $checkstock->fields['location'];} ?>" size="8" style="padding:5px;width:50px;font-size:120%;"/>
						
							
						<?php
						//if($checkstock->fields['location'] == ""){echo("?");}else{
						//	echo $checkstock->fields['location'];} ?>
						
						</td>
						<td class="dataTableContent stockAttributesCellAlert" style="white-space: nowrap;" align="right" <?php echo('id="alertid-'.$checkstock->fields['products_id'].'"'); ?>>
						<input style="background-color:<?php if ($checkstock->fields['flagstatus'] ==1 ){echo("grey");}else{echo("blue");}?>;text-align:center;font-weight:bold;" onclick="update_flag('stockid-<?= $checkstock->fields['id']?>','1',this,'1')" type="button" value="P"/>
						<input style="background-color:<?php if ($checkstock->fields['flagstatus2'] ==1 ){echo("grey");}else{echo("green");}?>;text-align:center;font-weight:bold;" onclick="update_flag('stockid-<?= $checkstock->fields['id']?>','1',this,'2')" type="button" value="R"/>
						
						</td>
						</tr>
				
				<?php
					$checkstock->MoveNext();
					}
					
				}else{
				
				?>
				
				<tr>
				<td>&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" style="cursor: pointer;" align="center" <?php echo('id="locationid-'.$products->fields['products_id'].'"'); ?>>
				
				<?php
				/*
				<input onkeypress="javascript: if(event.keyCode == 13) update_location(this.value,'<?php echo('locationid-'.$products->fields['products_id']); ?>',this);" onblur="" 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%;"/>
				*/
				?>
				
				<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%;"/>
				
				
				
							
							
				
				<?php 
				//if($products->fields['location'] == ""){echo("?");}else{
				//echo $products->fields['location'];} ?>
				</td>
				<td class="dataTableContent stockAttributesCellAlert" style="white-space: nowrap;" align="right" <?php echo('id="alertid-'.$products->fields['products_id'].'"'); ?>>
					<input style="background-color:<?php if($products->fields['flagstatus'] ==1 ){echo("grey");}else{echo("blue");}?>;text-align:center;font-weight:bold;" onclick="update_flag('alertid-<?= $products->fields['products_id']?>','1',this,'1')" type="button" value="P"/>
					<input style="background-color:<?php if($products->fields['flagstatus2'] ==1 ){echo("grey");}else{echo("green");}?>;text-align:center;font-weight:bold;" onclick="update_flag('alertid-<?= $products->fields['products_id']?>','1',this,'2')" type="button" value="R"/>
				</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){
		
			obj.style.backgroundColor = "grey";
		
		}
			
		}
   }
   
}
</script>