<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/
//
//$Id: WidgetModel, v 1.0 2014/06/05 16:17:29
//All functions 
//
class WidgetModel extends Model {
    /* Function to list the complete widgets */
    public function listWidget($params = array()) {
        extract($params);
        $selectFields = '';
        if (isset($limitTo) && $limitTo != '')
            $selectFields .= " SQL_CALC_FOUND_ROWS ";
        $sql = " 
				SELECT 
					" . $selectFields . "
					*,brandDet.brandName
				FROM 
						" . DB_PREFIX . "widgets AS wid
				INNER JOIN 
						" . DB_PREFIX . "widget_details AS widDet
							ON	(
								wid.widgetID = widDet.widgetID
								AND
								widDet.languageID = '" . $languageIDs['Content'] . "'
							)	
                                LEFT JOIN 
						" . DB_PREFIX . "brands AS brand
							ON	(
								brand.brandID = wid.brandID
							)                     
                                        LEFT JOIN 
						" . DB_PREFIX . "brand_details AS brandDet
							ON	(
								brandDet.brandID = brand.brandID
								AND
								brandDet.languageID = '" . $languageIDs['Content'] . "'
							)   
				WHERE
					1
				";
        if (isset($widgetStartDate) && $widgetStartDate != '') {
            $sql .= " 	
				AND
				DATE_FORMAT(widgetStartDate, '%Y-%m-%d') >= '" . $widgetStartDate . "' ";
        }
        if (isset($widgetEndDate) && $widgetEndDate != '') {
            $sql .= " 	
				AND 
				DATE_FORMAT(widgetEndDate, '%Y-%m-%d') <= '" . $widgetEndDate . "' ";
        }
        if (isset($widgetDisplayedOn) && $widgetDisplayedOn != '') {
            $sql .= "
				AND
				widgetDisplayedOn =  '" . $widgetDisplayedOn . "'
				";
        }
        /*if (isset($widgetType) && $widgetType != '') {
            $sql .= "
				AND
				widgetType =  '" . $widgetType . "'
				";
        }*/
        if (isset($widgetPlatform) && $widgetPlatform != '') {
            $sql .= "
				AND
				widgetPlatform =  '" . $widgetPlatform . "'				";
        }
        if (isset($brandID) && $brandID != '') {
            $sql .= "
				AND
				wid.brandID =  '" . $brandID . "'				";
        }
        if (isset($showTitle) && $showTitle != '') {
            $sql .= "
				AND
				showTitle like '%" . $showTitle . "%'
				";
        }
        if (isset($status) && $status != '') {
            $sql .= "
				AND
				wid.status ='" . $status . "'
				";
        } else {
            $sql .= "
				AND
				wid.status !='D'
				";
        }
        if (isset($widgetTitle) && $widgetTitle != '') {
            $sql .= "
				AND
				widgetTitle like '%" . $widgetTitle . "%'
				";
        }
        if (isset($widgetDescription) && $widgetDescription != '') {
            $sql .= "
				AND
				widgetDescription like '%" . $widgetDescription . "%'
				";
        }
        if (isset($currentDate) && $currentDate != '') {
            $sql .= "
				AND
					(
						'" . $currentDate . "' 
						BETWEEN 
						widgetStartDate AND widgetEndDate
					OR
						widgetStartDate='0000-00-00' 
						AND 
						widgetEndDate='0000-00-00'
					OR
						'" . $currentDate . "'  > widgetStartDate 
						AND
						widgetEndDate='0000-00-00'
					OR
						widgetStartDate ='0000-00-00'
						AND
						widgetEndDate > '" . $currentDate . "'
					)
						
			";
        }
        if (isset($widgetIDs) && !empty($widgetIDs)) {
            $sql .= "
				AND
				wid.widgetID IN ('" . implode("','", $widgetIDs) . "')
					
			";
        }
        if (isset($categoryWidgetIDs) && !empty($categoryWidgetIDs)) {
            $sql .= "
				AND
				wid.widgetID NOT IN ('" . implode("','", $categoryWidgetIDs) . "')
					
			";
        }
		if(isset($hasTabs) && $hasTabs){
			$sql.="
				AND
				(
					wid.widgetID IN (
						SELECT 
							widgetID
						FROM	
							" . DB_PREFIX . "widget_tab AS widTab
						WHERE
							status!='D'
					)
					
				)
			";
			
		}
                /*OR 
					widgetType='static'*/
        if (isset($orderby) && $orderby != '' && $sortby) {
            $sql .= "
				ORDER BY
					" . substr($sortby, 5) . " " . $orderby . "
				";
        } else {
            $sql .= "
				ORDER BY ";
            if (isset($widgetIDs) && !empty($widgetIDs)) {
                $sql .= "
				FIELD(wid.widgetID,'" . implode("','", $widgetIDs) . "'),";
            }
            $sql .= "
					sortOrder ASC";
        }
        if (isset($limitTo) && $limitTo != '') {
            $sql .= " 
				LIMIT  
					" . $limitFrom . ",
					" . $limitTo . "
				";
        }
        
        return $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);
    }
	public function getWidgetTabFrontend($params = array()) {
        extract($params);
        $sql = "
			SELECT SQL_CACHE
				* 
			FROM
					" . DB_PREFIX . "widget_tab AS widTab
				INNER JOIN 
					" . DB_PREFIX . "widget_tab_details AS widTabDet
						ON	(
							widTab.widgetTabID = widTabDet.widgetTabID
							AND
							widTabDet.languageID = '" . $languageIDs['Content'] . "'
						)
			WHERE
				widTab.widgetTabID = '" . $widgetTabID . "'
			
		";
        if (isset($status) && $status != '') {
            $sql .= "
				AND
				status='" . $status . "'
			";
        } else {
            $sql .= "
				AND
				status!='D'
			";
        }
        $sql .= " 
				LIMIT  
					1
				";
       
        return $this->ObjDatabase->readValueSlave($sql, MYSQLI_ASSOC);
    }
    /* function to get the single widget */
    public function getWidget($params = array()) {
        extract($params);
        $selectFields = isset($selectFields) ? $selectFields : '';
        $sql          = " 
			SELECT 
				" . $selectFields . "
				*
			FROM 
					" . DB_PREFIX . "widgets AS wid
				INNER JOIN 
					" . DB_PREFIX . "widget_details AS widDet
						ON	(
							wid.widgetID = widDet.widgetID
							AND
							widDet.languageID = '" . $languageIDs['Content'] . "'
						)				
			WHERE
				wid.widgetID = '" . $widgetID . "'
			";
        if (isset($status) && $status != '') {
            $sql .= "
				AND
				status='" . $status . "'
			";
        } else {
            $sql .= "
				AND
				status!='D'
			";
        }
        $sql .= " 
				LIMIT  
					1
				";
        return $this->ObjDatabase->readValue($sql, MYSQLI_ASSOC);
    }
    /* Function to get the complete widget tabs */
    public function listWidgetTab($params = array()) {
        extract($params);
        $sql = "
			SELECT SQL_CACHE
				* 
			FROM
					" . DB_PREFIX . "widget_tab AS widTab
				INNER JOIN 
					" . DB_PREFIX . "widget_tab_details AS widTabDet
						ON	(
							widTab.widgetTabID = widTabDet.widgetTabID
							AND
							widTabDet.languageID = '" . $languageIDs['Content'] . "'
						)
			WHERE
				widTab.widgetID = '" . $widgetID . "'
			
		";
        if (isset($status) && $status != '') {
            $sql .= "
				AND
				status='" . $status . "'
			";
        } else {
            $sql .= "
				AND
				status!='D'
			";
        }
        $sql .= " ORDER BY 
				widTab.sortOrder ASC";
        return $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);
    }
    /* Function to get the single widget tab */
    public function getWidgetTab($params = array()) {
        extract($params);
        $sql = "
			SELECT 
				* 
			FROM
					" . DB_PREFIX . "widget_tab AS widTab
				INNER JOIN 
					" . DB_PREFIX . "widget_tab_details AS widTabDet
						ON	(
							widTab.widgetTabID = widTabDet.widgetTabID
							AND
							widTabDet.languageID = '" . $languageIDs['Content'] . "'
						)
			WHERE
				widTab.widgetTabID = '" . $widgetTabID . "'
			
		";
        if (isset($status) && $status != '') {
            $sql .= "
				AND
				status='" . $status . "'
			";
        } else {
            $sql .= "
				AND
				status!='D'
			";
        }
        $sql .= " 
				LIMIT  
					1
				";
        return $this->ObjDatabase->readValue($sql, MYSQLI_ASSOC);
    }
    public function listAssignedWidgets($params = array()) {
        extract($params);
        $sql = "
			SELECT
				widgetID
			FROM
				" . DB_PREFIX . "widget_to_category
			WHERE
				productCategoryID = '" . $productCategoryID . "'
			ORDER BY
				sortOrder
		";
        return $this->ObjDatabase->getFields($sql);
    }
    /* Function to get the tab items other tha custom rules */
    public function listWidgetTabItems($params) {
        $args = $params;
        extract($args);
        switch ($listingType) {
            case 'brands':
                $sql = "
					SELECT SQL_CACHE
						brand.brandID AS itemID,
						brand.brandKey AS itemKey,
						CASE 
							WHEN brand.brandIcon!='' 
								THEN 
								CONCAT('brand/small/',brand.brandIcon) 
							ELSE 
								'' 
						END AS itemIcon,
						brandDet.brandName AS itemName,
						'' AS itemPrice,
						'' AS itemRegularPrice,
						'' AS itemDiscount,
						'' AS itemFeaturedStatus,
						'' AS itemOptionQuantitySum
					FROM
							" . DB_PREFIX . "widget_tab_items AS widTabIte
						INNER JOIN
							" . DB_PREFIX . "brands AS brand
								ON	(
									widTabIte.itemID = brand.brandID
									AND
									brand.status='A'
								)
						INNER JOIN
							" . DB_PREFIX . "brand_details AS brandDet
								ON	(
									brand.brandID = brandDet.brandID
									AND
									brandDet.languageID = '" . $languageIDs['Content'] . "'
								)
					WHERE
						widTabIte.widgetTabID = '" . $widgetTabID . "'
					ORDER BY 
						widTabIte.sortOrder ASC	";
                if (isset($itemCount) && $itemCount > 0) {
                    $sql .= "
					LIMIT 
						" . $itemCount . "
					";
                }
                break;
            case 'categories':
                $sql = "
					SELECT SQL_CACHE
						productCat.productCategoryID AS itemID,
						productCat.productCategoryKey AS itemKey,
						CASE 
							WHEN productCat.productCategoryImage!='' 
								THEN 
								CONCAT('product-category/',productCat.productCategoryImage)  
							ELSE 
								'' 
						END AS itemIcon,
						productCatDet.productCategoryName AS itemName,
						'' AS itemPrice,
						'' AS itemRegularPrice,
						'' AS itemDiscount,
						'' AS itemFeaturedStatus,
						'' AS itemOptionQuantitySum
					FROM
							" . DB_PREFIX . "widget_tab_items AS widTabIte
						INNER JOIN
							" . DB_PREFIX . "product_categories AS productCat
								ON	(
									widTabIte.itemID = productCat.productCategoryID
									AND
									productCat.productCategoryStatus='Active'
								)
						INNER JOIN
							" . DB_PREFIX . "product_category_details AS productCatDet
								ON	(
									productCat.productCategoryID = productCatDet.productCategoryID
									AND
									productCatDet.languageID = '" . $languageIDs['Content'] . "'
								)
					WHERE
						widTabIte.widgetTabID = '" . $widgetTabID . "'
					ORDER BY 
						widTabIte.sortOrder ASC";
                if (isset($itemCount) && $itemCount > 0) {
                    $sql .= "
					LIMIT 
						" . $itemCount . "
					";
                }
                break;
            case 'custom':
            case 'you_may_like':
                return $this->listWidgetProducts($params);
                break;
        }
        if(isset($sql) && $sql!=''){
                return $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);
        }else{
                return array();
        }    
    }
    public function listWidgetProducts($params = array()) {
        extract($params);
        $userGroupID  = isset($userGroupID) ? (int) $userGroupID : 0;
        $currDateTime = date('Y-m-d');
        $sql          = "
			SELECT SQL_CACHE
				product.productID AS itemID,
                                        product.sellAsBatch,
                                        product.batchType,
                                        product.qtyPerBatch,
				productOpt.optionSKU AS itemKey,
				CONCAT('catalog/vehicles/thumb/',veh_product.vehicleImage) AS itemIcon,
				productDet.productTitle AS itemName,
				LEAST(
					COALESCE(
						varOffPri.offerPrice,
						productOptBus.productOptionProductPrice
					),
					COALESCE(
						varGroPri.specialPrice,
						productOptBus.productOptionProductPrice
					) 
				)
				AS itemPrice,
				productOptBus.productOptionRegularPrice AS itemRegularPrice,
                                productOptBus.businessID,
				ROUND(
					(
						(
							(
							productOptBus.productOptionRegularPrice-
								LEAST(
									COALESCE(
										varOffPri.offerPrice,
										productOptBus.productOptionProductPrice
									),
									COALESCE(
										varGroPri.specialPrice,
										productOptBus.productOptionProductPrice
									) 
								)
							)*100
						)/productOptBus.productOptionRegularPrice
					),0
				) AS itemDiscount,
				product.featuredStatus AS itemFeaturedStatus,
				IF(product.InventoryTrackLevel ='No',
					1,
					IF(product.InventoryTrackLevel ='Product',
						(
							SELECT 
									SUM(productOptionQuantity)
								FROM 
									" . DB_PREFIX . "products_options_business
								WHERE 
									productOptionID=productOpt.productOptionID 
									AND 
									businessOptionDefault='Yes'
						),
						(
							SELECT 
									SUM(prodCombBus.businessCombQuantity)
								FROM 
									" . DB_PREFIX . "product_combination_business prodCombBus
                                                                INNER JOIN " . DB_PREFIX . "product_combination AS proCom1
                                                                        ON (proCom1.combinationID = prodCombBus.combinationID)
								WHERE 
									proCom1.productID=product.productID									
									AND 
									proCom1.status='A'
						)
					)
				)
				AS itemOptionQuantitySum ";
				if(isset($product_currency) && $product_currency != ''){
			$sql.="
				,productDefaultCurrency
			";
		}
			$sql		.=",product.productUrl,					                                                                          
                                            product.freeProductsCount,	
                                            product.productMinBuyLimit,
                                            productOpt.productOptionID,
                                            productOptBus.productOptionProductPrice,
                                            product.productDefaultCurrency, 
                                            productOptBus.businessID,
                                            product.InventoryTrackLevel from
                                             ";
        if (isset($widgetTabID) && $widgetTabID > 0) {
            $sql .= "
					" . DB_PREFIX . "widget_tab_items AS widTabIte
				INNER JOIN 
					" . DB_PREFIX . "products AS product 
						ON	(
							widTabIte.itemID = product.productID
							
						)";
        } else {
            $sql .= "
				" . DB_PREFIX . "products AS product 
			";
        }
        $sql .= "				
				INNER JOIN 
					" . DB_PREFIX . "product_details AS productDet 
						ON (
							product.productID = productDet.productID 
							AND 
							productDet.languageID = '" . $languageIDs['Content'] . "'
						)
				INNER JOIN 
					" . DB_PREFIX . "product_options	AS productOpt 
						ON (
							product.productID = productOpt.productID
							AND
							productOpt.productOptionStatus = 'Active' 
							AND 
							productOpt.productOptionDefault = 'Yes'
						) 
                                INNER JOIN 
					" . DB_PREFIX . "products_options_business	AS productOptBus 
						ON (
							productOptBus.productOptionID = productOpt.productOptionID
							AND
							productOptBus.busProductStatus = 'Active' 
							AND 
							productOptBus.businessOptionDefault = 'Yes'
						)
                                INNER JOIN 
					" . DB_PREFIX . "business 	AS bus 
						ON (
							productOptBus.businessID = bus.businessID 
							AND 
							bus.businessStatus = 'Active'
						)
				LEFT JOIN
					" . DB_PREFIX . "variant_offer_price AS varOffPri
						ON	(
							varOffPri.productOptionID = productOpt.productOptionID
							AND
							varOffPri.userGroupID='" . $userGroupID . "'
                                                        AND varOffPri.businessID = productOptBus.businessID
						)	
				LEFT JOIN
					" . DB_PREFIX . "variant_group_price AS varGroPri
						ON	(
							varGroPri.productOptionID = productOpt.productOptionID
							AND
							varGroPri.userGroupID='" . $userGroupID . "'
                                                        AND varGroPri.businessID = productOptBus.businessID
						)
				LEFT JOIN " . DB_PREFIX . "vehicle_images AS veh_product
					ON (veh_product.variantCode = SUBSTRING_INDEX(productOpt.optionSKU,'-',1) and veh_product.imageType='png')
			WHERE
				product.productStatus = 'Active' 
				AND (
					product.productStartTime <= '" . $currDateTime . "' 
					AND
					(
						product.productEndTime = '0000-00-00'
						OR
						product.productEndTime >=	'" . $currDateTime . "'
					)
				)
				";
        if (isset($productIDs) && !empty($productIDs)) {
            $sql .= "
					AND
					product.productID IN ('" . implode("','", $productIDs) . "')
				";
        }
        if (isset($widgetTabID) && $widgetTabID > 0) {
            $sql .= "
				AND
				widTabIte.widgetTabID = '" . $widgetTabID . "'";
        }
        $sql .= "
					GROUP BY product.productID 	";
        if( isset($hide_out_of_stock_in_homepage) && $hide_out_of_stock_in_homepage=='Yes' ){
			$sql.="
			HAVING 
				itemOptionQuantitySum > 0
			";
        }
        if (isset($widgetTabID) && $widgetTabID > 0) {
            $sql .= "	
				ORDER BY ";
            if (isset($productIDs) && !empty($productIDs)) {
                $sql .= "
						FIELD(product.productID,'" . implode("','", $productIDs) . "' ),
					";
            }
            $sql .= "	
						widTabIte.sortOrder ASC";
        } else if (isset($productIDs) && !empty($productIDs)) {
            $sql .= "	
					ORDER BY 
						FIELD(product.productID,'" . implode("','", $productIDs) . "' )
					";
        }
        if (isset($itemCount) && $itemCount > 0) {
            $sql .= "	
			LIMIT 
				" . $itemCount . "
			";
        }
        //if($widgetTabID=='23')
        //echo $sql;exit;
        return $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);
    }
    public function changeStatus($params = array()) {
        extract($params);
        $sql = "
				UPDATE  
					" . DB_PREFIX . "widgets 
				SET 
					status = '" . $status . "' 
				WHERE
					widgetID IN ('" . implode("','", $widgetIDs) . "')
				";
        $this->ObjDatabase->setQuery($sql);
    }
    public function insert($languageIDs, $widgetID = 0) {
        if ($widgetID > 0) {
            $sql = "
					UPDATE 
						" . DB_PREFIX . "widgets 
					SET
						widgetStartDate = '" . $this->escape($_POST['widgetStartDate']) . "',
						widgetEndDate = '" . $this->escape($_POST['widgetEndDate']) . "',
						sortOrder = '" . (isset($_POST['sortOrder']) ? $this->escape($_POST['sortOrder']) : '') . "',
						widgetDisplayedOn = '" . $this->escape($_POST['widgetDisplayedOn']) . "',
						showTitle = '" . $this->escape($_POST['showTitle']) . "',
						status = '" . $this->escape($_POST['status']) . "',
						widgetPlatform	= '" . $this->escape($_POST['widgetPlatform']) . "',
                                                widget_type	= '" . $this->escape($_POST['widget_type']) . "',
                                                brandID	= '" . $this->escape($_POST['brandID']) . "'    
					WHERE
						widgetID = '" . $widgetID . "'
					";
            $this->ObjDatabase->setQuery($sql);
            $sql = "
					UPDATE 
						" . DB_PREFIX . "widget_details 
					SET
						widgetTitle = '" . $this->escape($_POST['widgetTitle']) . "',
						widgetDescription = '" . $this->escape($_POST['widgetDescription']) . "'
						
					WHERE
						widgetID = '" . $widgetID . "'
						AND
						languageID = '" . $languageIDs['Content'] . "'
					";
            $this->ObjDatabase->setQuery($sql);
            $this->saveWidgetTabPriority();
            $this->ObjDatabase->setQuery("DELETE 
				FROM 
					" . DB_PREFIX . "widget_to_category
				WHERE 
					widgetID = '" . $widgetID . "'");
        } else {
            $sql       = "
					SELECT 
						 MAX(sortOrder)  sortOrder
					FROM 
						" . DB_PREFIX . "widgets";
            $sortOrder = $this->ObjDatabase->getField($sql);
            if ($sortOrder > 0)
                $sortOrder = $sortOrder + 1;
            else
                $sortOrder = 1;
            $sql = "
					INSERT INTO " . DB_PREFIX . "widgets 
						(
						widgetStartDate,
						widgetEndDate,						
						sortOrder,
						widgetDisplayedOn,
						showTitle,
						status,
						widgetPlatform,
                                                widget_type,
                                                brandID
						)
					VALUES
						(
						'" . $this->escape($_POST['widgetStartDate']) . "',
						'" . $this->escape($_POST['widgetEndDate']) . "',						
						'" . $this->escape($sortOrder) . "',						
						'" . $this->escape($_POST['widgetDisplayedOn']) . "',
						'" . (isset($_POST['showTitle']) ? $this->escape($_POST['showTitle']) : '') . "',
						'" . $this->escape($_POST['status']) . "',
						'" . $this->escape($_POST['widgetPlatform']) . "',
                                                '" . $this->escape($_POST['widget_type']) . "',
                                                '" . $this->escape($_POST['brandID']) . "'
						)
					";
            $this->ObjDatabase->setQuery($sql);
            $widgetID = $this->ObjDatabase->getInsertId();
            foreach ($languageIDs['All'] as $languageID) {
                $tempArr[] = "(
					'" . $widgetID . "',
					'" . $languageID . "',
					'" . $this->escape($_POST['widgetTitle']) . "',
					'" . $this->escape($_POST['widgetDescription']) . "')";
            }
            $sql = "
					INSERT INTO " . DB_PREFIX . "widget_details 
						(
						widgetID,
						languageID,
						widgetTitle,
						widgetDescription						 	
						)
					VALUES" . implode(",", $tempArr);
            $this->ObjDatabase->setQuery($sql);
        }
        $this->saveWidgetRelatedData($widgetID);
        $this->saveBannersToWidget($widgetID);
        return $widgetID;
    }
    public function saveWidgetPriority() {
        $caseSql = '';
        foreach ($_POST['widget'] as $widget) {
            $caseSql .= " WHEN widgetID='" . $widget['widgetid'] . "' THEN '" . ($widget['priority'] + 1) . "' ";
        }
        $sql = "
			UPDATE 
				" . DB_PREFIX . "widgets 
			SET 
				sortOrder= 
					CASE 
						" . $caseSql . "
					END";
        $this->ObjDatabase->setQuery($sql);
    }
    public function saveWidgetTabPriority() {
        if ($_POST['postItemIds']) {
            $tabIds  = explode(",", $_POST['postItemIds']);
            $caseSql = '';
            $i       = 0;
            foreach ($tabIds as $widget) {
                if ($widget != '') {
                    $caseSql .= " WHEN widgetTabID='" . $widget . "' THEN '" . ($i) . "' ";
                    $i++;
                }
            }
            $sql = "
			UPDATE 
				" . DB_PREFIX . "widget_tab 
			SET 
				sortOrder= 
					CASE 
						" . $caseSql . "
					END";
            $this->ObjDatabase->setQuery($sql);
        }
    }
    public function saveWidgetTab($languageIDs, $widgetID, $tabID) {
        if ($tabID > 0) {
            $sql = "
				UPDATE 
					" . DB_PREFIX . "widget_tab 
				SET
					itemCount = '" . $this->escape($_POST['itemCount']) . "',
					listingType = '" . $this->escape($_POST['listingType']) . "',
                                        widgetType= '" . $this->escape($_POST['widgetType']) . "',    
					bundleID    = '" . $this->escape($_POST['Bundle']) . "',
					showItemLabel= '" . $this->escape(isset($_POST['showItemLabel']) ? $_POST['showItemLabel'] : 'No') . "',
					viewMoreLabelType = '" . $this->escape(isset($_POST['viewMoreLabelType']) ? $_POST['viewMoreLabelType'] : 'viewMoreLabelType') . "',
					viewMoreLink= '" . $this->escape($_POST['viewMoreLink']) . "',
					enableViewMore = '" . $this->escape(isset($_POST['enableViewMore']) ? $_POST['enableViewMore'] : 'No') . "',
					enableAutogenerate = '" . $this->escape(isset($_POST['enableAutogenerate']) ? $_POST['enableAutogenerate'] : 'No') . "',
					conditions='" . $this->escape($_POST['conditions']) . "',
                                        status= '" . $_POST['status']. "'
                                            
				WHERE
					widgetTabID = '" . $tabID . "'
					";
            $this->ObjDatabase->setQuery($sql);
            $sql = "
				UPDATE 
					" . DB_PREFIX . "widget_tab_details 
				SET
					tabTitle = '" . $this->escape($_POST['tabTitle']) . "',
					viewMoreLabel = '" . $this->escape($_POST['viewMoreLabel']) . "',
                                        staticWidgetContent = '" . $this->escape($_POST['staticWidgetContent'], FALSE) . "'
				WHERE
					widgetTabID = '" . $tabID . "'
					AND
					languageID = '" . $languageIDs['Content'] . "'
				";
            $this->ObjDatabase->setQuery($sql);
        } else {
            $sql       = "
					SELECT 
						 MAX(sortOrder)  sortOrder
					FROM 
						" . DB_PREFIX . "widget_tab";
            $sortOrder = $this->ObjDatabase->getField($sql);
            if ($sortOrder > 0)
                $sortOrder = $sortOrder + 1;
            else
                $sortOrder = 1;
            $sql = "
					INSERT INTO " . DB_PREFIX . "widget_tab 
						(
						widgetID,
						itemCount,
						listingType,
                        widgetType,
						bundleID,
						showItemLabel,
						sortOrder,
						conditions,
						enableViewMore,
						viewMoreLabelType,
						viewMoreLink,
						enableAutogenerate,
						status,
						createdDate
						)
					VALUES
						(
						'" . $this->escape($widgetID) . "',
						'" . $this->escape($_POST['itemCount']) . "',
						'" . $this->escape($_POST['listingType']) . "',
                        '" . $this->escape($_POST['widgetType']) . "',
						'" . $this->escape($_POST['Bundle']) . "',
						'" . $this->escape(isset($_POST['showItemLabel']) ? $_POST['showItemLabel'] : 'No') . "',
						'" . $this->escape($sortOrder) . "',
						'" . $this->escape($_POST['conditions']) . "',
						'" . $this->escape(isset($_POST['enableViewMore']) ? $_POST['enableViewMore'] : 'No') . "',
						'" . $this->escape(isset($_POST['viewMoreLabelType']) ? $_POST['viewMoreLabelType'] : 'viewMoreLabelType') . "',
						'" . $this->escape(isset($_POST['viewMoreLink']) ? $_POST['viewMoreLink'] : '') . "',
						'" . $this->escape(isset($_POST['enableAutogenerate']) ? $_POST['enableAutogenerate'] : 'No') . "',
						'" . $_POST['status']. "',
						NOW()
						)
					";
            $this->ObjDatabase->setQuery($sql);
            $tabID = $this->ObjDatabase->getInsertId();
            foreach ($languageIDs['All'] as $languageID) {
                $tempArr[] = "(
					'" . $tabID . "',
					'" . $languageID . "',
					'" . $this->escape($_POST['tabTitle']) . "',
					'" . $this->escape($_POST['viewMoreLabel']) . "',
                                        '" . $this->escape($_POST['staticWidgetContent'], FALSE) . "')";
            }
            $sql = "
					INSERT INTO " . DB_PREFIX . "widget_tab_details 
						(widgetTabID,
						languageID,
						tabTitle,
						viewMoreLabel,
                                                staticWidgetContent
						)
					VALUES" . implode(",", $tempArr);
            $this->ObjDatabase->setQuery($sql);
        }
        $this->ObjDatabase->setQuery("DELETE FROM " . DB_PREFIX . "widget_tab_items WHERE widgetTabID='" . $tabID . "'");
        if (!empty($_POST['postItemIds'])) {
            $items = explode(",", $_POST['postItemIds']);
            foreach ($items as $key => $item) {
                $order = $key + 1;
                $Arr[] = "(
					'" . $tabID . "',
					'" . $item . "',
					'" . $order . "')";
            }
            $sql = "
					INSERT INTO " . DB_PREFIX . "widget_tab_items 
						(
						widgetTabID,
						itemID,
						sortOrder
						)
					VALUES" . implode(",", $Arr);
            $this->ObjDatabase->setQuery($sql);
        }
        return $tabID;
    }
    public function getTabItemIDs($tabID) {
        return $this->ObjDatabase->getField("SELECT 
				GROUP_CONCAT(itemID ORDER BY sortOrder ASC SEPARATOR ',') AS Col
			FROM
					" . DB_PREFIX . "widget_tab_items WHERE widgetTabID=" . $tabID . " GROUP BY widgetTabID");
    }
    public function listCustomProducts($params = array(),$business='') {
        extract($params);
        $queryRes             = $this->generateQueryConditionString($conditions);
        $userGroupID          = isset($userGroupID) ? $userGroupID : 0;
        $queryCondition       = ($queryRes['condition'] != '') ? $queryRes['condition'] . " ) " : '';
        $queryConditionTables = $queryRes['tables'];
        $orderBy              = $queryRes['orderBy'];
        $isFeatured           = $queryRes['isFeatured'];
        $args                 = array(
            'queryConditionTables' => &$queryConditionTables,
            'queryCondition' => &$queryCondition,
            'orderBy' => &$orderBy,
            'userGroupID' => $userGroupID,
            'itemCount' => &$itemCount,
            'isFeatured' => &$isFeatured,
            'hide_out_of_stock_in_homepage' => $hide_out_of_stock_in_homepage
        );
         $sql                  = $this->setQueryString($args,$business);
        return $this->ObjDatabase->getFields($sql);
    }
    //Set Query String
    private function setQueryString($params,$business='') {
        extract($params);
        $userGroupID = isset($userGroupID) ? (int) $userGroupID : 0;
        $today       = date("Y-m-d");
        $sql         = "
				SELECT SQL_CACHE
					product.productID,
                                        IF(product.InventoryTrackLevel ='No',
					1,
					IF(product.InventoryTrackLevel ='Product',
						(
							SELECT 
									SUM(productOptionQuantity)
								FROM 
									" . DB_PREFIX . "products_options_business
								WHERE 
									productOptionID=productOpt.productOptionID 
									AND 
									businessOptionDefault='Yes'
						),
						(
							SELECT 
									SUM(prodCombBus.businessCombQuantity)
								FROM 
									" . DB_PREFIX . "product_combination_business prodCombBus
                                                                INNER JOIN " . DB_PREFIX . "product_combination AS proCom1
                                                                        ON (proCom1.combinationID = prodCombBus.combinationID)
								WHERE 
									proCom1.productID=product.productID									
									AND 
									proCom1.status='A'
						)
					)
				)
				AS itemOptionQuantitySum
				FROM
					" . DB_PREFIX . "products product
				INNER JOIN
					" . DB_PREFIX . "product_options productOpt
						ON (
							product.productID = productOpt.productID
							AND 
							productOpt.productOptionStatus = 'Active'
							AND 
							productOpt.productOptionDefault = 'Yes'
						)
                                INNER JOIN 
					" . DB_PREFIX . "products_options_business	AS productOptBus 
						ON (
							productOptBus.productOptionID = productOpt.productOptionID
							AND
							productOptBus.busProductStatus = 'Active' 
							AND 
							productOptBus.businessOptionDefault = 'Yes'
						)
				LEFT JOIN
					" . DB_PREFIX . "variant_offer_price AS varOffPri
						ON	(
							varOffPri.productOptionID = productOpt.productOptionID
							AND
							varOffPri.userGroupID='" . (int) $userGroupID . "'
                                                        AND varOffPri.businessID = productOptBus.businessID
						)	
				LEFT JOIN
					" . DB_PREFIX . "variant_group_price AS varGroPri
						ON	(
							varGroPri.productOptionID = productOpt.productOptionID
							AND
							varGroPri.userGroupID='" . (int) $userGroupID . "'
                                                        AND varGroPri.businessID = productOptBus.businessID
						)		
					";
        if (isset($queryConditionTables['productToCat']) && $queryConditionTables['productToCat'] == 1) {
            $sql .= "			
				LEFT JOIN
					" . DB_PREFIX . "product_to_category productToCat
					ON product.productID = productToCat.productID";
        }
        if($business=='Y') {
            $queryConditionTables['business'] = 1;
        }
        if (isset($queryConditionTables['business']) && $queryConditionTables['business'] == 1) {
            $sql .= "			
				INNER JOIN
					" . DB_PREFIX . "business bus
					ON productOptBus.businessID = bus.businessID
					AND bus.businessStatus = 'Active'";
        }
        if ((isset($queryConditionTables['productAttrVal']) && $queryConditionTables['productAttrVal'] == 1) || (isset($queryConditionTables['productAttrValDet']) && $queryConditionTables['productAttrValDet'] == 1)) {
            $sql .= "			
				INNER JOIN
					" . DB_PREFIX . "product_attribute_values productAttrVal
					ON product.productID = productAttrVal.productID";
            if (isset($queryConditionTables['productAttrValDet']) && $queryConditionTables['productAttrValDet'] == 1) {
                $sql .= "					
				LEFT JOIN
					" . DB_PREFIX . "product_attribute_value_details productAttrValDet
					ON productAttrVal.attrValueID = productAttrValDet.attrValueID";
            }
            $sql .= "					
				INNER JOIN
					" . DB_PREFIX . "attributes attr
					ON attr.attributeID = productAttrVal.attributeID
					AND attr.attrStatus = 'A'";
        }
        $sql .= "			
				WHERE
					product.productStatus = 'Active' 
					AND 
					( 
						product.productStartTime <= '" . $today . "'
						AND 
						( 
							product.productEndTime = '0000-00-00' 
							OR 
							product.productEndTime >=  '" . $today . "'
						) 
					)";
        if ($queryCondition != '') {
            $sql .= "
					AND
					" . $queryCondition;
        }
       
        if ($isFeatured != '') {
            $sql .= $isFeatured;
        }
        if (isset($itemCount) && $itemCount > 0) {
            $sql .= "
			GROUP BY 
				product.productID
			";
        }
          if( isset($hide_out_of_stock_in_homepage) && $hide_out_of_stock_in_homepage=='Yes' ){
			$sql.="
			HAVING 
				itemOptionQuantitySum > 0
			";
        }
        if (isset($orderBy) && $orderBy != '') {
            $sql .= "
					ORDER BY
					" . $orderBy;
        }
        $sql .= "
			LIMIT 
				" . $itemCount;
        return $sql;
    }
    //Recursive Function for generating Query Condition String
    private function generateQueryConditionString($conditions, $tables = '') {
        $orderBy    = "";
        $isFeatured = "";
        $query      = '';
        $key        = 1;
        if (!empty($conditions)) {
            $braces = " ( ";
            if (isset($conditions['conditions']) && !empty($conditions['conditions'])) {
                foreach ($conditions['conditions'] as $condition) {
                    if ($conditions['set'] == 'any') {
                        $operator = " OR ";
                    } elseif ($conditions['set'] == 'all') {
                        $operator = " AND ";
                    }
                    $falseCondition = "";
                    if ($conditions['set_value'] == 0) {
                        $falseCondition = " ! ( ";
                    }
                    $query .= $braces;
                    if ($key != 1)
                        $query .= $operator;
                    $query .= $falseCondition;
                    $queryRes = $this->setQueryConditionString($condition, $tables);
                    $query .= $queryRes['sql'];
                    $tables  = $queryRes['tables'];
                    $orderBy = $queryRes['orderBy'];
                    if ($conditions['set_value'] == 0) {
                        $query .= " ) ";
                    }
                    $braces = "";
                    $key++;
                }
            }
        }
        if (isset($conditions['isFeatured']) && $conditions['isFeatured'] == 'Yes') {
            $isFeatured .= " 	
				AND
				featuredStatus ='Yes'";
        }
        if (isset($conditions['orderBy']) && $conditions['orderBy'] != '') {
            switch ($conditions['orderBy']) {
                case 'productID':
                    $orderBy = " product.productID DESC";
                    break;
                case 'discount':
                    $orderBy = " 
						ROUND(
							(
								(
									(
									productOptBus.productOptionRegularPrice-
										LEAST(
											COALESCE(
												varOffPri.offerPrice,
												productOptBus.productOptionProductPrice
											),
											COALESCE(
												varGroPri.specialPrice,
												productOptBus.productOptionProductPrice
											) 
										)
									)*100
								)/productOptBus.productOptionRegularPrice
							),2
						) DESC
					";
                    break;
                case 'best_seller':
                    $orderBy = " purchasePopularity DESC";
                    break;
            }
        }
        return array(
            'condition' => $query,
            'tables' => $tables,
            'orderBy' => $orderBy,
            'isFeatured' => $isFeatured
        );
    }
    //Set Query String based on conditions
    private function setQueryConditionString($condition, $tables) {
        $sql = '';
        if ((isset($condition['value']) && $condition['value'] != '') || (isset($condition['value_select']) && $condition['value_select'] > 0) || (isset($condition['orderby']) && $condition['orderby'] != '')) {
            if ($condition['condition'] == 'price') {
                $sql                  = " productOptBus.productOptionProductPrice " . $this->operatorEvaluation($condition['operator'], $condition['value']);
                $tables['productOpt'] = 1;
            } elseif ($condition['condition'] == 'categories') {
                $sql                    = " productToCat.productCategoryID " . $this->operatorEvaluation($condition['operator'], $condition['value']);
                $tables['productToCat'] = 1;
            } elseif ($condition['condition'] == 'brands') {
                $sql = " product.brandID " . $this->operatorEvaluation($condition['operator'], $condition['value']);
            } elseif ($condition['condition'] == 'products') {
                $sql               = " product.productID " . $this->operatorEvaluation($condition['operator'], $condition['value']);
                $tables['product'] = 1;
            } elseif ($condition['condition'] == 'business') {
                $sql                = " bus.businessID " . $this->operatorEvaluation($condition['operator'], $condition['value']);
                $tables['business'] = 1;
            } elseif ($condition['condition'] == 'attributes') {
                if (isset($condition['value_select']) && $condition['value_select'] > 0) {
                    $sql                      = " (attr.attributeID = '" . $condition['condition_element'] . "' AND  productAttrVal.attrOptionID " . $this->operatorEvaluation($condition['operator'], $condition['value_select']) . ")";
                    $tables['productAttrVal'] = 1;
                } elseif ($condition['value'] != '') {
                    $sql                         = " (attr.attributeID = '" . $condition['condition_element'] . "' AND  productAttrValDet.attrDetValue " . $this->operatorEvaluation($condition['operator'], $condition['value']) . ")";
                    $tables['productAttrValDet'] = 1;
                }
            }
        }
        return array(
            'sql' => $sql,
            'tables' => $tables,
            'orderBy' => isset($orderBy) ? $orderBy : ''
        );
    }
    //Operator Evaluation
    private function operatorEvaluation($op, $value) {
        $result = false;
        if ($op == 'neq') {
            $result = " != '" . $value . "'";
        } elseif ($op == 'eq') {
            $result = " = '" . $value . "'";
        } elseif ($op == 'lte') {
            $result = " <= '" . $value . "'";
            ;
        } elseif ($op == 'lt') {
            $result = " < '" . $value . "'";
        } elseif ($op == 'gte') {
            $result = " >= '" . $value . "'";
        } elseif ($op == 'gt') {
            $result = " > '" . $value . "'";
        } elseif ($op == 'cont') {
            $result = " LIKE '%" . $value . "%' ";
        } elseif ($op == 'ncont') {
            $result = " NOT LIKE '%" . $value . "%' ";
        } elseif ($op == 'in') {
            $conditionValues = explode(',', $value);
            $conditionValue  = "'" . implode("','", $conditionValues) . "'";
            $result          = " IN (" . $conditionValue . ") ";
        } elseif ($op == 'nin') {
            $conditionValues = explode(',', $value);
            $conditionValue  = "'" . implode("','", $conditionValues) . "'";
            $result          = " NOT IN (" . $conditionValue . ") ";
        }
        return $result;
    }
    public function changeWidgetTabStatus($tabID) {
        if ($tabID) {
            $sql = "UPDATE " . DB_PREFIX . "widget_tab
					SET
					status = 'D'
					WHERE widgetTabID='" . $tabID . "'";
            $res = $this->ObjDatabase->setQuery($sql);
            $this->ObjDatabase->setQuery("DELETE FROM " . DB_PREFIX . "widget_tab_items WHERE widgetTabID='" . $tabID . "'");
            return $res;
        }
    }
    public function getWidgetTabSchema($languageXml) {
        //Conditions
        $schema['conditions'] = array(
            'price' => array(
                'operators' => array(
                    'eq->' . $languageXml["lblPromotionSchemaEq"],
                    'neq->' . $languageXml["lblPromotionSchemaNeq"],
                    'lte->' . $languageXml["lblPromotionSchemaLte"],
                    'gte->' . $languageXml["lblPromotionSchemaGte"],
                    'lt->' . $languageXml["lblPromotionSchemaLt"],
                    'gt->' . $languageXml["lblPromotionSchemaGt"],
                    'in->' . $languageXml["lblPromotionSchemaIn"],
                    'nin->' . $languageXml["lblPromotionSchemaNin"]
                ),
                'type' => 'input',
                'lang' => 'lblPromotionSchemaProductPrice'
            ),
            
            'categories' => array(
                'operators' => array(
                    'in->' . $languageXml["lblPromotionSchemaIn"],
                    'nin->' . $languageXml["lblPromotionSchemaNin"]
                ),
                'type' => 'picker',
                'lang' => 'lblPromotionSchemaCategories',
                'popupLink' => 'lblPromotionSchemaLinkCategory',
                'pickerLink' => 'promotions/ajaxLoadCategories/'
            ),
            'products' => array(
                'operators' => array(
                    'in->' . $languageXml["lblPromotionSchemaIn"],
                    'nin->' . $languageXml["lblPromotionSchemaNin"]
                ),
                'type' => 'picker',
                'lang' => 'lblPromotionSchemaProducts',
                'popupLink' => 'lblPromotionSchemaLinkProducts',
                'pickerLink' => 'promotions/ajaxLoadProducts/'
            ),
            'business' => array(
                'operators' => array(
                    'in->' . $languageXml["lblPromotionSchemaIn"],
                    'nin->' . $languageXml["lblPromotionSchemaNin"]
                ),
                'type' => 'picker',
                'lang' => 'lblPromotionSchemaMerchants',
                'popupLink' => 'lblPromotionSchemaLinkMerchants',
                'pickerLink' => 'promotions/ajaxListMerchant/'
            ),
            'attributes' => array(
                'operatorSelectors' => array(
                    'textbox' => array(
                        'eq->' . $languageXml["lblPromotionSchemaEq"],
                        'neq->' . $languageXml["lblPromotionSchemaNeq"],
                        'lte->' . $languageXml["lblPromotionSchemaLte"],
                        'gte->' . $languageXml["lblPromotionSchemaGte"],
                        'lt->' . $languageXml["lblPromotionSchemaLt"],
                        'gt->' . $languageXml["lblPromotionSchemaGt"],
                        'in->' . $languageXml["lblPromotionSchemaIn"],
                        'nin->' . $languageXml["lblPromotionSchemaNin"],
                        'cont->' . $languageXml["lblPromotionSchemaCont"],
                        'ncont->' . $languageXml["lblPromotionSchemaNcont"]
                    ),
                    'textarea' => array(
                        'eq->' . $languageXml["lblPromotionSchemaEq"],
                        'neq->' . $languageXml["lblPromotionSchemaNeq"],
                        'lte->' . $languageXml["lblPromotionSchemaLte"],
                        'gte->' . $languageXml["lblPromotionSchemaGte"],
                        'lt->' . $languageXml["lblPromotionSchemaLt"],
                        'gt->' . $languageXml["lblPromotionSchemaGt"],
                        'in->' . $languageXml["lblPromotionSchemaIn"],
                        'nin->' . $languageXml["lblPromotionSchemaNin"],
                        'cont->' . $languageXml["lblPromotionSchemaCont"],
                        'ncont->' . $languageXml["lblPromotionSchemaNcont"]
                    ),
                    'date' => array(
                        'eq->' . $languageXml["lblPromotionSchemaEq"],
                        'neq->' . $languageXml["lblPromotionSchemaNeq"],
                        'lte->' . $languageXml["lblPromotionSchemaLte"],
                        'gte->' . $languageXml["lblPromotionSchemaGte"],
                        'lt->' . $languageXml["lblPromotionSchemaLt"],
                        'gt->' . $languageXml["lblPromotionSchemaGt"]
                    ),
                    'datetime' => array(
                        'eq->' . $languageXml["lblPromotionSchemaEq"],
                        'neq->' . $languageXml["lblPromotionSchemaNeq"],
                        'lte->' . $languageXml["lblPromotionSchemaLte"],
                        'gte->' . $languageXml["lblPromotionSchemaGte"],
                        'lt->' . $languageXml["lblPromotionSchemaLt"],
                        'gt->' . $languageXml["lblPromotionSchemaGt"]
                    ),
                    'time' => array(
                        'eq->' . $languageXml["lblPromotionSchemaEq"],
                        'neq->' . $languageXml["lblPromotionSchemaNeq"],
                        'lte->' . $languageXml["lblPromotionSchemaLte"],
                        'gte->' . $languageXml["lblPromotionSchemaGte"],
                        'lt->' . $languageXml["lblPromotionSchemaLt"],
                        'gt->' . $languageXml["lblPromotionSchemaGt"]
                    ),
                    'select' => array(
                        'eq->' . $languageXml["lblPromotionSchemaEq"],
                        'neq->' . $languageXml["lblPromotionSchemaNeq"]
                    ),
                    'multiselect' => array(
                        'eq->' . $languageXml["lblPromotionSchemaEq"],
                        'neq->' . $languageXml["lblPromotionSchemaNeq"]
                    )
                ),
                'type' => 'mixed',
                'lang' => 'lblPromotionSchemaGlobalAttributes'
            )
        );
        //print_r($schema);
        return $schema;
    }
    //Rewrite Condition Array
    public function rewriteConditions($params) {
        $ObjPromotions = new PromotionsModel();
        extract($params);
        $currentLanguageID = $languageIDs['Current'];
        if ($type == "promoCatalog") {
            $dataSchema = $this->getWidgetTabSchema($languageXml);
        } elseif ($type == "promoCart") {
            $dataSchema = $this->getCartSchema($languageXml);
        }
        $params            = array(
            'conditionArray' => $conditionArray,
            'conditionOrigArray' => $conditionArray,
            'dataSchema' => $dataSchema,
            'currentLanguageID' => $currentLanguageID,
            'currentLoopKeyVar' => ''
        );
        //print_r($conditionArray);					
        $rewriteConditions = $ObjPromotions->getConditionData($params);
        //print_r($rewriteConditions);	
        return $rewriteConditions;
    }
    public function saveWidgetRelatedData($widgetID) {
        if (isset($_POST['productCategoryID']) && count($_POST['productCategoryID']) > 0) {
            $i = 1;
            foreach ($_POST['productCategoryID'] as $Val) {
                $Sql[] = "('" . $widgetID . "','" . $Val . "','" . $i . "')";
                $i++;
            }
            $this->ObjDatabase->setQuery("
						INSERT INTO
							`" . DB_PREFIX . "widget_to_category` 
							(
								widgetID,
								productCategoryID,
								sortOrder
							)
							VALUES " . implode(",", $Sql));
        }
    }
    public function getCategoriesByWidgetID($widgetID) {
        $sql = "
                    SELECT 
                        productCategoryID 
                    FROM
                         `" . DB_PREFIX . "widget_to_category` 
                    WHERE
                        `widgetID`='" . (int) $widgetID . "'";
        return $this->ObjDatabase->getFields($sql);
    }
    public function listWidgetTocategoryDetails($languageIDs, $widgetID, $status = '') {
        $sql = "
				SELECT
						
						productCatDet.productCategoryName
						FROM
						" . DB_PREFIX . "widget_to_category AS widToCat
					LEFT JOIN
						" . DB_PREFIX . "product_categories AS productCat
							ON	(
								productCat.productCategoryID=	widToCat.productCategoryID								
							) 	
					LEFT JOIN
						" . DB_PREFIX . "product_category_details AS productCatDet 
							ON	(
								widToCat.productCategoryID=productCatDet.productCategoryID
							)
				WHERE
					widgetID='" . $widgetID . "'
					AND 
					productCatDet.languageID = '" . $languageIDs['Current'] . "'";
        return $this->ObjDatabase->readValuesSlave($sql);
    }
    

    public function listWidgetItems($params = array()) {
         extract($params);
        $userGroupID  = isset($userGroupID) ? (int) $userGroupID : 0;
        $currDateTime = date('Y-m-d');
        $sql          = "
			SELECT SQL_CACHE
				product.productID,
				product.productUrl,					 
				product.productImage,
				productDet.productTitle,	
                                productOpt.productOptionID,
                                productOptDet.productOptionName,
				product.productDefaultCurrency,
                                product.productMinBuyLimit,
                                product.productMaxBuyLimit,
                                product.productMaxGiftBuy,
                                bus.businessKey,                                
                                product.productServiceFee, 
                                product.isProductDeal, 
                                productOptBus.productOptionQuantity,
                                productOptBus.productOptionRegularPrice,
                                productOptBus.productOptionProductPrice,
                                productOptBus.businessID,
                                IF(productOptBus.dealPrice>0,productOptBus.dealPrice,ROUND((productOptBus.productOptionProductPrice)-(productOptBus.productOptionProductPrice*(product.dealDiscount/100)))) AS dealPrice,
                                product.InventoryTrackLevel,
                                product.showQuantityAvailable,
				LEAST(
					COALESCE(
						varOffPri.offerPrice,
						productOptBus.productOptionProductPrice
					),
					COALESCE(
						varGroPri.specialPrice,
						productOptBus.productOptionProductPrice
					) 
				)
				AS offerPrice, 
                                ROUND(
					(
						(
							(
							productOptBus.productOptionRegularPrice-
								LEAST(
									COALESCE(
										varOffPri.offerPrice,
										productOptBus.productOptionProductPrice
									),
									COALESCE(
										varGroPri.specialPrice,
										productOptBus.productOptionProductPrice
									) 
								)
							)*100
						)/productOptBus.productOptionRegularPrice
					),2
				) AS productOptionOfferDiscount,
                                (productOptBus.productOptionRegularPrice-productOptBus.productOptionProductPrice) AS productOptionSavePrice,
				ROUND(
					(((productOptBus.productOptionRegularPrice-productOptBus.productOptionProductPrice)*100)/productOptBus.productOptionRegularPrice)) 
				AS productOptionDiscount,
				productOptBus.soldQuantity AS productOrderItemsCount,
                                IF(product.InventoryTrackLevel ='No',
						1,
						IF(product.InventoryTrackLevel ='Product',
							(
								SELECT 
									SUM(productOptionQuantity)
								FROM 
									" . DB_PREFIX . "products_options_business
								WHERE 
									productOptionID=productOpt.productOptionID 
									AND 
									businessOptionDefault='Yes'
							),
							(
								SELECT 
									SUM(prodCombBus.businessCombQuantity)
								FROM 
									" . DB_PREFIX . "product_combination_business prodCombBus
                                                                INNER JOIN " . DB_PREFIX . "product_combination AS proCom1
                                                                        ON (proCom1.combinationID = prodCombBus.combinationID)
								WHERE 
									proCom1.productID=product.productID									
									AND 
									proCom1.status='A'
							)
						)
					)
					AS productOptionQuantitySum FROM ";
                
               
   
            $sql .= "
					" . DB_PREFIX . "widget_tab_items AS widTabIte
				INNER JOIN 
					" . DB_PREFIX . "products AS product 
						ON	(
							widTabIte.itemID = product.productID
							
						)";
       $sql .= "INNER JOIN 
					" . DB_PREFIX . "widget_tab 	AS wt 
						ON (
							wt.widgetTabID = widTabIte.widgetTabID 
							AND 
							wt.status = 'A'
						)";
        $sql .= "INNER JOIN 
					" . DB_PREFIX . "widgets 	AS widgets 
						ON (
							widgets.widgetID = wt.widgetID 
							AND 
							widgets.status = 'A'
						)";
        $sql .= "				
				INNER JOIN 
					" . DB_PREFIX . "product_details AS productDet 
						ON (
							product.productID = productDet.productID 
							AND 
							productDet.languageID = '" . $languageIDs['Current'] . "'
						)
				INNER JOIN 
					" . DB_PREFIX . "product_options	AS productOpt 
						ON (
							product.productID = productOpt.productID
							AND
							productOpt.productOptionStatus = 'Active' 
							AND 
							productOpt.productOptionDefault = 'Yes'
						)
                                INNER JOIN 
					" . DB_PREFIX . "products_options_business	AS productOptBus 
						ON (
							productOptBus.productOptionID = productOpt.productOptionID
							AND
							productOptBus.busProductStatus = 'Active' 
							AND 
							productOptBus.businessOptionDefault = 'Yes'
						)
                                INNER JOIN 
					" . DB_PREFIX . "business 	AS bus 
						ON (
							productOptBus.businessID = bus.businessID 
							AND 
							bus.businessStatus = 'Active'
						)
                                LEFT JOIN 
							".DB_PREFIX."product_option_details	AS productOptDet
								ON (
								productOptDet.productOptionID = productOpt.productOptionID
								AND
								productOptDet.languageID = '".$languageIDs['Current']."'
							)
				LEFT JOIN
					" . DB_PREFIX . "variant_offer_price AS varOffPri
						ON	(
							varOffPri.productOptionID = productOpt.productOptionID
							AND
							varOffPri.userGroupID='" . $userGroupID . "'
                                                        AND varOffPri.businessID = productOptBus.businessID
						)	
				LEFT JOIN
					" . DB_PREFIX . "variant_group_price AS varGroPri
						ON	(
							varGroPri.productOptionID = productOpt.productOptionID
							AND
							varGroPri.userGroupID='" . $userGroupID . "'
                                                        AND varGroPri.businessID = productOptBus.businessID
						)
			WHERE
				product.productStatus = 'Active' 
				
				";
        if (isset($productIDs) && !empty($productIDs)) {
            $sql .= "
					AND
					product.productID IN ('" . implode("','", $productIDs) . "')
				";
        }
        if (isset($widgetTabID) && $widgetTabID > 0) {
            $sql .= "
				AND
				widTabIte.widgetTabID = '" . $widgetTabID . "'";
        }
        if (isset($brandID) && $brandID > 0) {
            $sql .= " AND widgets.brandID = '" . $brandID . "'";
        }
        if (isset($widgetTabID) && $widgetTabID > 0) {
            $sql .= "	
				ORDER BY ";
            if (isset($productIDs) && !empty($productIDs)) {
                $sql .= "
						FIELD(product.productID,'" . implode("','", $productIDs) . "' ),
					";
            }
            $sql .= "	
						widTabIte.sortOrder ASC";
        } else if (isset($productIDs) && !empty($productIDs)) {
            $sql .= "	
					ORDER BY 
						FIELD(product.productID,'" . implode("','", $productIDs) . "' )
					";
        }
        if (isset($itemCount) && $itemCount > 0) {
            $sql .= "	
			LIMIT 
				" . $itemCount . "
			";
        }
        return $this->ObjDatabase->readValuesSlave($sql, MYSQLI_ASSOC);
    }
    public function saveBannersToWidget($widgetID) {
        $this->ObjDatabase->setQuery("DELETE FROM " . DB_PREFIX . "banner_to_widget WHERE widgetID='" . $widgetID . "'");
        if (!empty($_POST['bannerIDs']) && $_POST['widget_type']=='banner') {
            $_POST['bannerIDs']=explode(',',$_POST['bannerIDs']);
            foreach ($_POST['bannerIDs'] as $key=>$bannerID) {
               
          
            $sql = "
					INSERT INTO " . DB_PREFIX . "banner_to_widget 
						(
						widgetID,
						bannerID
						)
					VALUES (
						'" . $widgetID . "',
						'" . $bannerID. "'
                                                )";
            $this->ObjDatabase->setQuery($sql);
}
        }
    }
    public function getSelectedBannerWidget($widgetID){
        $sql="SELECT bannerID FROM ".DB_PREFIX."banner_to_widget WHERE widgetID='".$widgetID."'"; 
        $result         =     $this->ObjDatabase->readValues($sql,MYSQLI_ASSOC);
        $resCity        =     (@array_map(array($this, 'filterbannerIDs'),$result));
        return $resCity;
    }
    public function filterbannerIDs($result)     {
        return $result['bannerID'];
    }
    public function getBannerWidget($widgetID){
        $sql="SELECT banwid.bannerID,ban.bannerSize,banDet.bannerTitle,banDet.bannerImage FROM ".DB_PREFIX."banner_to_widget banwid JOIN ".DB_PREFIX."banner ban ON ban.bannerID=banwid.bannerID  JOIN ".DB_PREFIX."banner_details banDet ON banDet.bannerID=ban.bannerID WHERE widgetID='".$widgetID."' GROUP BY banwid.bannerID";   
        $result         =     $this->ObjDatabase->readValues($sql,MYSQLI_ASSOC);
        return $result;
    }
      public function listBannerWidget($languageIDs,$widgetID,$image_path='') {
        $currentLanguageID = $languageIDs['Current'];
        $sql               = "	
				SELECT 
					ban.bannerID,
					CONCAT('" . $image_path . "',banDet.bannerImage) AS bannerImage,
					ban.bannerSwf,
					ban.bannerStartTime,
					ban.bannerEndTime,
					banDet.bannerTitle,
					ban.bannerDisplayType,
					ban.bannerTextBlend,
                                        ban.bannerSize,
					ban.bannerLink,
					ban.bannerTarget,
					ban.bannerCssStyle,
					banDet.bannerContent 
		
                               FROM
                                        " . DB_PREFIX . "banner_to_widget banWid
				LEFT JOIN 
					" . DB_PREFIX . "banner AS ban
				ON 
					ban.bannerID = banWid.bannerID 
				LEFT JOIN 
					" . DB_PREFIX . "banner_details AS banDet 
				ON 
					banDet.bannerID = ban.bannerID 
					";
         $sql .= "	
				WHERE banWid.widgetID='" . $widgetID . "' AND
					ban.bannerStatus = 'Active'";
        
        $sql .= " AND 
				(banDet.languageID = '" . $currentLanguageID . "') ";
         return $this->ObjDatabase->readValuesSlave($sql);
        
      }
}
		