<?php 
include "includes/config.php";
include "includes/session.php";
include "includes/functions.php";
include_once "classes/cls_products.php";
if (get_magic_quotes_gpc()) {
	$_POST = array_map('stripslashes_deep', $_POST);
	$_GET = array_map('stripslashes_deep', $_GET);
	$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
}
if(isset( $_SESSION["sess_userid"]) and $_SESSION["sess_userid"]!= "") {
	$userid = $_SESSION["sess_userid"];
}

$currency_attributes = displayCurrencyType();
/*if(isset( $_GET["begin"]) and $_GET["begin"]!= ""){
 $begin = $_GET["begin"];
}else{
$begin = 0;
}
if(isset( $_GET["num"]) and $_GET["num"]!= ""){
$num = $_GET["num"];
}else{
$num = 0;
}
if(isset( $_GET["numBegin"]) and $_GET["numBegin"]!= ""){
$numBegin = $_GET["numBegin"];
}else{
$numBegin = 0;
}*/

$ddlCategory = $_REQUEST['ddlCategory']; 
$ddlCategory=stripslashes($ddlCategory);

if(isset( $_POST["sd"]) and $_POST["sd"]!= "") {
	$sd = $_POST["sd"];
}else {
	$sd = $_GET["sd"];
}

if(isset( $_POST["txtSearch"]) and $_POST["txtSearch"]!= "") {
	$txtSearch = $_POST["txtSearch"];
}else {
	$txtSearch = $_GET["txtSearch"];
}

$txtSearchtext=htmlspecialchars(strip_tags(trim($txtSearch)));

$txtSearch = htmlspecialchars(strip_tags(trim($txtSearch)));

if(isset( $_POST["chkProductName"]) and $_POST["chkProductName"]!= "") {
	$chkProductName = $_POST["chkProductName"];
	if($chkProductName == "on") {
		$chkProductName = "1";
	}
}else if(isset( $_GET["chkProductName"]) and $_GET["chkProductName"]!= "") {
	$chkProductName = $_GET["chkProductName"];
	if($chkProductName == "on") {
		$chkProductName = "1";
	}
}else {
	$chkProductName = $_GET["pn"];
}

if(isset( $_POST["chkProductDescription"]) and $_POST["chkProductDescription"]!= "") {
	$chkProductDescription = $_POST["chkProductDescription"];
	if($chkProductDescription == "on") {
		$chkProductDescription = "1";
	}
}else {
	$chkProductDescription = $_GET["pd"];
}

if(isset( $_POST["chkProductTags"]) and $_POST["chkProductTags"]!= "") {
	$chkProductTags = $_POST["chkProductTags"];
	if($chkProductTags == "on") {
		$chkProductTags = "1";
	}
}

if(isset( $_POST["chkProductArtist"]) and $_POST["chkProductArtist"]!= "") {
	$chkProductArtist = $_POST["chkProductArtist"];
	if($chkProductArtist == "on") {
		$chkProductArtist = "1";
	}
}else {
	$chkProductArtist = $_GET["ps"];
}
if(isset( $_POST["chkIncludeSubcategories"]) and $_POST["chkIncludeSubcategories"]!= "") {
	$chkIncludeSubcategories = $_POST["chkIncludeSubcategories"];
	if($chkIncludeSubcategories == "on") {
		$chkIncludeSubcategories = "1";
	}
}else if(isset( $_GET["chkIncludeSubcategories"]) and $_GET["chkIncludeSubcategories"]!= "") {
	$chkIncludeSubcategories = $_GET["chkIncludeSubcategories"];
	if($chkIncludeSubcategories == "on") {
		$chkIncludeSubcategories = "1";
	}
}else {
	$chkIncludeSubcategories = $_GET["isc"];
}

if($ddlCategory!='') {
	if($chkIncludeSubcategories == "1") {
		$categorylist  = implode(",",getCategoryDescendants($ddlCategory));
	}else {
		$categorylist  = $ddlCategory;
	}
}

if(isset($_POST["btnSearch"])) {
	$sd=1;
}else if($_GET["sd"] =="1") {
	$sd=1;
}
$where = "";

