<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | PHP version 4/5                                                      |
// +----------------------------------------------------------------------+
// | This source file is a part of iScripts Multicart                     |
// +----------------------------------------------------------------------+
// | Authors: Santhosh Thomas Alexander<santhosh.thomas@armiasystems.com> |
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems, Inc and iScripts.com @ 2005                |
// | All rights reserved                                                  |
// +----------------------------------------------------------------------+
// | This script may not be distributed, sold, given away for free to     |
// | third party, or used as a part of any internet services such as      |
// | webdesign etc.                                                       |
// +----------------------------------------------------------------------+
?>
<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>
<?php
if(isset($_GET["txtSearch"]) and $_GET["txtSearch"]!="") {
    $txtSearch = $_GET["txtSearch"];
    $cmbSearchType = $_GET["cmbSearchType"];
}else if(isset($_POST["txtSearch"]) and $_POST["txtSearch"]!="") {
    $txtSearch = $_POST["txtSearch"];
    $cmbSearchType = $_POST["cmbSearchType"];
}

$txtCategoryName = trim($_POST["txtCategoryName"]);
$txtProductName = $_POST["txtProductName"];
$txtDescription = $_POST["txtDescription"];
$txtPrice = $_POST["txtPrice"];
$ddlArtist =$_POST["ddlArtist"];
$productlist = $_POST["chkproducts"];


$artistlist = makeArtistList();

$productListingFee = getSettingsValue('product_listing_fee');

$whereCondition =   '';

 $currency_attributes = displayCurrencyType();
//***************************Product Listing  Modifications for Scalability **********************
if(CheckGiftCertificateCategory($_REQUEST['catid'])=='Y') {

    $sql    =   "SELECT p.*, (p.product_price + p.default_additional_price) AS product_price FROM " . $tableprefix . "products p INNER JOIN " . $tableprefix . "artists a ON p.product_artist_id = a.artist_id
                 INNER JOIN ".$tableprefix."giftcoupon_master gm oN gm.ngift_product_id=p.product_id
                 LEFT JOIN ".$tableprefix."record_ratings r ON p.product_id = r.nrseller_id  where p.vapproved = 'Y' AND a.plan_expired ='N' ";

    // Getting the total rows count without limit
    $sql_total_rows  = "SELECT count(p.product_id) as cnt FROM " . $tableprefix . "products p INNER JOIN " . $tableprefix . "artists a ON p.product_artist_id = a.artist_id
                        INNER JOIN ".$tableprefix."giftcoupon_master gm oN gm.ngift_product_id=p.product_id
                        LEFT JOIN ".$tableprefix."record_ratings r ON p.product_id = r.nrseller_id  where p.vapproved = 'Y' AND a.plan_expired ='N'  ";

    $whereCondition.=" AND p.deleted='N' ";  // check deleted status
    $whereCondition.=" AND p.publish_status='Y' ";  // check published status
    $whereCondition.=" AND p.seller_vacation_mode='N' ";  // check seller vacation ode settings
    $whereCondition.=" AND p.vSellerStatus='Y' ";  // check seller approved or plan expiry status
}

else {
         $whereCondition = "";
        $sql    =   "SELECT p.*, (p.product_price + p.default_additional_price) AS product_price FROM " . $tableprefix . "products p INNER JOIN " . $tableprefix . "artists a ON p.product_artist_id = a.artist_id
                    LEFT JOIN ".$tableprefix."record_ratings r ON p.product_id = r.nrseller_id
                    where p.vapproved = 'Y' AND a.plan_expired ='N' ";
       
        // Getting the total rows count without limit
        $sql_total_rows  = "SELECT count(p.product_id) as cnt FROM " . $tableprefix . "products p INNER JOIN " . $tableprefix . "artists a ON p.product_artist_id = a.artist_id
                    LEFT JOIN ".$tableprefix."record_ratings r ON p.product_id = r.nrseller_id
                    where p.vapproved = 'Y' AND a.plan_expired ='N' ";
        
        $whereCondition.=" AND p.deleted='N' ";  // check deleted status
        $whereCondition.=" AND p.publish_status='Y' ";  // check published status
        $whereCondition.=" AND p.seller_vacation_mode='N' ";  // check seller vacation ode settings
        $whereCondition.=" AND p.vSellerStatus='Y' ";  // check seller approved or plan expiry status
        if ($productListingFee > 0) {
                $whereCondition .= " AND p.payment_status='COMPLETED' ";  // Check seller payment completed
            }
    }
$sql    =   $sql .$whereCondition ;
$sql_total_rows = $sql_total_rows.$whereCondition;

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


$qrystring= " ";

if($txtSearch != "" || $catid!='') { // check for searching

    $qrystring.=" AND ";

    if(!empty($catid)) { // check category Id is empty or not

        $qrystring.=" p.product_category =".GetSQLValueString($catid,"text")." AND ";

    } //

    if($txtSearch!='') {
        $qrystring .= ' ( p.product_name like "%' . addslashes($txtSearch) . '%" || p.product_description like "%' . addslashes($txtSearch) . '%") AND  ';
    }

} // end if search 

$query1=rtrim($qrystring, " AND");	

