<?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: SearchController.php, v 1.0 2013/06/12 16:00:00
//
class SearchController extends Controller {
    public function __construct() {
        parent::__construct();
        $this->ObjView->assign('statPageName', 'catalogSearch');
    }
    public function indexAction() {
        $ObjCategory           = new ProductCategoryModel();
        $languageIDs           = $this->ObjView->languageIDs;
        $searchKeyword         = $_GET['keyword'];
        $searchCatID           = isset($_GET['in']) ? (int) $_GET['in'] : 0;
        $selCategoryDet        = $ObjCategory->getCategoryInfo($languageIDs, $searchCatID, '');
        $pageDefaultView       = $selCategoryDet['pageDefaultView'];
        $catIDAndSubcategories = implode(",", array_merge(array(
            $searchCatID
        ), $this->ObjCommon->getSubCategories($searchCatID, 'ID')));
        //$GlobalSelectedCategoryID	= $this->ObjCommon->getCategoryMenu($languageIDs,$selCategoryDet['productCategoryKey']);
        $this->listProductsUnderCategory($searchCatID);
        $rviEnable        = $this->getSettingValue('product_cart_settings', 'recently_viewed_items');
        $enableRecentView = 0;
        if ($rviEnable == 'Yes') {
            if ($this->ObjCookie->getCookie("RVI_IDS")) {
                $enableRecentView = 1;
            }
        }
        $this->assignWishlistProductList();
        $this->ObjView->assign('catIDAndSubcategories', $catIDAndSubcategories);
        $this->ObjView->assign('enableRecentView', $enableRecentView);
        $this->ObjView->assign('searchKeyword', htmlspecialchars($searchKeyword, ENT_QUOTES, 'UTF-8'));
        $this->ObjView->assign('pageDefaultView', $pageDefaultView);
        $this->ObjView->assign('searchCategory', $searchCatID);
        $this->ObjView->assign('originCatalogID', $searchCatID);
        $this->ObjView->assign('selCategoryDet', $selCategoryDet);
        $this->ObjView->assign('languageID', $languageIDs['Current']);
        $this->ObjView->assign('pageLayout', 'catalog/default/');
        $this->ObjView->display('catalog/Search.tpl');
    }
    private function assignWishlistProductList() {
        $ObjWishList            = new WishlistModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $params                 = array(
            'userID' => $this->ObjCommon->REGISTERED_USER_ID,
            'languageIDs' => $languageIDs
        );
        $listUsersWishListItems = $ObjWishList->listUsersWishListItems($params);
        $this->ObjView->assign('listUsersWishListItems', $listUsersWishListItems);
    }
    private function listProductsUnderCategory($selCategoryID, $isAjax = false) {
        $ObjProductList        = new ProductListModel();
        $ObjProduct            = new ProductModel();
        $ObjCustomOption       = new CustomOptionModel();
        $ObjLog                = new AnalyticsModel();
        $catIDAndSubcategories = '';
        $languageIDs           = $this->ObjView->languageIDs;
        $productType           = array(
            'productTypeKey' => 'product_product',
            'productTypeUrlKey' => '',
            'productTypeName' => $this->getLanguageValue('lblProducts')
        );
        $sefProductIDArray     = array();
        $product_list_count    = $this->getSettingValue('product_cart_settings', 'product_list_count');
        $settingsCatalogSef    = $this->getSettingValue('seo_settings', 'product_sef_format');
        /* START : Search key word Tracking */
        $ObjSearchTerm         = new SearchTermModel();
        $languageIDs           = $this->ObjView->languageIDs;
        $categoryID            = isset($_GET['in']) ? (int) $_GET['in'] : 0;
        $params                = array(
            "languageIDs" => $languageIDs,
            "queryText" => $_GET['keyword'],
            "categoryID" => isset($_GET['in']) ? (int) $_GET['in'] : 0
        );
        $checkKeywordExist     = $ObjSearchTerm->checkKeywordExist($params);
        if ($checkKeywordExist) {
            $getSeachTerms = $ObjSearchTerm->getSeachTerms($params);
            if ($getSeachTerms['queryStatus'] == 'A') {
                $relatedSearch = $ObjSearchTerm->getRelatedSearchKeywords($params);
                if ($getSeachTerms['redirect'] != '') {
                    $this->setRedirect($getSeachTerms['redirect']);
                }
                if ($getSeachTerms['synonymFor'] != '') {
                    $searchKeyword = preg_split("/,/", $getSeachTerms['synonymFor']);
                    if (is_array($searchKeyword)) {
                        $searchKeyword = array_merge($searchKeyword, array(
                            $_GET['keyword']
                        ));
                    }
                } else {
                    $searchKeyword = array(
                        $_GET['keyword']
                    );
                }
            } else {
                $searchKeyword = array(
                    $_GET['keyword']
                );
            }
        } else {
            $searchKeyword = array(
                $_GET['keyword']
            );
        }
        if ($selCategoryID > 0) {
            $catIDAndSubcategories = implode(",", array_merge(array(
                $selCategoryID
            ), $this->ObjCommon->getSubCategories($selCategoryID, 'ID')));
        }
        $_POST['page']  = isset($_POST['page']) ? $_POST['page'] : '';
        $args           = array(
            'requestedBy' => 'customer',
            'requestPage' => 'category_prod_listing',
            'limitFrom' => $_POST['page'] * $product_list_count,
            'limitTo' => $product_list_count,
            'languageIDs' => $languageIDs,
            'productType' => $productType,
            'categoryID' => $catIDAndSubcategories,
            'customOrderBy' => 'spcl_offers',
            'searchKeyword' => $searchKeyword,
            'userGroupID' => (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID
        );
        $resAllProducts = $ObjProductList->listActiveProducts($args);
        //$resPagesCount = $this->setPagesCount($key = 'page');
        $prodsMaxCount  = $ObjProductList->getProductsMaxCount();
        $this->ObjView->assign('listDiscountSchema', $ObjProductList->listDiscountSchema());
        $priceRangeArgs = array(
            'productCategoryID' => $catIDAndSubcategories,
            'languageIDs' => $languageIDs,
            'searchKeyword' => $searchKeyword,
            'userGroupID' => (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID
        );
        $priceRanges    = $ObjProductList->getPriceRange($priceRangeArgs);
        $this->ObjView->assign('priceRanges', $priceRanges);
        /* To update the user enterded search keywords. The search keyword report will be shown in admin side Catalog Section */
        $visitorID             = $this->ObjCookie->getCookie("GT_VISITORID"); //Visitor ID Cookie
        $visitorSearchNotExits = true;
        if ($checkKeywordExist && $_GET['keyword'] != '') {
            $visitorSearchID = $ObjLog->saveVisitorSearch($visitorID, $getSeachTerms['queryID']);
            if ($visitorSearchID < 1) {
                $visitorSearchNotExits = false;
            }
        }
        if ($_GET['keyword'] != '') {
            if ($checkKeywordExist) {
                if ($prodsMaxCount == 0 && $getSeachTerms['relatedSearchTerm'] != '' && $getSeachTerms['queryStatus'] == 'A') {
                    $relatedSearchTerms = preg_split("/,/", $getSeachTerms['relatedSearchTerm']);
                    $this->ObjView->assign('relatedSearchTerms', $relatedSearchTerms);
                }
                if ($visitorSearchNotExits) {
                    $params  = array(
                        "set" => array(
                            "languageID='" . $languageIDs['Current'] . "'",
                            "numResults='" . $prodsMaxCount . "'",
                            "popularity=popularity+1",
                            "updatedAt='" . date('Y-m-d H:i:s') . "'"
                        ),
                        "queryID" => $getSeachTerms['queryID']
                    );
                    $queryID = $ObjSearchTerm->insert($params);
                } else {
                    $params  = array(
                        "set" => array(
                            "numResults='" . $prodsMaxCount . "'",
                            "updatedAt='" . date('Y-m-d H:i:s') . "'"
                        ),
                        "queryID" => $getSeachTerms['queryID']
                    );
                    $queryID = $ObjSearchTerm->insert($params);
                }
            } else {
                $params          = array(
                    "fields" => array(
                        'queryText' => $_GET['keyword'],
                        'languageID' => $languageIDs['Current'],
                        'numResults' => $prodsMaxCount,
                        'categoryID' => (int) $categoryID,
                        'popularity' => 1
                    )
                );
                $queryID         = $ObjSearchTerm->insert($params);
                $visitorSearchID = $ObjLog->saveVisitorSearch($visitorID, $queryID);
            }
        }
        foreach ($resAllProducts as $resProduct) {
            $productOptionID         = $resProduct['productOptionID'];
            $offerPrice              = $resProduct['offerPrice'];
            /* START : to get the minimum tier price */
            $params                  = array(
                'productOptionID' => $productOptionID,
                'offerPrice' => $offerPrice,
                'userGroupID' => (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID
            );
            $resProduct['tierPrice'] = $ObjProductList->getMinTierPrices($params);
            if ($resProduct['productEndTime'] != '0000-00-00 00:00:00') {
                $seconds                = strtotime($resProduct['productEndTime']) - strtotime($resProduct['timeZoneConverted']);
                $resProduct['daysLeft'] = ceil($seconds / 3600 / 24);
            }
            $currProdID                  = $resProduct['productID'];
            $settingsAllowProductReviews = $this->getSettingValue('product_cart_settings', 'allow_product_reviews');
            if ($settingsAllowProductReviews == 'Yes') {
                $prodReviews = $ObjProductList->fetchProductReviews($currProdID);
                $resProduct  = array_merge($resProduct, $prodReviews);
            }
            if (isset($resProduct['productOptionCount']) && $resProduct['productOptionCount'] == 1) {
                $resProduct['customOptionCount'] = $ObjCustomOption->getProductCustomOptionsCount($currProdID);
            }

            /* function call for Product option count */
            $args                             = array(
                'productID' => $currProdID
            );
            $resProduct['productOptionCount'] = $ObjProductList->getProductOptionCount($args);
             
            if ($resProduct['productOptionCount'] > 0) {
                if (isset($productOptionID) && $productOptionID > 0) {
                    $params                        = array(
                        'languageIDs' => $languageIDs,
                        'productID' => $currProdID,
                        'productOptionID' => $productOptionID,
                        'inventoryTrackLevel' => $resProduct['InventoryTrackLevel'],
                        'showQuantityAvailable' => $resProduct['showQuantityAvailable'],
                        'userGroupID' => (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID
                    );
                    $resProduct['options'] = $ObjProductList->fetchProductOptionsInfo($params);
                } else {
                    $params                        = array(
                        'languageIDs' => $languageIDs,
                        'productID' => $currProdID,
                        'productOptionID' => 0,
                        'inventoryTrackLevel' => $resProduct['InventoryTrackLevel'],
                        'showQuantityAvailable' => $resProduct['showQuantityAvailable'],
                        'userGroupID' => (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID
                    );
                    $resProduct['options'] = $ObjProductList->fetchProductOptionsInfo($params);
                }
                foreach ($resProduct['options'] as $key => $option) {
                    $params                                            = array(
                        'productOptionID' => $option['productOptionID'],
                        'offerPrice' => $option['offerPrice'],
                        'userGroupID' => (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID
                    );
                    $resProduct['options'][$key]['tierPrices'] = $ObjProductList->listTierPrices($params);
                }
            } 
            $argsFreeProducts                 = array(
                                                    'requestedBy' => 'customer',
                                                    'requestPage' => 'product_detail',
                                                    'limitFrom' => 0,
                                                    'limitTo' => '',
                                                    'languageIDs' => $languageIDs,
                                                    'previewOnly' => '',
                                                    'currDateTime' => '',                                    
                                                    'selectedProductID' => $currProdID,
                                                    'userGroupID' => (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID

                                                );
            $listactivefreeproducts = $ObjProduct->getActiveFreeProducts($argsFreeProducts);
            $resProduct['freeProductsCount'] = count($listactivefreeproducts);
            $resProducts[]       = $resProduct;
            $sefProductIDArray[] = $currProdID;
            
            
        }
        $this->ObjCommon->setCommonSefPath(array(
            'product'
        ), $sefProductIDArray);
        if ($selCategoryID > 0) {
            $args        = array(
                'requestedBy' => 'customer',
                'requestPage' => 'category_best_seller',
                'limitFrom' => 0,
                'limitTo' => 1,
                'languageIDs' => $languageIDs,
                'productType' => $productType,
                'categoryID' => $selCategoryID,
                'customOrderBy' => 'best_sellers',
                'searchKeyword' => $searchKeyword,
                'userGroupID' => (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID
            );
            $bestSellers = $ObjProductList->listActiveProducts($args);
            $this->ObjView->assign('bestSeller', isset($bestSellers[0]) ? $bestSellers[0] : array());
        }
        $this->ObjView->assign('searchKeywordArray', json_encode($searchKeyword));
        if (isset($relatedSearch))
            $this->ObjView->assign('relatedSearch', $relatedSearch);
        $this->ObjView->assign('resProducts', isset($resProducts) ? $resProducts : array());
        $this->ObjView->assign('productPageCount', ceil($prodsMaxCount/$product_list_count));
        $this->ObjView->assign('prodsMaxCount', $prodsMaxCount);
    }
	
	public function ajaxAutoSuggestAction() {
        $ObjProductList = new ProductListModel();
        $ObjBrand       = new BrandModel();
        $ObjSearchTerm  = new SearchTermModel();
        $languageIDs    = $this->ObjView->languageIDs;
        $arrSuggestions = array();
        $searchQuery    = $this->decodeUrlString($_GET['term']);
        $selCategoryID  = $_GET['catID'];
        $subCategories  = $this->ObjCommon->getSubCategories($selCategoryID, 'ID');
        if (count($subCategories) > 0) {
            $catIDAndSubcategories = $selCategoryID . "," . implode(",", $subCategories);
        } else {
            $catIDAndSubcategories = $selCategoryID;
        }
        $args         = array(
            'requestedBy' => 'customer',
            'requestPage' => 'search_autosuggest',
            'limitFrom' => 0,
            'limitTo' => 15,
            'languageIDs' => $languageIDs,
            'categoryID' => $catIDAndSubcategories,
            'searchKeyword' => $searchQuery
        );
        $arrResTitles = $ObjProductList->searchAutoSuggest($args);
		foreach ($arrResTitles as $resTitle) {
            $arrSuggestions[] = array(
                'productOptionName' => $this->decodeSplChar($resTitle['productOptionName']),
                'productCategoryName' => $this->decodeSplChar($resTitle['productCategoryName']),
                'productCategoryID' => $this->decodeSplChar($resTitle['productCategoryID']),
                'productTitle' => $this->decodeSplChar($resTitle['productTitle']),
                'brandKey' => '',
                'searchTags' => isset($resTitle['searchTags']) ? $this->decodeSplChar($resTitle['searchTags']) : ''
            );
        }
        if (isset($arrSuggestions) && count($arrSuggestions) < 16) {
            $languageIDs['Content'] = $languageIDs['Current'];
            $params                 = array(
                'categoryID' => 0,
                'languageIDs' => $languageIDs,
                'searchQuery' => $searchQuery,
                'getFields' => 'queryText AS productTitle'
            );
            $listSeachTerms         = $ObjSearchTerm->listSeachTerms($params);
            foreach ($listSeachTerms as $resTitle) {
                $arrSuggestions[] = array(
                    'brandKey' => '',
                    'productTitle' => $this->decodeSplChar($resTitle['productTitle']),
                    'productOptionName' => $this->decodeSplChar($resTitle['productTitle'])
                );
            }
			
			if (count($arrSuggestions) < 16) {
                $params    = array(
                    'languageIDs' => $languageIDs,
                    'brandName' => $searchQuery
                );
                $listBrand = $ObjBrand->listBrand($params);
                foreach ($listBrand as $resTitle) {
                    $arrSuggestions[] = array(
                        'productTitle' => $this->decodeSplChar(strtolower($resTitle['brandName'])),
                        'brandKey' => $this->decodeSplChar($resTitle['brandKey']),
                        'productOptionName' => $this->decodeSplChar(strtolower($resTitle['brandName']))
                    );
                }
            }
        }
        echo json_encode($arrSuggestions);
        exit;
    }
}