if($chkProductName == "1") {
	$where .= '  AND (( p.product_name LIKE "%'.mysql_real_escape_string($txtSearch).'%" )';  
        $searchWords = explode(" ", $txtSearch);  
        foreach ($searchWords as $value) { 
            $where .= ' OR (p.product_tags LIKE "%'.mysql_real_escape_string($value).'%" )';
        }    
        //$where .= ')';
        
}

if($chkProductTags == "1" && $chkProductName !='1'){
   $where .= '  AND (( p.product_tags LIKE "%'.mysql_real_escape_string($txtSearch).'%" )';
        $searchWords = explode(" ", $txtSearch);  
     foreach ($searchWords as $value) { 
         $where .= ' OR (p.product_tags LIKE "%'.mysql_real_escape_string($value).'%" )';
     }    
     //$where .= ')';    
}

if($chkProductDescription == "1") {

	$where .= '  AND  ( p.product_description LIKE "%'.mysql_real_escape_string($txtSearch).'%") ';

}
if($chkProductArtist == "1") {
    
    $where = '';
    
    $where .="  AND (CONCAT(s.artist_name,s.first_name, s.last_name,s.storename) REGEXP ('".mysql_real_escape_string($txtSearch).".*$'))";

	//$where .= '  AND  (s.artist_name LIKE "%'.mysql_real_escape_string($txtSearch).'%" || s.first_name LIKE "%'.mysql_real_escape_string($txtSearch).'%" || s.last_name LIKE "%'.mysql_real_escape_string($txtSearch).'%" ||  s.company LIKE "%'.mysql_real_escape_string($txtSearch).'%" ) ';
if($chkProductName == "1") {
	$where .= '  OR  (( p.product_name LIKE "%'.mysql_real_escape_string($txtSearch).'%" ) ';


}

if($chkProductTags == "1")
    {
       $where .= '  OR (';
       
       if($chkProductName != "1" && $chkProductTags != "1" && $chkProductDescription != "1" && $chkProductArtist != "1")
          $where .= '(';
       
       $where .= ' p.product_tags LIKE "%'.mysql_real_escape_string($txtSearch).'%" )';
        $searchWords = explode(" ", $txtSearch);
         foreach ($searchWords as $value) {
             $where .= ' OR (p.product_tags LIKE "%'.mysql_real_escape_string($value).'%" )';
         }
        //$where .= ')'; 
    }
    
}

/*-------Multicart 2.0 Upgradation starts------*/

//echo $categorylist;

if(isNotNull($categorylist)) {

	$where .= " AND p.product_category IN ($categorylist) ";

}
else if($txtSearch!=""){
        
        $categorylist = Products::getCategoryHierarchy($txtSearch,'',$category_list = array());
        
 
        
        
        if(!empty($categorylist))
        {
           $categorylist = implode(",", array_unique($categorylist));
           $where .= " AND p.product_category IN ($categorylist) ";
        }
}

/*-------Multicart 2.0 Upgradation ends------*/
//***************************Product Listing  Modifications for Scalability **********************
     $sql = Products::getProduct_list_Join_Search_Query();

     if($chkProductName == "1" || $chkProductTags == "1" )
     $where .= ')';
     
    //$orderBy    =    "p.product_id DESC"
      $sql = $sql.$where ." ORDER BY p.product_id DESC";

//***************************Product Listing  Modifications for Scalability End**********************

$ddlSelectedCategory=str_replace("'", "", stripslashes($ddlCategory));

if(!(isset($pagenum))) {
	$pagenum = 1;
}
$limit=getPaginationLimit();

//$result=mysql_query($sql) or die(mysql_error());




$productCountQuery      =   Products::getProduct_list_Join_Search_Query_Count();
$resultRow              =   mysql_query($productCountQuery.$where);   
$totalrows              =   mysql_result($resultRow,0,"cnt");


if(empty($page)) {
	$page = 1;
}

$limit=getPaginationLimit();

if($limit==0) {
	$limit=12;
}

$sql_qr=dopaging($sql,'',$limit);

