<?php 
defined( '_JEXEC' ) or die;
//JHtml::_('behavior.modal');
if (!class_exists( 'shopFunctionsF' )) require(JPATH_SITE.'/components/com_virtuemart/helpers/shopfunctionsf.php');

$user =& JFactory::getUser();
$mainframe = Jfactory::getApplication();
$virtuemart_currency_id = $mainframe->getUserStateFromRequest( "virtuemart_currency_id", 'virtuemart_currency_id',JRequest::getInt('virtuemart_currency_id',0) );
error_reporting('E_ALL');
echo vmJsApi::writeJS();
if (!$user->guest) {
					//var_dump ($_SESSION['id']);

				if (isset($_SESSION['id'])) {
					$dbIds = $_SESSION['id'];
					$db =& JFactory::getDBO();
					$q ="SELECT virtuemart_product_id FROM #__wishlists WHERE userid =".$user->id;
					$db->setQuery($q);
					$allproducts = $db->loadAssocList();
					foreach($allproducts as $productbd){
						$allprod['ids'][] = $productbd['virtuemart_product_id'];
					}
					//var_dump ($allproducts);
					$sessionWP = isset($allprod['ids']) ? $allprod['ids'] : array();
					for($r=0; $r<count($dbIds); $r++) {
						if(!in_array($dbIds[$r],$allprod['ids'])) {
					   $q = "";
						$q = "INSERT INTO `#__wishlists`
								(virtuemart_product_id,userid )
								VALUES
								('".$dbIds[$r]."','".$user->id."') ";
								//var_dump ($dbIds[$r]);
						$db->setQuery($q);
						//$db->queryBatch();
						$db->query();
					   }
				   }
				//unset($_SESSION['id']);
			   }
		   }

$document = JFactory::getDocument();
$product_model = VmModel::getModel('product');
	if (!$user->guest) {
	 	   $db =& JFactory::getDBO();
		   $q ="SELECT virtuemart_product_id FROM #__wishlists WHERE userid =".$user->id;
		   $db->setQuery($q);
		   $allproducts = $db->loadAssocList();
			foreach($allproducts as $productbd){
				$allprod['id'][] = $productbd['virtuemart_product_id'];
			}
				$products=$allprod['id'];
	   }else {
		   		$products=$_SESSION['id'];
		   }
  $prods = $product_model->getProducts($products);
$product_model->addImages($prods,1);
if($products){
	$currency = CurrencyDisplay::getInstance();
}
//var_dump ($prods);

?>
<div class="wishlist_box">
<div class="wishlist_info">
<h3 class="module-title">
	<?php echo JText::_('COM_WISHLIST_PRODUCT') ?>