if(isset($_REQUEST['sel_order_by']))
{
	//die("Here I'm");
	if($_REQUEST['sel_order_by']=="rating desc"){
		$order = " GROUP BY p.product_id ORDER BY AVG(r.nrating_id) DESC ";
	}	
	else if($_REQUEST['sel_order_by']=="vendor desc"){
		$order = " GROUP BY p.product_id ORDER BY p.seller_name DESC ";
	}
	else if($_REQUEST['sel_order_by']=="vendor asc"){
		$order = " GROUP BY p.product_id ORDER BY  p.seller_name ASC";
	}
	else if($_REQUEST['sel_order_by']=="price desc"){
		$order = " GROUP BY p.product_id ORDER BY product_price DESC ";
	}  
	else if($_REQUEST['sel_order_by']=="price asc"){
		$order = " GROUP BY p.product_id ORDER BY product_price ASC";
	}
	else {
		$order = "GROUP BY p.product_id ";
	}
}
else {
	//$order = "GROUP BY p.product_id ";
}

$query=$sql.$query1.$order;

$query_total_rows=$sql_total_rows.$query1.$order;

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

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

//$totalrows = mysql_num_rows($result);
$totalrows = mysql_result(mysql_query($query_total_rows),0,'cnt');



$limit=12;
//$limit=3;

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

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

$prodimagedir = "products/";

if($totalrows > 0 ) {
    $i=1;
    $cells =4;
    $count_row = 1;

    while($row = mysql_fetch_array($result)) {
       // echo "<pre>";print_r($row);echo "</pre>";
        // Image Selection Modification // Done By Asha
            $imageurl='';
            $product_image = "";
            if($row["default_image_small"] !="") {
                $product_image = $row["default_image_small"];

            }  // end if product image null check
  
       if($product_image=="") {
                $imageurl = $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' >";




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

     

        if(strlen($row["product_name"])>30) {
            $prd_name = stripslashes(substr($row["product_name"],0,30));
        }
        else {
            $prd_name = stripslashes($row["product_name"]);

        }

        $price=$row['product_price'];

        $discountstr="";

       
        $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>
	<div class="prod_green" id="<?php echo $row["product_id"];?>" data="<?php echo $SEOFriendlyLink; ?>" >	
		<div class="prodover_blk">
			<div class="prodover_blk_row">
                                <?php if ($enable_seller_friendly == "Y") {
                                    $sellerLink =  SITE_URL . "/store/" . $row['seller_name'];
                                } else {
                                    $sellerLink = SITE_URL."/showportfolio.php?artistid=" . $row['product_artist_id'];
                                } ?>
				<div class="artist_name"><a href="<?php echo $sellerLink; ?>" title="<?php echo $row['seller_name'];?>"><?php echo $row['seller_name'];?></a></div>
				<div class="clear"></div>  
			</div>
			<div class="clear"></div>
			<div class="prodover_blk_row">
				<?php $productRating = ProductRatingStar($row["product_id"]); ?>
				<div class="rating_<?php echo $productRating; ?>" id="rating_<?php echo $productRating; ?>"></div>				                 
				<div class="clear"></div>  
			</div>
			<div class="clear"></div>
			<div class="prodover_blk_row">
				<div width="64%" align="left" class="txt_align" valign="middle"> <?php $productRating = ProductRatingStar($row["product_id"]); ?></div>
				<div class="clear"></div>  
			</div> 
			<div class="clear"></div>  
					<?php
					if($productinstock) {
						?>
                        <?php  // Hide Shop now Button for Subscription Items
                            if(!$subscriptionFlag) { ?>
			<div class="prodover_blk_row">
				<div class="adtocart_tbn_blk">
					<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"]?>"><?php echo ADD_TO_CART_TEXT; ?></a>
					<div class="clear"></div>  
				</div>
				<div class="clear"></div>  
			</div>
                        <?php } ?>
			<div class="clear"></div>
						<?php
					}
					else {
						?>
			<div class="prodover_blk_row">
				<div class="adtocart_tbn_blk"><span class="out_stock">Out of Stock</span></div>
				<div class="clear"></div>  
			</div>
			<div class="clear"></div>
						<?php
		
					} 
					?>
		</div>
	</div>
    <h5><a href="<?php echo $SEOFriendlyLink;?>" title="<?php echo $prd_name; ?>">
                        <?php 
                        if(strlen($prd_name)>20) {
                            echo substr($prd_name,0,20)."...";
                        } else {
                            if(LANGUAGE=='english')
                                echo $prd_name;
                            else
                                echo $prd_name;
                        }
                        ?>
            </a></h5>
    <div class="product_price"><p> <?php if($discountprice!=0) { ?> <?php echo  $currency_attributes[0] ?> <?php echo $discountprice;?> <span>(<strike><?php echo  $currency_attributes[0] ?> <?php echo $display_product_price;?> </strike>)</span> <?php }  else { ?> <?php echo  $currency_attributes[0] ?> <?php echo $display_product_price;?> <?php } ?> </p></div>
    <div class="clear"></div>
</div>
</div>

        <?php
        if($count_row ==$cells) {

            $count_row = 1;
        }
        else {
            $count_row++;
        }

    }
    ?>
    <?php
} 
else {
    ?>
<div class="noproducts" ><?php echo NO_PRODUCT_FOUND_TEXT;?></div>
    <?php
}  // end else
?>
<input type="hidden" value="<?php echo $featured;?>" name="featured">
<div class="clear"></div>
</div>
<?php if($totalrows>$limit) {
    ?>
<div  class="pagination"> <?php echo rightpaging();?></div>
    <?php

}
?>