$result=mysql_query($sql_qr) or die(mysql_error());


$catlist = make_selectlist(0, 0);

/*display the active template*/

$active_template = displayTemplate();
include "includes/htmltop.php";
/* Top File Name */
include_once ("includes/".$active_template[0]);
?>
<!--mainbody area start -->
<div class="main_body">
	<div class="container">
		<div class="row">			
	<!--center content area start-->
	<form name="frmSearch" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, 'UTF-8') ?>" method="POST">
		<input type="hidden" name="sd" value="<?php echo $sd;?>">
		
		<section class="sec_marg">
		<div class="col-sm-12 col-lg-12 col-md-12 ">
			<h3 id="items_top_area_ttl"><?php echo SEARCH_BUTTON;?></h3>
		</div>
		</section>
		<div class="clear"></div>
		
		<div align="left" id="item_details">
			<!--items display area start -->
			<div class="col-sm-12 col-lg-12 col-md-12 ">
				<div class="text_information" align="center">
					<?php echo $message?>
				</div>
			</div>
			<div class="col-sm-12 col-lg-12 col-md-12 ">
			<div class="search_list_box">
				<div class="row">
				<div class="search_list_box_row">
					<div class="col-sm-12 col-lg-2 col-md-2">
						<div class="field_wrapper formfield_row"><?php echo SEARCH_FOR_TEXT;?></div>
					</div>
					<div class="col-sm-12 col-lg-5 col-md-5">
						<div class="field_wrapper formfield_row">
							<input type="text" class="form-control" value="<?php echo (stripslashes($txtSearchtext));?>" name="txtSearch" size="30" maxlength="100">
						</div>
					</div>
					<div class="col-sm-12 col-lg-5 col-md-5">
						&nbsp;
					</div>
				</div>
				<div class="clear"></div>
				<div class="search_list_box_row">
					<div class="col-sm-12 col-lg-2 col-md-2">
						<div class="field_wrapper formfield_row"><?php echo CATERGORY_IN_TEXT;?></div>
					</div>
					<div class="col-sm-12 col-lg-5 col-md-5">
						<div class="field_wrapper formfield_row">
							<?php echo makeDropDownList("ddlCategory", $catlist, $ddlSelectedCategory, true, "form-control", $properties, $behaviors)?>
						</div>
					</div>
					<div class="col-sm-12 col-lg-5 col-md-5">
						<span class="spansearch_check"><input type="checkbox" class="checkbox" name="chkIncludeSubcategories"
						<?php if($chkIncludeSubcategories == "1") {
							echo " CHECKED ";
						}?>></span> <span class="spansearch_name"> <?php echo SUB_CATEGORY_INCLUDE_TEXT;?></span>
					</div>
				</div>
				<div class="clear"></div>
				<div class="search_list_box_row">
					<div class="col-sm-12 col-lg-2 col-md-2">
						<div class="field_wrapper formfield_row"><?php echo MATCH_WITH_TEXT;?></div>
					</div>
					<div class="col-sm-12 col-lg-5 col-md-5">
						<div class="field_wrapper formfield_row">
							<div class="linksCopy2">
									<div class="match_with_blocks">
										<span class="spansearch_check">
											<input type="checkbox" name="chkProductName"
										class="checkbox"
										<?php if($chkProductName == "1") {
											echo " CHECKED ";
										}?>>
										</span>
										<span class="spansearch_name"><?php echo PRODUCT_NAME_TEXT1;?> </span>
									</div>
									<div class="clear"></div>
									<div class="match_with_blocks">
										<span class="spansearch_check">
										<input type="checkbox" name="chkProductTags"
											class="checkbox"
											<?php if($chkProductTags == "1") {
												echo " CHECKED ";
											}?>> 
										</span>
										<span class="spansearch_name"><?php echo PRODUCT_TAG_TEXT;?></span>
									</div>
									<div class="clear"></div>                                                                        
									<div class="match_with_blocks">
										<span class="spansearch_check">
										<input type="checkbox" name="chkProductDescription"
											class="checkbox"
											<?php if($chkProductDescription == "1") {
												echo " CHECKED ";
											}?>> 
										</span>
										<span class="spansearch_name"><?php echo PRODUCT_DESCRIPTION_TEXT;?></span>
									</div>
									<div class="clear"></div>
									<div class="match_with_blocks">
										<span class="spansearch_check">
										<input type="checkbox" name="chkProductArtist"
										class="checkbox"
										<?php if($chkProductArtist == "1") {
											echo " CHECKED ";
										}?>> 
										</span>
										<span class="spansearch_name"><?php echo PRODUCT_SELLER_TEXT;?></span>
									</div>
								</div>
						</div>
					</div>
					<div class="col-sm-12 col-lg-5 col-md-5">
						&nbsp;
					</div>
				</div>
				<div class="clear"></div>
				<div class="search_list_box_row">
					<div class="col-sm-12 col-lg-2 col-md-2">
						<div class="field_wrapper formfield_row">&nbsp;</div>
					</div>
					<div class="col-sm-12 col-lg-5 col-md-5">
						<div class="field_wrapper formfield_row">
							<input type="submit" value="<?php echo SEARCH_BUTTON;?>" name="btnSearch"
											class="login_btn">
						</div>
					</div>
					<div class="col-sm-12 col-lg-5 col-md-5">
						&nbsp;
					</div>
				</div>
				</div>
			<div class="clear"></div>
			</div>
			</div>
			<div class="clear"></div>
			
			<div align="center" id="items_display_area" >
				<?php
				if($sd==1) {
                    ?>
							<div class="search_details">
								<?php
								$prodimagedir = "products/";
								if(mysql_num_rows($result) > 0 ) {
                                        $i=1;
                                        $cells =4;
                                        $count_row = 1;
                                        $product_image  =   "";
                                        while($row = mysql_fetch_array($result)) {
                                            $product_image = "";
                                            $i++;
                                            $link = "<a  href='productdetails.php?productid=".$row["product_id"]."'>";
                                            $check = "<input type='checkbox' name='chkproducts[]' value='" . $row["product_id"] . "' >";
                                            $price = $row['product_price'];

                                            // Image Selection Modification // Done By Asha
   
                    $imageurl = '';
                     if ($row["default_image_small"] != "") {
                        $product_image = $row["default_image_small"];
                    }  // end if product image null check

                    if ($product_image == "") {
                        $imageurl = $site_url . "/" . $prodimagedir . "noimage.jpg";
                    } else {
                        if (strstr($product_image, "http://") || strstr($product_image, "https://")) {
                            $imageurl = $product_image;
                        } else {
                            if(ENABLE_AMAZON_S3_IMAGES=="Y")
                                $imageurl = AMAZON_S3_DOMAIN_URL.$prodimagedir . $product_image ;
                            else
                                $imageurl = $site_url . "/" . $prodimagedir . $product_image;
                        }
                    }




                    $imageurl = "<img class='product_img' src='" . $imageurl . "' border='0' >";
// Image Listing Modification End
                                      $discountstr="";

                                       if($row["default_stock"] > 0) {
                                                $productinstock = true;
                                            }
                                            else {
                                                $productinstock = false;
                                            }

                                            $conversionRate	= ConvertedCurrencyRate($currency_attributes[2]);
                                            $converted_price = $price * $conversionRate;
                                            
                                           
                                            $discountprice=0;

                                            if($row["default_discount"] !="0") {
                                                $discountprice=$converted_price- ($converted_price*$row["default_discount"])/100;
                                                $discountprice =number_format($discountprice,2,".","");
                                                $discountstr="<br>".strtolower(MAIL_ORDER_TEXT_DISCOUNT)."(".$row["default_discount"]."%)";

                                            }

                                            $display_product_price = number_format($converted_price,2,".","");

                                            /********************Multicart 3.0 Modifications******************************************/

                                             $SEOFriendlyLink = getOptimisedLink(SITE_URL, $row["product_category"], $row["alias"]);

                                             $subscriptionFlag   =    Products::is_subscription_product($row["product_id"]);

                                              
                                        /********************Multicart 3.0 Modifications******************************************/
                    
                                            ?>

								 <div class="col-sm-12 col-lg-4 col-md-4">
								<div class="products" <?php if ($count_row == 4) { ?> style="margin-right:0px;"  <?php } ?>>
									
										<a class="product_anchor" href="<?php echo $SEOFriendlyLink;?>">
											<div class="imgblock">
												<?php echo $imageurl?>
											</div>
										</a>
                                                                   
										<!--GreenOver-->
										<div class="prod_green" id="<?php echo $row["product_id"];?>" data="<?php echo $SEOFriendlyLink;?>">
											<div class="prodover_blk">
												<?php
												if ($productinstock) {
													?>
                                                                                                    <?php  // Hide Shop now Button for Subscription Items
                                                                                                       if(!$subscriptionFlag) { ?>
                                                                                                                <div class="prodover_blk_row">


                                                                                                                        <div class="adtocart_tbn_blk cart_btn_home">
                                                                                                                                <a class="adtocart" href="<?php echo SITE_URL?>/homepage_addtocart.php?productid=<?php echo $row["product_id"]?>&product_option_id=<?php echo $row["default_option_id"]?>" class="add_cart_small"><?php echo ADD_TO_CART_TEXT; ?></a>
                                                                                                                                <div class="clear"></div>
                                                                                                                        </div>

                                                                                                                </div>
                                                                                                    <?php } ?>
													<div class="clear"></div>
													<?php
												} else {
													?>
													<div class="prodover_blk_row">
														<div class="adtocart_tbn_blk cart_btn_home">
															<img src="<?php echo SITE_URL?>/images/home_outfstock.gif" alt="<?php echo OUT_STOCK_TEXT;?>" border="0" />
														</div>
														<div class="clear"></div>  
													</div>
													<div class="clear"></div>
													<?php
												}
												?>
											</div>
										</div>
										<!--GreenOver:End-->
										<h5><a href="<?php echo $SEOFriendlyLink ?>" title="<?php echo stripslashes(ucwords($row["product_name"])); ?>">
												<?php if(strlen($row["product_name"])>25){
												 echo stripslashes(ucwords(strtolower(substr($row["product_name"],0,25)))).".."; 
												 }else{
												 echo stripslashes(ucwords(strtolower(substr($row["product_name"],0,25)))); 
												 }
												 ?>
											</a>
										</h5>
										
									<div class="product_price">
										<p>
											<?php if($discountprice!=0) { ?>
											<?php echo  $currency_attributes[0] ?>
											<?php echo $discountprice;?>
											(<strike><?php echo  $currency_attributes[0] ?> <?php echo $display_product_price;?>
											</strike>)
											<?php }  else { ?>
											<?php echo  $currency_attributes[0] ?>
											<?php echo $display_product_price;?>
											<?php } ?>
										</p>
									</div>
									
									</div>
									<div class="clear"></div>
								</div>
								<?php
								if($count_row ==$cells) {
                                                $count_row = 1;
                                            }
                                            else {
                                                $count_row++;
                                            }
                                        }
                                    }
                                    else {
                                        ?>
								<?php echo NO_RESULT_TEXT;?>
								<?php
                                    }
                                    ?>
								<div class="clear"></div>
							</div>
				<?php if($totalrows>$limit) {?>
				<div class="pagination">
					<?php echo rightpaging();?>
				</div>
				<?php  } ?>
				<?php
                }
                ?>
			</div>
			<!--items display area end -->
	</form>
	<!--center content area end-->
	</div>
	</div>
</div>		
<!--mainbody area end -->
<div class="clear"></div>
<?php
include "includes/".$active_template[2];	/* Bottom File Name */
?>
<script type="text/javascript">
    $(document).ready(function(){
        $('.prod_green').click(function(){
         /*var pid=$(this).attr('id');            
         window.location = "<?php echo SITE_URL ?>/productdetails.php?productid="+pid;*/
         var OptimizedUrl=$(this).attr('data');          
         window.location = OptimizedUrl;
        });
    });
</script>