</h3>
</div>
<?php // Back To Category Button
	if ($product->virtuemart_category_id) {
		$catURL =  JRoute::_('index.php?option=com_virtuemart&view=category&virtuemart_category_id='.$product->virtuemart_category_id);
		$categoryName = $product->category_name ;
	} else {
		$catURL =  JRoute::_('index.php?option=com_virtuemart&view=virtuemart');
		$categoryName = jText::_('COM_VIRTUEMART_SHOP_HOME');
	}
	?>
	
	<div class="back-to-category" >
    	<a href="<?php echo $catURL ?>" class="button_back button" title="<?php echo $categoryName ?>"><?php echo JText::sprintf('COM_VIRTUEMART_CATEGORY_BACK_TO',$categoryName) ?><span></span></a>
	</div>
    <div class="clear"></div>
    	<?php
	if (!empty($prods)) { ?>

  <?php  
    	echo '<div class="category-wishlist"><table class="sectiontableheader zebra">';
	echo '<tr clas="bg">';
	echo '<th>';
		//echo JHtml::_('grid.sort', 'NAME', 'name', $listDirn, $listOrder);
	echo JText::_('COM_VM2WISHLISTS_PRODUCT_IMAGES');
	echo '</th>';
	echo '<th>';
	echo JText::_('COM_VM2WISHLISTS_NAMECAT');
	echo '</th>';
	echo '<th>';
	echo JText::_('COM_VM2WISHLISTS_PRICE');
	echo '</th>';
	echo '<th>';
	echo JText::_('COM_VM2WISHLISTS_ACTION');
	echo '</th>';
	echo '</tr>';
	
	foreach ($prods as $product) {
		$i++;
		$list_item_url = JRoute::_('index.php?option=com_virtuemart&view=productdetails&virtuemart_product_id='.$product->virtuemart_product_id.'&virtuemart_category_id='.$product->virtuemart_category_id);

		if($i>2) $i = 1;
		echo '<tr id="wishlists_prod_'.$product->virtuemart_product_id.'" class="sectiontableentry'.$i.'" >';
		echo '<td>';
		?>
		<div class="browseImage ">
			<?php if (($product->prices['override'] == -1 || $product->prices['override'] == 1) && ($product->prices['product_price_publish_down'] > 0)){ ?>
            <div class="discount limited"><?php echo JText::_('DR_LIMITED_OFFER');?></div>
            <?php } elseif($discont >0 && $product->product_sales < 20 ) { ?>
            <div class="discount"><?php echo JText::_('DR_SALE');?></div>
            <?php } elseif ($product->product_sales > 20) {?>
            <div class="hit"><?php echo JText::_('DR_HOT');?></div>
            <?php } ?>
            	<?php
					if (!empty($product->images[0]) )
							$image = $product->images[0]->displayMediaThumb('class="browseProductImage featuredProductImage" id="Img_to_Js_'.$product->virtuemart_product_id.'"  border="0"',false) ;
						else $image = '';
					?>
					<a href="<?php echo 'index.php?option=com_virtuemart&view=productdetails&virtuemart_product_id='.$product->virtuemart_product_id.'&virtuemart_category_id='.$product->virtuemart_category_id; ?>"><?php echo $image ?></a>
            </div>
        <?php
		echo '</td>';
		echo '<td>';
		echo '<div class="product_name" >';
		echo '<a href="'.$list_item_url.'"  title="'.ucfirst($product->product_name).'::'.strip_tags($product->product_s_desc).'" class="hasTips">'.ucfirst($product->product_name).'</a>';
		echo '</div>';
			
		echo '<div style="clear:both;"></div>';
		echo '<div class="product_cat" >';
		//echo '<img src="'.$juri.'components/com_vm2wishlists/assets/img/category.png" alt="'.JText::_('COM_VM2WISHLISTS_CATEGORY').'" title="'.JText::_('COM_VM2WISHLISTS_CATEGORY').'" width="13" height="13"  class="hasTip" /> ';
		echo '<a href="'.JRoute::_('index.php?option=com_virtuemart&view=category&virtuemart_category_id='.$product->virtuemart_category_id).'">'.$product->category_name.'</a>';
		echo '</div>';
		echo '<div style="clear:both;"></div>';
		$ratingModel = VmModel::getModel('ratings');
		 $showRating = $ratingModel->showRating($product->virtuemart_product_id);
			 if ($showRating=='true'){
			$rating = $ratingModel->getRatingByProduct($product->virtuemart_product_id);
			if( !empty($rating)) {
				$r = $rating->rating;
			} else {
				$r = 0;
			}
			$maxrating = VmConfig::get('vm_maximum_rating_scale',5);
							$ratingwidth = ( $r * 100 ) / $maxrating;//I don't use round as percetntage with works perfect, as for me
				?>
			  <?php  if( !empty($rating)) {  ?>                        
					<span class="vote">
						<span title="" class="vmicon ratingbox" style="display:inline-block;">
							<span class="stars-orange" style="width:<?php echo $ratingwidth;?>%">
							</span>
						</span>
						<span class="rating-title"><?php echo JText::_('COM_VIRTUEMART_RATING').' '.round($rating->rating, 2) . '/'. $maxrating; ?></span>
					</span>
			   <?php } else { ?>
				  <span class="vote">
						<span title="" class="vmicon ratingbox" style="display:inline-block;">
							<span class="stars-orange" style="width:<?php echo $ratingwidth;?>%">
							</span>
						</span>
						<span class="rating-title"><?php echo JText::_('COM_VIRTUEMART_RATING').' '.JText::_('COM_VIRTUEMART_UNRATED') ?></span>
				   </span>
				<?php } }

		echo '<div style="clear:both;"></div>';
		echo '</td>';
		echo '<td>';
					$discont = $product->prices['discountAmount'];
					$discont = abs($discont);
					?>
                    <?php if ((!empty($product->prices['salesPrice'])) && !$product->images[0]->file_is_downloadable) { ?>
                    <div class="Price <?php if ($discont>0) { echo 'disc';}?> " id="productPrice<?php echo $product->virtuemart_product_id ?>">
						 <?php if ($discont>0)
                            echo '<span class="WithoutTax">'.$currency->createPriceDiv('basePriceWithTax', '', $product->prices,true).'</span>';
                        ?>
                        <?php if ($product->prices['salesPrice']>0)
                            echo '<span class="sales">' .$currency->createPriceDiv('salesPrice', '', $product->prices,true).'</span>';
                        ?>
                        <?php if ($discont>0)
                            echo '<span class="discount">' .$currency->createPriceDiv('discountAmount', '', $product->prices,true).'</span>';
                        ?>
                        
        			 </div>
                    
			<?php } else {
									if ($product->prices['salesPrice']<=0 and VmConfig::get ('askprice', 1) ) { ?>
									<div class="call-a-question">
                                     	<a class="call modal"  rel="{handler: 'iframe', size: {x: 460, y: 550}}" href="<?php echo JRoute::_('index.php?option=com_virtuemart&view=productdetails&task=askquestion&virtuemart_product_id='.$product->virtuemart_product_id.'&virtuemart_category_id='.$product->virtuemart_category_id.'&tmpl=component'); ?>" ><?php echo JText::_('COM_VIRTUEMART_PRODUCT_ASKPRICE') ?></a>
                                    </div>
									<?php } } 
			
		echo '</td>';
		echo '<td>';
		  		 $show_price = $currency->createPriceDiv('salesPrice', '', $product->prices,true);
				?>
				 <?php if (!empty($show_price)){

                     if ((!VmConfig::get('use_as_catalog', 0) and !empty($product->prices['salesPrice'])) && !$product->images[0]->file_is_downloadable) { 
					 if (isset($product->step_order_level))
							$step=$product->step_order_level;
						else
							$step=1;
						if($step==0)
							$step=1;
						$alert=JText::sprintf ('COM_VIRTUEMART_WRONG_AMOUNT_ADDED', $step);
					 ?>
									<div class="addtocart-area2">
										<?php $stockhandle = VmConfig::get ('stockhandle', 'none');
			if (
				($stockhandle == 'disableit' or $stockhandle == 'disableadd') and (($product->product_in_stock - $product->product_ordered) < 1) || 
			(
			 ($product->product_in_stock - $product->product_ordered) < $product->min_order_level ))  { ?>
											<a class="addtocart-button" title="<?php echo JText::_('COM_VIRTUEMART_CART_NOTIFY') ?>" href="<?php echo JRoute::_('index.php?option=com_virtuemart&view=productdetails&layout=notify&virtuemart_product_id='.$product->virtuemart_product_id); ?>"><?php echo JText::_('COM_VIRTUEMART_CART_NOTIFY') ?><span></span></a>
										<?php } else { ?>
										<form method="post" class="product" action="index.php" id="addtocartproduct<?php echo $product->virtuemart_product_id ?>">
                                          <input name="quantity" type="hidden" value="<?php echo $step ?>" />
										<div class="addtocart-bar2">
                                        <script type="text/javascript">
												function check(obj) {
												// use the modulus operator '%' to see if there is a remainder
												remainder=obj.value % <?php echo $step?>;
												quantity=obj.value;
												if (remainder  != 0) {
													alert('<?php echo $alert?>!');
													obj.value = quantity-remainder;
													return false;
													}
												return true;
												}
										</script> 
											<?php // Display the quantity box 
											 if (!empty($product->customfields)) {
													foreach ($product->customfields as $k => $custom) {
														if (!empty($custom->layout_pos)) {
															$product->customfieldsSorted[$custom->layout_pos][] = $custom;
															unset($product->customfields[$k]);
														}
													}
													$product->customfieldsSorted['normal'] = $product->customfields;
													unset($product->customfields);
												}
											$position = 'addtocart';
											if (!empty($product->customfieldsSorted[$position])) {  ?>
											<span class="attributes"><b>*</b> Product has attributes</span>
                                            <div class="addtocart_button2">
											<?php echo JHTML::link($product->link, JText::_('DR_VIRTUEMART_SELECT_OPTION').'<span>&nbsp;</span>', array('title' =>JText::_('DR_VIRTUEMART_SELECT_OPTION'),'class' => 'addtocart-button')); ?>
                                      	  </div>
										
										<?php } else { ?>
										<span class="quantity-box">
											<input type="text" class="quantity-input js-recalculate"  name="quantity[]" onblur="check(this);" value="<?php if (isset($product->step_order_level) && (int)$product->step_order_level > 0) {
											echo $product->step_order_level;
										} else if(!empty($product->min_order_level)){
											echo $product->min_order_level;
										}else {
											echo '1';
										} ?>"/>
																			
                                            <span class="quantity-controls">
											<input type="button" class="quantity-controls quantity-plus" />
											<input type="button" class="quantity-controls quantity-minus" />
										</span>
										</span>
										
										<?php // Add the button
											$button_lbl = JText::_('COM_VIRTUEMART_CART_ADD_TO');
											$button_cls = 'addtocart-button cart-click'; //$button_cls = 'addtocart_button';
										?>
											<?php // Display the add to cart button ?>
											<div class="clear"></div>
											<span class="addtocart_button2">
												<button type="submit" value="<?php echo $button_lbl ?>" title="<?php echo JText::_('COM_VIRTUEMART_CART_ADD_TO');?>" class="<?php echo $button_cls ?>"><?php echo $button_lbl ?><span>&nbsp;</span></button>
											</span>
                                            
										<input type="hidden" class="pname" value="<?php echo $product->product_name ?>"/>
										<input type="hidden" name="option" value="com_virtuemart" />
										<input type="hidden" name="view" value="cart" />
										<noscript><input type="hidden" name="task" value="add" /></noscript>
										<input type="hidden" class="item_id" name="virtuemart_product_id[]" value="<?php echo $product->virtuemart_product_id ?>" />
										<input type="hidden" name="virtuemart_category_id[]" value="<?php echo $product->virtuemart_category_id ?>" />	
										<?php }?>
									</div>
									</form>
									<?php } ?>
                                    </div>
							<?php } } ?>
                  <div class="remwishlists"><a class="wishlist_del" title="remove"  onclick="removeWishlists('<?php echo $product->virtuemart_product_id;?>');"><?php echo JText::_('REMOVE'); ?></a></div>
			<?php 
			echo '</td>';
		
		echo '</tr>';
	}
	echo '</table></div>';
	echo '<h3 class="module-title wishlists no-products" style="display:none;">'.JText::_('COM_VIRTUEMART_ITEMS_NO_PRODUCTS_WHISHLIST').'</h3>';
	} else { echo '<h3 class="module-title no-products">'.JText::_('COM_VIRTUEMART_ITEMS_NO_PRODUCTS_WHISHLIST').'</h3>';}
?>
</div>

