<?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: AjaxController.php, v 1.0 2011/06/14 20:52:11
//
class AjaxController extends Controller {
    public function __construct() {
        $this->init();
    }
    //DISPLAY STATES USING AJAX
    public function statesAjaxAction() {
        $countryID   = $_POST['countryID'];
        $objAjax     = new StateModel();
        $languageIDs = $this->ObjView->languageIDs;
        $statesList  = $objAjax->listAjaxStates($languageIDs, $countryID);
        $this->ObjView->assign('statesList', $statesList);
        $this->ObjView->display('statesAjax.tpl');
    }
    //END OF FUNCTION
    //AJAX ACTION FOR CATALOG LINK GENERATION
    public function generateCatalogLinkAction() {
        $ObjProductCategory      = new ProductCategoryModel();
        $ObjBrand                = new BrandModel();
		$ObjBusiness             = new BusinessModel();
        $ObjProductList          = new ProductListModel();
        $languageIDs             = $this->ObjView->languageIDs;
        $importDomElementEnabled = 0;
        //For binding URL to a DOM Element From Parent
        if ($_GET["id"]) {
            $importDomElement        = $_GET["id"];
            $importDomElementType    = "id";
            $importDomElementEnabled = 1;
        } elseif ($_GET["class"]) {
            $importDomElement        = $_GET["class"];
            $importDomElementType    = "class";
            $importDomElementEnabled = 1;
        }
        $resCategories = $ObjProductCategory->listProductCategoryItems($languageIDs, 0, '', '', 'user');
        if (is_array($resCategories)) {
            array_shift($resCategories);
        }
        $listBrand = $ObjBrand->listBrand(array(
            'languageIDs' => $languageIDs
        ));
		
		$resBusiness               = $ObjBusiness->listBusinessInOptions($languageIDs);
		  //echo"<pre>";print_r($resBusiness);exit;
        $this->ObjView->assign("listBrand", $listBrand);
		$this->ObjView->assign('resBusiness', $resBusiness);
        $this->ObjView->assign("importDomElementEnabled", $importDomElementEnabled);
        $this->ObjView->assign("importDomElement", $importDomElement);
        $this->ObjView->assign("importDomElementType", $importDomElementType);
        $this->ObjView->assign("resCategories", $resCategories);
        $this->ObjView->assign('listDiscountSchema', $ObjProductList->listDiscountSchema());
        $this->ObjView->assign('catalogUrlSeperatorSchema', json_encode($ObjProductList->getCatalogUrlSeperatorSchema()));
        $this->ObjView->assign('itemType',(isset($_GET["itemID"])) ? 'menuitem' : 0);
        $this->ObjView->assign('siteUrl', rtrim($this->getSettingValue('site_settings', 'global_http_url'), "/"));
        $this->ObjView->display('AjaxGenerateCatalogLink.tpl');
    }
    //AJAX ACTION FOR LISTING ATTRIBUTES
    public function listAttributesAction() {
        echo json_encode($this->listAttributesForOption());
    }
    //Generate Attribute Array
    private function listAttributesForOption() {
        $ObjAttribute   = new AttributeModel();
        $languageIDs    = $this->ObjView->languageIDs;
        $params         = array(
            'isFilterable' => "Yes"
        );
        $resAttributes  = $ObjAttribute->listAttributesWithOptions($languageIDs, $params);
        $i              = 0;
        $attrCheckArray = array();
        foreach ($resAttributes as $attributes) {
            if ($attributes['attrOptionID'] > 0)
                $attrOptionArray[$attributes['attributeID']][$attributes['attrOptionID']] = $attributes['attrOptName'];
            if (in_array($attributes['attributeID'], $attrCheckArray))
                continue;
            $attrCheckArray[]                    = $attributes['attributeID'];
            $attributeArray[$i]['attributeID']   = $attributes['attributeID'];
            $attributeArray[$i]['attrName']      = $attributes['attrName'] . "[ " . $attributes['attributeKey'] . " ]";
            $attributeArray[$i]['attrInputType'] = $attributes['attrInputType'];
            $attributeArray[$i]['attributeKey']  = $attributes['attributeKey'];
            $i++;
        }
        $attrData['attributeArray']  = $attributeArray;
        $attrData['attrOptionArray'] = $attrOptionArray;
        return $attrData;
    }
    public function productpriorityAction()
    {
        $menuItemID =   $this->getRequestValue("itemID");//(isset($_GET["itemID"])) ?$_GET["itemID"] : 0;
        $ObjCustomMenu = new CustommenuModel();        
        if(isset($_POST['data'])){
         $data_list				= 	json_decode($_POST['data'], true);  
         if($data_list['task']=='setpriority' && count($data_list['products'])>0 ){
             $params['menuItemID']  = $menuItemID;
             $params['products']  = $data_list['products'];
             $ObjCustomMenu->setProductPriorityForItem($params);
             $this->setMessage( "language.msgPriorityUpdated", "success" );
             echo 1;exit;
         }
        }
        $this->ObjView->assign('itemID', $menuItemID);
        if($menuItemID>0){
           
           $itemlink     =      $ObjCustomMenu->getPathByItem($menuItemID,'','target','productfilterurl');
           $this->set_vars($itemlink);
           $this->queryString  	= explode('/',$itemlink);
           $ObjProductList          = new ProductListModel();
           // params 
           $category              	 = $this->getParamValue("id");
           $brand                   = $this->getParamValue("brand");           
           $menuItemID              = $this->getParamValue("itemID");
           $personalizable          = $this->getParamValue("personalizable");
           $newarrival              = $this->getParamValue("newarrival");
            
        $brandID                 = isset($brandID) ? $brandID : 0;
        $isDeals                 =  0;
       	 /* START : Query String */
        $categoryIDs = $brandIDs = $teamIDs = array();
                if($category!=''){
                    if(!is_numeric($category)){
                        if(strpos($category, ":")>=0){
                            $categoryIDs = explode(":",$category);

                        }
                        else{
                            $ObjCategory		= 	new ProductCategoryModel();
                            $getCategoryInfo 	= 	$ObjCategory->getCategoryInfo($language_ids,0,$category);
                            if(!empty($getCategoryInfo)){
                                $categoryIDs		=	array($getCategoryInfo['productCategoryID']);
                            }
                        }
                    }else{
                        $categoryIDs = array($category);
                    }
                }
                if($brand!=''){
                    if(!is_numeric($brand)){
                        if(strpos($brand, ":")>=0){
                            $brandIDs = explode(":",$brand);

                        }else{
                            $ObjBrand		= new BrandModel();
                            $args=array(
                                'language_ids'=>$language_ids,
                                'brandKey'	=>$brand,
                            );
                            $getBrand 	= 	$ObjBrand->getBrand($args);
                            if(!empty($getBrand)){
                                $brandIDs 	= 	array($getBrand['brandID']);
                            }
                        }

                    }else{
                        $brandIDs = array($brand);
                    }
                }

                
        $searchString   = isset($_GET) ? $_GET : '';
        if (!empty($searchString)) {
            unset($searchString['q']);
        }
        $attrQueryStringArray = array();
        $discountQueryString  = '';
        $priceMinQueryString  = '';
        $priceMaxQueryString  = '';
        $queryStringMode      = 0;
        if (!empty($searchString)) {
            $catalogUrlSeperatorSchema = $ObjProductList->getCatalogUrlSeperatorSchema();
            //Price
            if (isset($searchString['price'])) {
                $priceRange = explode($catalogUrlSeperatorSchema['price'], $searchString['price']);
                if ($priceRange[0] >= 0 && $priceRange[1] > 0 && $priceRange[0] <= $priceRange[1]) {
                    $priceMinQueryString = $priceRange[0];
                    $priceMaxQueryString = $priceRange[1];
                    $queryStringMode++;
                }
            }
            //Discount
            $discountArray = array_keys($ObjProductList->listDiscountSchema());
            if (isset($searchString['discount']) && $searchString['discount'] && in_array($searchString['discount'], $discountArray)) {
                $discountQueryString = $searchString['discount'];
                $queryStringMode++;
            }
            //Attributes			
            if (isset($searchString['search'])) {
                $attrArray = explode($catalogUrlSeperatorSchema['attributes'], $searchString['search']);
                foreach ($attrArray as $attrRes) {
                    if ($attrRes) {
                        //Attribute - Attribute Options
                        $attrName = explode($catalogUrlSeperatorSchema['attribute'], $attrRes);
                        //$attrName[0] => Attribute Key ; $attrName[1] => Attribute Option
                        if ($attrName[1]) {
                            $attrOptions = explode($catalogUrlSeperatorSchema['attrOption'], $attrName[1]);
                            if ($attrOptions && $attrName[0]) {
                                $attrOptionIds = '';
                                foreach ($attrOptions as $attrOptionRes) {
                                    $attrOptionIdRes = explode($catalogUrlSeperatorSchema['attr_option_id'], $attrOptionRes);
                                    //Attribute OptionID
                                    $attrOptionIds[] = $attrOptionIdRes[1];
                                }
                                $attrQueryStringArray[$attrName[0]] = $attrOptionIds;
                            }
                        }
                    }
                }
                if (!empty($attrQueryStringArray))
                    $queryStringMode++;
            }
        }
        $productType              = array(
                    'productTypeID' => 1,
                    'productTypeKey' => 'product_product',
                    'productTypeName' => $this->getLanguageValue('lblProducts')
                );
         $default_catalog_listing     = $this->getSettingValue('product_cart_settings', 'default_catalog_listing');
        if(isset($_GET['sortby']) && $_GET['sortby']!='')
            $default_catalog_listing = $_GET['sortby'];
            $args                    = array(
            'languageIDs' => $this->ObjView->languageIDs,
            'brandIDs' =>  isset($brandIDs) && !empty($brandIDs)  ? $brandIDs : array(),
            'categoryIDs' =>  isset($categoryIDs) && !empty($categoryIDs)  ? $categoryIDs : array(),
            'categoryID' => $category,
            'productType'=>$productType,
            'customOrderBy' =>  '',
            'searchKeyword' => array(),
            'attrDataObj' => array(),
            'priceRangeMin' => $priceMinQueryString,
            'priceRangeMax' => $priceMaxQueryString,
            'discountRange' => $discountQueryString,
            'userGroupID' => 0,
            'attrQueryStringArray' => $attrQueryStringArray,
            'menuItemID' => $menuItemID
        );        
        $resAllProducts = $ObjProductList->listActiveProducts($args);
        $this->ObjView->assign('resAllProducts', $resAllProducts);
        
        }
        $this->ObjView->display('AjaxProductPriority.tpl'); 	
    }
    //To get the value of the query string from the url
    public function getParamValue($queryStringKey=0)  
    {		
        $queryString  =$this->queryString;
        $queryStringKeyNumber = (array_search($queryStringKey, $queryString)+1);
        return ($queryStringKeyNumber>1)?trim($queryString[$queryStringKeyNumber]):"";		
    }
    public function set_vars($target_path){
        if(strpos($target_path, "?") !== false){
            $target_path = explode("?", $target_path);
            $addQryStrng = htmlspecialchars_decode($target_path[1]);
                if($addQryStrng!='/'){
                    $get_array = explode("&",rtrim($addQryStrng,'?'));
                    foreach($get_array as $full_param){
                        $params = explode("=", $full_param);
                        $_GET[$params[0]] = (!empty($params[1])) ? $params[1] : '';
                    }
                }
        }
    } 
}