<?
	/*==================================================================*\
	######################################################################
	#                                                                    #
	# Copyright 2005 Arca Solutions, Inc. All Rights Reserved.           #
	#                                                                    #
	# This file may not be redistributed in whole or part.               #
	# eDirectory is licensed on a per-domain basis.                      #
	#                                                                    #
	# ---------------- eDirectory IS NOT FREE SOFTWARE ----------------- #
	#                                                                    #
	# http://www.edirectory.com | http://www.edirectory.com/license.html #
	######################################################################
	\*==================================================================*/

	# ----------------------------------------------------------------------------------------------------
	# * FILE: /search_filters.php
	# ----------------------------------------------------------------------------------------------------
	
    extract($_GET);
    $aux_array_filters = $_GET;
    
    //Array with all parameters within the query string
    $parameters = array();
    //Array with all parameters within the query string, except for "rating"
    $parametersRating = array();
    //Array with all parameters within the query string, except for "categories"
    $parametersCategories = array();
    //Array with all parameters within the query string, except for "location_x"
    $parametersLocations = array();
    //Array with all parameters within the query string, except for "price"
    $parametersPrice = array();
    //Get Location levels enabled
    $locationsToShow = system_retrieveLocationsToShow("array");

    //query string without "rating"
    $postRating = $aux_array_filters;
    unset($postRating["rating"]);
    unset($postRating["categories"]);
    unset($postRating["filter_price"]);
    unset($postRating["filter_location_".end($locationsToShow)]);
    unset($postRating["filter_deal"]);

    //query string without "categories"
    $postCategs = $aux_array_filters;
    unset($postCategs["categories"]);
    unset($postCategs["rating"]);
    unset($postCategs["filter_price"]);
    unset($postCategs["filter_location_".end($locationsToShow)]);
    unset($postCategs["filter_deal"]);

    //query string without "location"
    $postLocation = $aux_array_filters;
    unset($postLocation["categories"]);
    unset($postLocation["rating"]);
    unset($postLocation["filter_price"]);
    unset($postLocation["filter_location_".end($locationsToShow)]);
    unset($postLocation["filter_deal"]);

    //query string without "deal"
    $postDeal = $aux_array_filters;
    unset($postDeal["categories"]);
    unset($postDeal["rating"]);
    unset($postDeal["filter_price"]);
    unset($postDeal["filter_deal"]);
    unset($postDeal["filter_location_".end($locationsToShow)]);

    //query string without "price"
    $postPrice = $aux_array_filters;
    unset($postPrice["categories"]);
    unset($postPrice["rating"]);
    unset($postPrice["filter_price"]);
    unset($postPrice["filter_deal"]);
    unset($postPrice["filter_location_".end($locationsToShow)]);

    if (!$filterApi) {
    
        foreach ($aux_array_filters as $key => $value) {
            //Removing useless parameters
            if ($key != "screen" && $key != "letter" && $key != "orderby" && $key != "filter_item" && $key != "url_full") {
                if (get_magic_quotes_gpc()) {
                    $value = stripslashes($value);
                }
                $parameters[] = $key."=".urlencode($value);
                if ($key != "rating") {
                    $parametersRating[] = $key."=".urlencode($value);
                }
                if ($key != "categories" && $key != "category_id") {
                    $parametersCategories[] = $key."=".urlencode($value);
                }
                if ($key != "filter_location_".end($locationsToShow)) {
                    $parametersLocations[] = $key."=".urlencode($value);
                }
                if ($key != "filter_price") {
                    $parametersPrice[] = $key."=".urlencode($value);
                }

            }
        }
    
    }

    $filters = array();
    $posFilter = 0;

    if ($filter_item == LISTING_FEATURE_FOLDER) {

        //Auxiliary var to build filter by rate
        setting_get("review_listing_enabled", $review_enabled);

        //Search with all parameters
        $searchReturn = search_frontListingSearch($aux_array_filters, "listing_results");
        //Search with all parameters except for "rating"
        $searchReturnRating = search_frontListingSearch($postRating, "listing_results");
        //Search with all parameters except for "categories"
        $searchReturnCategories = search_frontListingSearch($postCategs, "listing_results");
        //Search with all parameters except for "location"
        $searchReturnLocation = search_frontListingSearch($postLocation, "listing_results");
        //Search with all parameters except for "deal"
        $searchReturnDeal = search_frontListingSearch($postDeal, "listing_results");
        //Search with all parameters except for "price"
        $searchReturnPrice = search_frontListingSearch($postPrice, "listing_results");

        //Available filters for listing
        $availableFilters = array("location","category","deal","rating","price");

        //URL to concat filters with all parameters
        $filterLinkJS = (defined("ACTUAL_MODULE_FOLDER") ? LISTING_DEFAULT_URL : DEFAULT_URL)."/results.php?".str_replace("'", "\'", implode("&", $parameters));

        //URL to concat filters with all parameters except for "rating"
        $filterLinkRatingJS = (defined("ACTUAL_MODULE_FOLDER") ? LISTING_DEFAULT_URL : DEFAULT_URL)."/results.php?".str_replace("'", "\'", implode("&", $parametersRating));

        //URL to concat filters with all parameters except for "categories"
        $filterLinkCategoriesJS = (defined("ACTUAL_MODULE_FOLDER") ? LISTING_DEFAULT_URL : DEFAULT_URL)."/results.php?".str_replace("'", "\'", implode("&", $parametersCategories));

        $filterLinkLocationsJS = (defined("ACTUAL_MODULE_FOLDER") ? LISTING_DEFAULT_URL : DEFAULT_URL)."/results.php?".str_replace("'", "\'", implode("&", $parametersLocations));

        $filterLinkPriceJS = (defined("ACTUAL_MODULE_FOLDER") ? LISTING_DEFAULT_URL : DEFAULT_URL)."/results.php?".str_replace("'", "\'", implode("&", $parametersPrice));

        //Category Obj
        $categObj = "ListingCategory";

        //Aux to check review by level
        $use_level_to_ratings = true;

    } elseif ($filter_item == PROMOTION_FEATURE_FOLDER) {

        //Auxiliary var to build filter by rate
        setting_get("review_promotion_enabled", $review_enabled);

        //Search with all parameters
        $searchReturn = search_frontPromotionSearch($aux_array_filters, "promotion_results");
        //Search with all parameters except for "rating"
        $searchReturnRating = search_frontPromotionSearch($postRating, "promotion_results");
        //Search with all parameters except for "categories"
        $searchReturnCategories = search_frontPromotionSearch($postCategs, "promotion_results");
        //Search with all parameters except for "location"
        $searchReturnLocation = search_frontPromotionSearch($postLocation, "promotion_results");
        //Search with all parameters except for "deal"
        $searchReturnDeal = search_frontPromotionSearch($postDeal, "promotion_results");
        //Search with all parameters except for "price"
        $searchReturnPrice = search_frontPromotionSearch($postPrice, "promotion_results");

        //Available filters for deal
        $availableFilters = array("category","location","rating","week_filter");

        //URL to concat filters with all parameters
        $filterLinkJS = PROMOTION_DEFAULT_URL."/results.php?".str_replace("'", "\'", implode("&", $parameters));

        //URL to concat filters with all parameters except for "rating"
        $filterLinkRatingJS = PROMOTION_DEFAULT_URL."/results.php?".str_replace("'", "\'", implode("&", $parametersRating));

        //URL to concat filters with all parameters except for "categories"
        $filterLinkCategoriesJS = PROMOTION_DEFAULT_URL."/results.php?".str_replace("'", "\'", implode("&", $parametersCategories));
        
        $filterLinkLocationsJS = PROMOTION_DEFAULT_URL."/results.php?".str_replace("'", "\'", implode("&", $parametersLocations));

        $filterLinkPriceJS = PROMOTION_DEFAULT_URL."/results.php?".str_replace("'", "\'", implode("&", $parametersPrice));

        //Category Obj
        $categObj = "ListingCategory";

        //Aux to check review by level
        $use_level_to_ratings = false;
        
    } elseif ($filter_item == EVENT_FEATURE_FOLDER) {

        //Search with all parameters
        $searchReturn = search_frontEventSearch($aux_array_filters, "event");
        //Search with all parameters except for "categories"
        $searchReturnCategories = search_frontEventSearch($postCategs, "event");
        //Search with all parameters except for "location"
        $searchReturnLocation = search_frontEventSearch($postLocation, "event");

        //Available filters for event
        $availableFilters = array("location","category");

        //URL to concat filters with all parameters
        $filterLinkJS = EVENT_DEFAULT_URL."/results.php?".str_replace("'", "\'", implode("&", $parameters));

        //URL to concat filters with all parameters except for "categories"
        $filterLinkCategoriesJS = EVENT_DEFAULT_URL."/results.php?".str_replace("'", "\'", implode("&", $parametersCategories));

        $filterLinkLocationsJS = EVENT_DEFAULT_URL."/results.php?".str_replace("'", "\'", implode("&", $parametersLocations));

        //Category Obj
        $categObj = "EventCategory";
        
    } elseif ($filter_item == CLASSIFIED_FEATURE_FOLDER) {

        //Search with all parameters
        $searchReturn = search_frontClassifiedSearch($aux_array_filters, "classified");
        //Search with all parameters except for "categories"
        $searchReturnCategories = search_frontClassifiedSearch($postCategs, "classified");
        //Search with all parameters except for "location"
        $searchReturnLocation = search_frontClassifiedSearch($postLocation, "classified");

        //Available filters for classified
        $availableFilters = array("location","category");

        //URL to concat filters with all parameters
        $filterLinkJS = CLASSIFIED_DEFAULT_URL."/results.php?".str_replace("'", "\'", implode("&", $parameters));

        //URL to concat filters with all parameters except for "categories"
        $filterLinkCategoriesJS = CLASSIFIED_DEFAULT_URL."/results.php?".str_replace("'", "\'", implode("&", $parametersCategories));

        $filterLinkLocationsJS = CLASSIFIED_DEFAULT_URL."/results.php?".str_replace("'", "\'", implode("&", $parametersLocations));

        //Category Obj
        $categObj = "ClassifiedCategory";
        
    } elseif ($filter_item == ARTICLE_FEATURE_FOLDER) {

        //Search with all parameters
        $searchReturn = search_frontArticleSearch($aux_array_filters, "article");
        //Search with all parameters except for "categories"
        $searchReturnCategories = search_frontArticleSearch($postCategs, "article");
        //Search with all parameters except for "location"
        $searchReturnLocation = search_frontArticleSearch($postLocation, "article");

        //Available filters for article
        $availableFilters = array("category");

        //URL to concat filters with all parameters
        $filterLinkJS = ARTICLE_DEFAULT_URL."/results.php?".str_replace("'", "\'", implode("&", $parameters));

        //URL to concat filters with all parameters except for "categories"
        $filterLinkCategoriesJS = ARTICLE_DEFAULT_URL."/results.php?".str_replace("'", "\'", implode("&", $parametersCategories));

        $filterLinkLocationsJS = ARTICLE_DEFAULT_URL."/results.php?".str_replace("'", "\'", implode("&", $parametersLocations));

        //Category Obj
        $categObj = "ArticleCategory";
        
    } else {
        if ($filterApi) {
            echo "Invalid Resource";
            exit;
        }
    }

    /**
     * Create a file to save cache
     */
    if (isset($category_id)) {
        $aux_filename[] = "category_id=".$category_id;    
    }
    if (isset($location_1)) {
        $aux_filename[] = "location_1=".$location_1;
    }
    if (isset($location_2)) {
        $aux_filename[] = "location_2=".$location_2;
    }
    if (isset($location_3)) {
        $aux_filename[] = "location_3=".$location_3;
    }
    if (isset($location_4)) {
        $aux_filename[] = "location_4=".$location_4;
    }
    if (isset($location_5)) {
        $aux_filename[] = "location_5=".$location_5;
    }
    if (isset($keyword)) {
        $aux_filename[] = "keyword=".$keyword;
    }
    if (isset($where)) {
        $aux_filename[] = "where=".$where;
    }
    $aux_original_search = $aux_filename;
    
    if (is_array($aux_filename)) {
        $filename = md5($filter_item.implode("-",$aux_filename).($filterApi ? "_app" : "")).".php";
        $filename = CACHE_FILTER_FOLDER.$filename;
    }
    
    
    if (isset($filename)) {
        
        if (file_exists($filename) && filesize($filename) > 0) {
            $file_filter_cache = fopen($filename, "r");
            $contents = fread($file_filter_cache, filesize($filename));
            $data_from_cache = unserialize($contents);

            /**
             * Preparing Arrays
             */
            $arrayCategories    = $data_from_cache["categories"];
            $filter_location    = $data_from_cache["locations"];
            $array_filter_price = $data_from_cache["price"];
            $filter_rating      = $data_from_cache["rating"];
            $enable_filter_deal = $data_from_cache["deal"];
        } else {
            $file_filter_cache = fopen($filename, "w+");
        }
    }
    $db = db_getDBObject();

    //Category
    if (in_array("category", $availableFilters)) {

        if (!isset($arrayCategories)) {
            if ($category_id) {
                
                $arrayCategories = array();
                
                if (!$categories) {
                    $categories = $category_id;
                }
                $categObj = new $categObj($category_id);
                
                if ($filter_item == LISTING_FEATURE_FOLDER || $filter_item == PROMOTION_FEATURE_FOLDER) {
                    $arrayCategories[] = $categObj->getNumber("root_id");
                } else {
                    if ($categObj->getNumber("category_id")) {
                        $arrayCategories[] = $categObj->getNumber("category_id");
                    } else {
                        $arrayCategories[] = $categObj->getNumber("id");
                    }
                }
            } else {

                if ($filter_item == LISTING_FEATURE_FOLDER || $filter_item == PROMOTION_FEATURE_FOLDER) {
                    $sub_sql = "SELECT ".($filter_item == PROMOTION_FEATURE_FOLDER ? "listing_id" : "id")." FROM ".$searchReturnCategories["from_tables"]." WHERE ".$searchReturnCategories["where_clause"];
                    $sql = "SELECT category_id, category_root_id FROM Listing_Category WHERE listing_id IN (".$sub_sql.") ORDER BY category_id";
                
                } else {
                    $sql = "SELECT 
                                    cat_1_id,
                                    parcat_1_level1_id,
                                    parcat_1_level2_id,
                                    parcat_1_level3_id,
                                    parcat_1_level4_id,
                                    cat_2_id, 
                                    parcat_2_level1_id,
                                    parcat_2_level2_id,
                                    parcat_2_level3_id,
                                    parcat_2_level4_id,
                                    cat_3_id,
                                    parcat_3_level1_id,
                                    parcat_3_level2_id,
                                    parcat_3_level3_id,
                                    parcat_3_level4_id,
                                    cat_4_id, 
                                    parcat_4_level1_id,
                                    parcat_4_level2_id,
                                    parcat_4_level3_id,
                                    parcat_4_level4_id,
                                    cat_5_id,
                                    parcat_5_level1_id,
                                    parcat_5_level2_id,
                                    parcat_5_level3_id,
                                    parcat_5_level4_id
                                    
                            FROM ".$searchReturnCategories["from_tables"]." WHERE ".$searchReturnCategories["where_clause"];
                }
                $result = $db->unbuffered_query($sql);

                unset($filter_category);

                $arrayCategories = array();
                $arrayTotal = array();

                while ($row = mysql_fetch_assoc($result)) {
                    
                    if ($filter_item == LISTING_FEATURE_FOLDER || $filter_item == PROMOTION_FEATURE_FOLDER) {
                    
                        if (!in_array($row["category_root_id"], $arrayCategories)) {
                            $arrayCategories[] = $row["category_root_id"];
                        }
                        //$arrayTotal[$row["category_root_id"]]++; //total items on father category
                    
                    } else {
                        
                        for ($k = 1; $k <= MAX_CATEGORY_ALLOWED; $k++) {
                
                            if ($row["cat_{$k}_id"] && !in_array($row["cat_{$k}_id"], $arrayCategories)) {
                                $arrayCategories[] = $row["cat_{$k}_id"];
                            }

                            for ($j = MAX_CATEGORY_ALLOWED - 1; $j >= 1; $j--) {

                                if ($row["parcat_{$k}_level{$j}_id"] && !in_array($row["parcat_{$k}_level{$j}_id"], $arrayCategories)) {
                                    $arrayCategories[] = $row["parcat_{$k}_level{$j}_id"];
                                }

                            }

                        }
                                                
                    }
                }

                mysql_free_result($result);

                /**
                 * Generating cache from categories
                 */
                $data_to_cache["categories"] = $arrayCategories;
            }
        }
        
        if (count($arrayCategories) > 0) {
            $filters[$posFilter]["type"] = ($filterApi ? "categories" : "category");
            
            if ($filterApi) {
                $filters[$posFilter]["filters"] = system_buildCategoriesFilter($arrayCategories, $arrayTotal, $categories, $filterLinkCategoriesJS, $aux_array_filters, false, 0, $filter_item, true);
            }
            
            $posFilter++;
        }
    }

    //Location
    if (in_array("location", $availableFilters)) {

        $locationLevel_toShow = end($locationsToShow);
        $array_locationsSelected = explode("-",${"filter_location_".$locationLevel_toShow});
        
        if (!isset($filter_location)) {
            if ($filter_item == PROMOTION_FEATURE_FOLDER) {
                $sql = "SELECT listing_location".end($locationsToShow)." AS location_id"
                        . " FROM ".$searchReturnLocation["from_tables"].""
                        . " WHERE ".$searchReturnLocation["where_clause"]." AND listing_location".end($locationsToShow)." > 0";

            } else {
                $sql = "SELECT location_".end($locationsToShow)." AS location_id";
                $sql .= " FROM ".$searchReturnLocation["from_tables"]." "
                       ." WHERE ".$searchReturnLocation["where_clause"]." AND location_".end($locationsToShow)." > 0";
            }

            $result = $db->unbuffered_query($sql);

            /**
             * Get location id
             */
            if ($result) {
                $array_location = array();
                while ($row = mysql_fetch_assoc($result)) {
                    if (!in_array($row["location_id"], $array_location)) {
                        $array_location[] = $row["location_id"];
                    }

                }
                if (count($array_location) > 0) {
                    $dbMain = db_getDBObject(DEFAULT_DB,true); 
                    $sql = "SELECT name, id FROM Location_".end($locationsToShow)." WHERE id IN (".implode(",",$array_location).") ORDER BY name";
                    $result = $dbMain->unbuffered_query($sql);
                    
                    if ($result) {
                        $filter_location = array();
                        $i = 0;

                        while ($row = mysql_fetch_assoc($result)) {
                            $filter_location[$i][($filterApi ? "value" : "id")]      = ($filterApi ? (float)$row["id"] : $row["id"]);
                            $filter_location[$i][($filterApi ? "label" : "title")]   = $row["name"];
                            $filter_location[$i]["level"]   = ($filterApi ? (float)$locationLevel_toShow : $locationLevel_toShow);
                            $i++;
                        }

                        /**
                         * Generating cache from categories
                         */
                        $data_to_cache["locations"] = $filter_location;

                    }
                }
            }
        }
        
        if (count($filter_location) > 0) {
            $filters[$posFilter]["type"] = ($filterApi ? "filter_location_".$locationLevel_toShow : "location");
            $filters[$posFilter]["filters"] = $filter_location;
            $posFilter++;
        }


    }

    //Deal
    if (in_array("deal", $availableFilters)) {

        if (PROMOTION_FEATURE == "on" && CUSTOM_PROMOTION_FEATURE == "on" && CUSTOM_HAS_PROMOTION == "on") {
            if (!isset($enable_filter_deal)) {

                $levelsWithDeal = system_retrieveLevelsWithInfoEnabled("has_promotion");

                if (is_array($levelsWithDeal)) {
                    $sql = "SELECT id FROM ".$searchReturnDeal["from_tables"]." WHERE ".$searchReturnDeal["where_clause"]." AND promotion_id > 0 AND level IN (".(implode(", ", $levelsWithDeal)).")";
                    $result = $db->query($sql);
                    $listingIDs = array();

                    if (mysql_num_rows($result) > 0) {
                        while ($row = mysql_fetch_assoc($result)) {
                            $listingIDs[] = $row["id"];
                        }
                    }
                    mysql_free_result($result);

                    if (count($listingIDs) > 0) {

                        $searchDeal["listing_IDs"] = implode(",", $listingIDs);
                        $searchReturnDeal_aux = search_frontPromotionSearch($searchDeal, "promotion_results");
                        $sql = "SELECT id FROM ".$searchReturnDeal_aux["from_tables"]." WHERE ".$searchReturnDeal_aux["where_clause"];
                        $result = $db->query($sql);
                        if (mysql_num_rows($result) > 0) {
                            $enable_filter_deal = true;
                            $data_to_cache["deal"] = $enable_filter_deal;
                        }

                    }
                }

            }
        
            if ($enable_filter_deal) {
                $filters[$posFilter]["type"] = ($filterApi ? "filter_deal" : "deal");
                if (!$filterApi) {
                    $filters[$posFilter]["filters"] = true;
                } else {
                    $filterApp[0]["label"] = LANG_LABEL_DEAL_FILTER;
                    $filterApp[0]["value"] = true;
                    $filters[$posFilter]["filters"] = $filterApp;
                }
                $posFilter++;
            }
            
        }
        
    }

    //Price
    if (in_array("price", $availableFilters) && THEME_LISTING_PRICE && !$price) {
        
        unset($array_filter_price);
        $aux_filter_price = explode("-", $filter_price);
        if (!isset($array_filter_price)) {
            $fieldsListing = system_getFormFields("listing", "", "price");
            setting_get("listing_price_symbol", $listing_price_symbol);

            if (is_array($fieldsListing)) {

                $sql = "    SELECT price

                            FROM ".$searchReturnPrice["from_tables"]."

                            WHERE ".$searchReturnPrice["where_clause"]." AND price > 0 AND level IN (".implode(", ", $fieldsListing).")";

                $result = $db->unbuffered_query($sql);
                
                $i = 0;
                $arrayPrice = array();
                while ($row = mysql_fetch_assoc($result)) {
                    if (!in_array($row["price"], $arrayPrice)) {
                        if (!$filterApi) {
                            $array_filter_price[$i]["price"] = $row["price"];
                        } else {
                            $array_filter_price[$i]["label"] = $row["price"];
                            $array_filter_price[$i]["value"] = (float)$row["price"];
                        }
                        $arrayPrice[] = $row["price"];
                    }

                    $i++;
                }
                mysql_free_result($result);
                /**
                 * Generating cache from categories 
                 */
                $data_to_cache["price"] = $array_filter_price;
            }
        } else {
            unset($arrayPrice);
            for ($i = 0; $i < count($array_filter_price); $i++) {
                $arrayPrice[] = $array_filter_price[$i]["price"];
            }
        }
        
        if (count($array_filter_price) > 0) {
            rsort($array_filter_price);
            $filters[$posFilter]["type"] = ($filterApi ? "filter_price" : "price");
            $filters[$posFilter]["filters"] = $array_filter_price;
            $posFilter++;
        }
    }

    //Rating
    if (in_array("rating", $availableFilters) && !$avg_review) {
        
        setting_get("commenting_edir", $commenting_edir);

        if ($review_enabled == "on" && $commenting_edir) {
            
            if (!isset($filter_rating)) {
                
                if ($use_level_to_ratings) {
                    $levelsWithReview = system_retrieveLevelsWithInfoEnabled("has_review");
                }

                if (is_array($levelsWithReview) || ($filter_item == PROMOTION_FEATURE_FOLDER)) {

                    $sql = "    SELECT avg_review AS rating 

                                FROM ".$searchReturnRating["from_tables"]." 

                                WHERE ".$searchReturnRating["where_clause"]." AND avg_review > 0 ".($use_level_to_ratings ? "AND level IN (".(implode(", ", $levelsWithReview)).")" : "");

                    $result = $db->unbuffered_query($sql);
                    unset($filter_rating);

                    $i = 0;
                    $arrayReview = array();
                    while ($row = mysql_fetch_assoc($result)) {
                        if (!in_array($row["rating"], $arrayReview)) {
                            if (!$filterApi) {
                                $filter_rating[$i]["rating"] = $row["rating"];
                            } else {
                                $filter_rating[$i]["label"] = $row["rating"];
                                $filter_rating[$i]["value"] = (float)$row["rating"];
                            }
                            $arrayReview[] = $row["rating"];
                        }

                        $i++;
                    }
                    mysql_free_result($result);
                    
                    /**
                     * Generating cache from categories 
                     */
                    $data_to_cache["rating"] = $filter_rating;

                }
            }
            
            if (count($filter_rating) > 0) {
                rsort($filter_rating);
                $filters[$posFilter]["type"] = "rating";
                $filters[$posFilter]["filters"] = $filter_rating;
                $posFilter++;
            }
            
        }
    }

    if (!isset($data_from_cache) && $file_filter_cache) {
        fwrite($file_filter_cache, serialize($data_to_cache));
        fclose($file_filter_cache);
    }

    //Filter to Deal
    if (in_array("week_filter", $availableFilters)) {

        if (PROMOTION_FEATURE == "on" && CUSTOM_PROMOTION_FEATURE == "on" && CUSTOM_HAS_PROMOTION == "on") {

            if(!$search_lock){
                $levelsWithDeal = system_retrieveLevelsWithInfoEnabled("has_promotion");

                if (is_array($levelsWithDeal) && (count($filters) > 0)) {

                    if ($filter_valid_for) {

                        unset($aux_filter_lang);
                        $filters[$posFilter]["type"] = "valid_for";

                        if ($filter_valid_for == "deal_week") {
                            $aux_filter_lang = array("deal_week", LANG_LABEL_FILTER_VALID_FOR_MORE_THAN_A_WEEK);
                        } elseif ($filter_valid_for == "deal_1_day") {
                            $aux_filter_lang = array("deal_1_day", LANG_LABEL_FILTER_ENDS_IN_LESS_THAN_24_HOURS);
                        } elseif ($filter_valid_for == "deal_2_day") {
                            $aux_filter_lang = array("deal_2_day",LANG_LABEL_FILTER_VALID_FOR_MORE_THAN_2_DAYS);
                        }

                        $filters[$posFilter]["filters"][] = $aux_filter_lang;
                        $posFilter++;

                    } else {

                        $visibility_start = date('H')*60+date('i');
                        $visibility_end = date('H')*60+date('i');

                        $where_clause = " ((Promotion.visibility_start <= $visibility_start AND Promotion.visibility_end >= $visibility_end ) OR (Promotion.visibility_start = 24 AND Promotion.visibility_end = 24)) ";

                        $sql = "SELECT  if (end_date > DATE_FORMAT(adddate(now(), interval 1 week), '%Y-%m-%d'), 1, 0 ) as count_week,
                                        if (end_date <= DATE_FORMAT(adddate(now(), interval 1 day), '%Y-%m-%d'), 1, 0 ) as count_1_day,
                                        if (end_date > DATE_FORMAT(adddate(now(), interval 2 day), '%Y-%m-%d'), 1 ,0 ) as count_2_day
                                 FROM Promotion 
                                 WHERE Promotion.listing_status = 'A' AND 
                                       Promotion.end_date >= DATE_FORMAT(NOW(), '%Y-%m-%d') AND 
                                       Promotion.start_date <= DATE_FORMAT(NOW(), '%Y-%m-%d') AND 
                                       ".$where_clause." AND
                                       Promotion.listing_id > 0 AND 
                                       Promotion.listing_level IN (".(implode(", ", $levelsWithDeal)).") 
                                 GROUP BY count_week, count_1_day, count_2_day";

                        $result = $db->unbuffered_query($sql);

                        $aux_count_week  = 0;
                        $aux_count_1_day = 0;
                        $aux_count_2_day = 0;

                        while ($row = mysql_fetch_assoc($result)) {

                            if ($row["count_week"] == 1) {
                                $aux_count_week++;
                            }
                            if ($row["count_1_day"] == 1) {
                                $aux_count_1_day++;
                            }
                            if ($row["count_2_day"] == 1) {
                                $aux_count_2_day++;
                            }

                        }

                        $array_filter_deal = array();

                        if ($aux_count_week > 0) {
                            if (!$filterApi) {
                                $array_filter_deal[] = array("deal_week", LANG_LABEL_FILTER_VALID_FOR_MORE_THAN_A_WEEK);
                            } else {
                                $array_filter_deal[] = array("value" => "deal_week", "label" => LANG_LABEL_FILTER_VALID_FOR_MORE_THAN_A_WEEK);
                            }
                        }
                        if ($aux_count_1_day > 0) {
                            if (!$filterApi) {
                                $array_filter_deal[] = array("deal_1_day", LANG_LABEL_FILTER_ENDS_IN_LESS_THAN_24_HOURS);
                            } else {
                                $array_filter_deal[] = array("value" => "deal_1_day", "label" => LANG_LABEL_FILTER_ENDS_IN_LESS_THAN_24_HOURS);
                            }
                        }
                        if ($aux_count_2_day > 0) {
                            if (!$filterApi) {
                                $array_filter_deal[] = array("deal_2_day", LANG_LABEL_FILTER_VALID_FOR_MORE_THAN_2_DAYS);
                            } else {
                                $array_filter_deal[] = array("value" => "deal_2_day", "label" => LANG_LABEL_FILTER_VALID_FOR_MORE_THAN_2_DAYS);
                            }
                        }
                        if (count($array_filter_deal) > 0) {
                            $filters[$posFilter]["type"] = ($filterApi ? "filter_valid_for" : "valid_for");
                            $filters[$posFilter]["filters"] = $array_filter_deal;
                            $posFilter++;
                        }

                    }
                }
            }
        }
    }
    
?>