<?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: CatalogsearchController.php, v 1.0 2011/06/14 20:52:11
//
class CatalogsearchController extends Controller {
    public function indexAction() {
        $ObjSearchTerm          = new SearchTermModel();
        $ObjLanguage            = new LanguageModel();
        $ObjProductCategory     = new ProductCategoryModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $settingsDateFormat     = $date_format = $this->getSettingValue('site_settings', 'date_format');
        $languageIDs['Current'] = $languageIDs['Content'];
        $link                   = 'catalogsearch/index/';
        $page                   = '';
        if (isset($_POST['submitSearch'])) {
            if ($_POST['queryTextSearch'] != '') {
                $link .= 'queryText/' . $this->encodeUrlString($_POST['queryTextSearch']) . '/';
            }
            if ($_POST['categoryID'] != '') {
                $link .= 'categoryID/' . $_POST['categoryID'] . '/';
            }
            if ($_POST['synonymForSearch'] != '') {
                $link .= 'synonymFor/' . $this->encodeUrlString($_POST['synonymForSearch']) . '/';
            }
            if ($_POST['numResultsSearch'] != '') {
                $link .= 'numResults/' . $this->encodeUrlString($_POST['numResultsSearch']) . '/';
            }
            if ($_POST['popularitySearch'] != '') {
                $link .= 'popularity/' . $this->encodeUrlString($_POST['popularitySearch']) . '/';
            }
            if ($_POST['queryStatusSearch'] != '') {
                $link .= 'queryStatus/' . $this->encodeUrlString($_POST['queryStatusSearch']) . '/';
            }
            if ($_POST['searchDate'] != '') {
                if (strpos($_POST['searchDate'], " - ")) {
                    $searchDates = explode(' - ', $_POST['searchDate']);
                    $fromDate    = $searchDates[0];
                    if (isset($searchDates[1]))
                        $toDate = $searchDates[1];
                } else {
                    $fromDate = $toDate = $_POST['searchDate'];
                }
                $searchProductFromDate = trim($fromDate);
                $searchProductToDate   = trim($toDate);
            }
            if (isset($searchProductFromDate)) {
                $link .= "from/" . $this->urlDate($searchProductFromDate, 'set', $settingsDateFormat) . "/";
            }
            if (isset($searchProductToDate)) {
                $link .= "to/" . $this->urlDate($searchProductToDate, 'set', $settingsDateFormat) . "/";
            }
            $this->setRedirect($link);
        } else {
            $params         = array(
                "languageIDs" => $languageIDs
            );
            $queryText      = $this->decodeUrlString($this->getRequestValue("queryText"));
            $synonymFor     = $this->decodeUrlString($this->getRequestValue("synonymFor"));
            $numResults     = $this->decodeUrlString($this->getRequestValue("numResults"));
            $popularity     = $this->decodeUrlString($this->getRequestValue("popularity"));
            $queryStatus    = $this->decodeUrlString($this->getRequestValue("queryStatus"));
            $searchFromDate = $this->urlDate($this->getRequestValue("from"), 'get', $settingsDateFormat);
            $searchToDate   = $this->urlDate($this->getRequestValue("to"), 'get', $settingsDateFormat);
            $categoryID     = $this->getRequestValue("categoryID");
            $orderby        = $this->getRequestValue("orderby");
            $sortby         = $this->getRequestValue("sortby");
            if (isset($searchFromDate) && $searchFromDate != '') {
                $link .= "from/" . $this->urlDate($searchFromDate, 'set', $settingsDateFormat) . "/";
                $params['searchFromDate'] = $this->convertDateForSQL($searchFromDate, $settingsDateFormat);
            }
            if (isset($searchToDate) && $searchToDate != '') {
                $link .= "to/" . $this->urlDate($searchToDate, 'set', $settingsDateFormat) . "/";
                $params['searchToDate'] = $this->convertDateForSQL($searchToDate, $settingsDateFormat);
            }
            if ($queryText != '') {
                $params['queryText'] = $queryText;
                $this->ObjView->assign("queryTextSearch", $queryText);
                $link .= 'queryText/' . $this->encodeUrlString($queryText) . '/';
            }
            if ($synonymFor != '') {
                $params['synonymFor'] = $synonymFor;
                $this->ObjView->assign("synonymForSearch", $synonymFor);
                $link .= 'synonymFor/' . $this->encodeUrlString($synonymFor) . '/';
            }
            if ($numResults != '') {
                $params['numResults'] = $numResults;
                $this->ObjView->assign("numResultsSearch", $numResults);
                $link .= 'numResults/' . $this->encodeUrlString($numResults) . '/';
            }
            if ($popularity != '') {
                $params['popularity'] = $popularity;
                $this->ObjView->assign("popularitySearch", $popularity);
                $link .= 'popularity/' . $this->encodeUrlString($popularity) . '/';
            }
            if ($queryStatus != '') {
                $params['queryStatus'] = $queryStatus;
                $this->ObjView->assign("queryStatusSearch", strtoupper($queryStatus));
                $link .= 'queryStatus/' . $this->encodeUrlString($queryStatus) . '/';
            }
            if ($categoryID != '') {
                $params['categoryID'] = $categoryID;
                $this->ObjView->assign("categoryID", $categoryID);
                $link .= 'categoryID/' . $this->encodeUrlString($categoryID) . '/';
            }
            if ($sortby != '') {
                $params['sortby'] = $sortby;
                $this->ObjView->assign("sortby", $sortby);
            } else {
                $params['sortby'] = 'updated';
                $this->ObjView->assign("sortby", 'updated');
            }
            if ($orderby == 'desc') {
                $params['orderby'] = 'asc';
                $this->ObjView->assign("orderby", 'asc');
            } else {
                $params['orderby'] = 'desc';
                $this->ObjView->assign("orderby", 'desc');
            }
        }
        if (isset($_POST['changeStatus']) && !empty($_POST['checkSearchTermIDs'])) {
            $params = array(
                "languageIDs" => $languageIDs,
                "queryIDs" => $_POST['checkSearchTermIDs'],
                "queryStatus" => $_POST['changeStatus']
            );
            $ObjSearchTerm->changeStatus($params);
            if ($_POST['changeStatus'] == 'D') {
                $this->setMessage("language.msgSearchTermDeletedSuccessfully", "success");
            } else {
                $this->setMessage("language.msgSearchTermUpdatedSuccessfully", "success");
            }
            $this->setRedirect($link);
        }
        list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
        $params['limitFrom'] = $limitFrom;
        $params['limitTo']   = $limitTo;
        $listSeachTerms      = $ObjSearchTerm->listSeachTerms($params);
        $resPagesCount       = $this->setPagesCount($key = 'page');
        $resLanguages        = $ObjLanguage->listLanguages("", "Active");
        foreach ($listSeachTerms as $index => $array) {
            $insertLangs                      = explode(",", $array['tagCount']);
            $diff                             = array();
            $diff                             = array_diff($languageIDs['All'], $insertLangs);
            $listSeachTerms[$index]['addTag'] = (!empty($diff)) ? 1 : 0;
        }
        /* Fetch all Categories  having status Active and Inactive */
        $CategoryMenus = $ObjProductCategory->listProductCategories($languageIDs, -1, 'user');
        /* Iteration start to find the similar Products having same group */
        foreach ($CategoryMenus as $key => $value) {
            $categoryTree[$CategoryMenus[$key]['productCategoryParent']][] = $CategoryMenus[$key];
        }
        $categories = array_merge(array(
            array(
                '0',
                "All"
            )
        ), $categoryTree[0]);
        if ($searchFromDate == $searchToDate) {
            $this->ObjView->assign('searchDate', $searchFromDate);
        } else {
            $this->ObjView->assign('searchDate', $searchFromDate . " - " . $searchToDate);
        }
        $this->ObjView->assign("productCategories", $categories);
        $this->ObjView->assign("editPrivilage", $this->ObjCommon->hasPrivilege('catalogsearch/edit/'));
        $this->ObjView->assign("deletePrivilage", $this->ObjCommon->hasPrivilege('catalogsearch/destroy/'));
        $this->ObjView->assign("globalTagPrivilage", $this->ObjCommon->hasPrivilege('catalogtags/index/'));
        $this->ObjView->assign("page", $page);
        $this->ObjView->assign("link", $link);
        $this->ObjView->assign("resLanguages", $resLanguages);
        $this->ObjView->assign("listSeachTerms", $listSeachTerms);
        $this->ObjView->display('CatalogSearchTerms.tpl');
    }
    public function newAction() {
        $ObjSearchTerm          = new SearchTermModel();
        $ObjProductCategory     = new ProductCategoryModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        if ($this->ObjForm->isValid('formSearchTerm', 'submitSearchTerm')) {
            $params = array(
                "fields" => array(
                    'queryText' => $this->escape($_POST['queryText']),
                    'languageID' => $languageIDs['Current'],
                    'numResults' => $this->escape($_POST['numResults']),
                    'categoryID' => $this->escape($_POST['categoryID']),
                    'popularity' => $this->escape($_POST['popularity']),
                    'redirect' => $this->escape($_POST['redirect']),
                    'synonymFor' => $this->escape($_POST['synonymFor']),
                    'relatedSearchTerm' => $this->escape($_POST['relatedSearchTerm']),
                    'displayInTerms' => $this->escape($_POST['displayInTerms']),
                    'queryStatus' => $this->escape($_POST['queryStatus'])
                )
            );
            $ObjSearchTerm->insert($params);
            $this->setMessage("language.msgSearchTermAddedSuccessfully", "success");
            $this->setRedirect('catalogsearch/index/');
        }
        /* Fetch all Categories  having status Active and Inactive */
        $CategoryMenus = $ObjProductCategory->listProductCategories($languageIDs, -1, 'user');
        /* Iteration start to find the similar Products having same group */
        foreach ($CategoryMenus as $key => $value) {
            $categoryTree[$CategoryMenus[$key]['productCategoryParent']][] = $CategoryMenus[$key];
        }
        $this->ObjView->assign("productCategories", $categoryTree[0]);
        $this->ObjView->display('CatalogSearchTermsAdd.tpl');
    }
    public function editAction() {
        $queryID = $this->getRequestValue("id");
        if (!$queryID > 0) {
            $this->setRedirect('catalogsearch/index/');
        }
        $ObjSearchTerm          = new SearchTermModel();
        $ObjProductCategory     = new ProductCategoryModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $params                 = array(
            "languageIDs" => $languageIDs,
            "queryID" => $queryID
        );
        $getSeachTerms          = $ObjSearchTerm->getSeachTerms($params);
        if ($this->ObjForm->isValid('formSearchTerm', 'submitSearchTerm')) {
            $params = array(
                "set" => array(
                    "languageID='" . $languageIDs['Current'] . "'",
                    "queryText='" . $this->escape($_POST['queryText']) . "'",
                    "numResults='" . $this->escape($_POST['numResults']) . "'",
                    "popularity='" . $this->escape($_POST['popularity']) . "'",
                    "categoryID='" . $this->escape($_POST['categoryID']) . "'",
                    "redirect='" . $this->escape($_POST['redirect']) . "'",
                    "synonymFor='" . $this->escape($_POST['synonymFor']) . "'",
                    "relatedSearchTerm='" . $this->escape($_POST['relatedSearchTerm']) . "'",
                    "displayInTerms='" . $this->escape($_POST['displayInTerms']) . "'",
                    "queryStatus='" . $this->escape($_POST['queryStatus']) . "'",
                    "updatedAt='" . date('Y-m-d H:i:s') . "'"
                ),
                "queryID" => $queryID
            );
            $ObjSearchTerm->insert($params);
            $this->setMessage("language.msgSearchTermUpdatedSuccessfully", "success");
            $this->setRedirect('catalogsearch/index/');
        }
        /* Fetch all Categories  having status Active and Inactive */
        $CategoryMenus = $ObjProductCategory->listProductCategories($languageIDs, -1, 'user');
        /* Iteration start to find the similar Products having same group */
        foreach ($CategoryMenus as $key => $value) {
            $categoryTree[$CategoryMenus[$key]['productCategoryParent']][] = $CategoryMenus[$key];
        }
        $this->ObjView->assign("productCategories", $categoryTree[0]);
        $this->ObjView->assignValues($getSeachTerms);
        $this->ObjView->assign("queryID", $queryID);
        $this->ObjView->display('CatalogSearchTermsAdd.tpl');
    }
    public function destroyAction() {
        $queryID = $this->getRequestValue("id");
        if (!$queryID > 0) {
            $this->setRedirect('catalogsearch/index/');
        }
        $ObjSearchTerm          = new SearchTermModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $params                 = array(
            "languageIDs" => $languageIDs,
            "queryIDs" => array(
                $queryID
            ),
            "queryStatus" => 'D'
        );
        $ObjSearchTerm->changeStatus($params);
        $this->setMessage("language.msgSearchTermDeletedSuccessfully", "success");
        $this->setRedirect('catalogsearch/index/');
    }
    public function checkexist($data) {
        $queryText              = $data['currValue'];
        $categoryID             = $_POST['categoryID'];
        $ObjSearchTerm          = new SearchTermModel();
        $languageIDs            = $this->ObjView->languageIDs;
        $languageIDs['Current'] = $languageIDs['Content'];
        $params                 = array(
            "languageIDs" => $languageIDs,
            "queryText" => $queryText,
            "categoryID" => $categoryID,
            "queryID" => isset($_POST['queryID']) ? $_POST['queryID'] : ''
        );
        return !$ObjSearchTerm->checkKeywordExist($params);
    }
}