<?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: productController.php, v 1.2 2013/04/25 20:52:11
//
class ProductController extends Controller {
    public function indexAction() {
        echo 'api product';
    }
    public function ajaxListAction() {
        $ObjBrand               = new BrandModel();
        $languageIDs['Current'] = $_POST['lan'];
        $productType            = isset($_POST['producttype']) ? $_POST['producttype'] : '';
        $page                   = $_POST['page'];
        $categoryID             = '';//isset($_POST['categoryID']) ? $_POST['categoryID'] : '';
        $customOrderBy          = $_POST['sortBy'];
        $searchKeyword          = json_decode($_POST['keyword'], TRUE);
        $attrQueryStringArray   = array();
        $uniqueID               = $_POST['uniqueID'];
        $originCatalogID        = isset($_POST['parentCategoryID']) ? $_POST['parentCategoryID'] : '';
        $businessID                = isset($_POST['businessID']) ? $_POST['businessID'] : '';
        $brandID                = isset($_POST['brandID']) ? $_POST['brandID'] : '';
        $brandIDs               = isset($_POST['brandIDs']) ? $_POST['brandIDs'] : array();
	$isDeal                 = isset($_POST['isDeal']) ? $_POST['isDeal'] : '';
        $urlCat                = isset($_POST['urlCat']) ? $_POST['urlCat'] : '';
        $urlBodyStyle           = isset($_POST['urlBodyStyle']) ? $_POST['urlBodyStyle'] : '';
        $attributeArray         = array();
        $custCode               = array();
        $ckey                   = isset($_POST['ckey']) ? $_POST['ckey'] : '';
        
        if (!empty($_POST['categoryID'])) {
            foreach ($_POST['categoryID'] as $catdet) {
                $catArray[] = $catdet['option'];              
            }
            $categoryIDs = $catArray;
        }
        
        if (isset($_POST['attrDataObj']) && $_POST['attrDataObj'] != '') {
            $bodyStyle  =array();
            foreach ($_POST['attrDataObj'] as $attributes) {                
                //$attributeArray[$attributes['attribute']][] = $attributes['option'];
                $bodyStyle[]= $attributes['option'];                
            }       
            $_POST['bodyStyle'] = $bodyStyle;
        }
        if (isset($_POST['custDataObj']) && $_POST['custDataObj'] != '') {
            
            foreach ($_POST['custDataObj'] as $cust) {                
                //$attributeArray[$attributes['attribute']][] = $attributes['option'];
                $custCode[]= $cust['option'];                
            }       
            $_POST['custCode'] = $custCode;
        }
       // echo "<pre>";print_r($_POST['bodyStyle']);exit;
        $bodyStyle              = isset($_POST['bodyStyle']) ? $_POST['bodyStyle'] : '';
        $custCode               = isset($_POST['custCode']) ? $_POST['custCode'] : '';
        $bmwCode                = isset($_POST['bmwCode']) ? $_POST['bmwCode'] : '';
        //$catKey                 = isset($_POST['bmwCode']) ? $_POST['bmwCode'] : '';
        
        //$brandKey = 'bmw';
		$brandKey = FRANCHISEE;
        $paramsbrand            = array(
                'languageIDs' => $languageIDs,
                'brandKey' => $brandKey
            );
            $brandInfo         = $ObjBrand->getBrand($paramsbrand);
        if($brandInfo['brandID']>0) {
                //get Subbrands if any
                $getSub = $ObjBrand->getSubBrandIDs($brandInfo['brandID']);                
                $brandIDs = $brandInfo['brandID'];
                if(!empty($getSub) && !empty($getSub['brandIDs'])) {
                    $brandIDs .= ",".$getSub['brandIDs'];
                }
            }    
       
        $resProducts            = array();
        if ($languageIDs['Current'] == '') {
            exit;
        }
        $ObjProductList     = new ProductListModel();
        $ObjProduct         = new ProductModel();
        $ObjCustomOption    = new CustomOptionModel();
        $ObjCategory        = new ProductCategoryModel();
        $catKey = '';
        if($categoryID > 0) {
                $selCategoryDet        = $ObjCategory->getCategoryInfo($languageIDs, $categoryID, '', 'productCategoryID');
                $catKey = $selCategoryDet['productCategoryKey'];
        }
        $productType        = array(
            'productTypeID' => 1,
            'productTypeKey' => 'product_product',
            'productTypeUrlKey' => '',
            'isFeatured' => 1,
            'limitMainListing' => '',
            'limitDefListing' => '',
            'productTypeName' => $this->getLanguageValue('lblProducts')
        );
        $product_list_count = trim($this->getSettingValue('product_cart_settings', 'product_list_count'));
        if ($product_list_count == '') {
            exit;
        } 
        if($isDeal=='Yes'){
		$args              = array(
            'requestedBy' => 'customer',
            'requestPage' => 'category_prod_listing',
            'limitFrom' => $page * $product_list_count,
            'limitTo' => $product_list_count,
            'languageIDs' => $languageIDs,
            'productType' => $productType,
			'isProductDeal' => 'Yes',
            'customOrderBy' => $customOrderBy,
			'attrDataObj' => (isset($_POST['attrDataObj']) ? $_POST['attrDataObj'] : array()),
            'attrQueryStringArray' => $attrQueryStringArray,
            'userGroupID' => $_POST['userGroupID']	
		);
		}
		else {
                    $customGroupBy = (empty($categoryIDs) || $categoryIDs<=0)?'bodyStyle':'';
                    $showDet    = '';
                    $listLevel  = 1;  
                    if(!empty($categoryIDs) && !empty($bodyStyle)) {
                        $customGroupBy = 'bmwCode';
                        $listLevel  = 2; 
                        //$showLst       = 2;
                    } elseif(!empty($categoryIDs)) {
                        $customGroupBy = 'bmwCode';
                        $listLevel  = 2; 
                    }
                    if(!empty($bmwCode)) {
                        $listLevel  = 3; 
                        $customGroupBy = '';
                    }
           
                     
        $args              = array(
            'requestedBy' => 'customer',
            'requestPage' => 'category_prod_listing',
            'limitFrom' => $page * $product_list_count,
            'limitTo' => $product_list_count,
            'languageIDs' => $languageIDs,
            'productType' => $productType,
            'categoryIDs' => $categoryIDs,
            'brandID' => 0,
            'businessID' => $businessID,
            'brandIDs' => $brandIDs,
            'customOrderBy' => $customOrderBy,
            'searchKeyword' => $searchKeyword,
            'attrDataObj' => array(),
            'priceRangeMin' => $_POST['priceRangeMin'],
            'priceRangeMax' => $_POST['priceRangeMax'],
            'discountRange' => $_POST['discountRange'],
            'attrQueryStringArray' => '',
            'userGroupID' => $_POST['userGroupID'],
            'apilisting'  => 'listing',
            'customGroupBy'=>$customGroupBy,
            'bodyStyle'=>$bodyStyle,
            'bmwCode'=>$bmwCode,
            'custom'=>'Yes',
            'custCode'=>$custCode
        );
		} 
        $resAllProducts    = $ObjProductList->listActiveProducts($args);
        $sefProductIDArray = array();
        foreach ($resAllProducts as $key => $resProduct) {
            $sefProductIDArray[] = $resProduct['productID'];
        }
        $custOptionDet       = array();
        $custOptionName      = array();
        $custOptionNameValue = array();
        $labelvalue          = array();
        $bodyStyles          = array();
        $typeArr             = '';
        $incust              =  0;
        $keyb                =  0;
        $incustopt           =  0;
        if (count($sefProductIDArray) > 0)
            $this->ObjCommon->setCommonSefPath(array(
                'product'
            ), $sefProductIDArray);
        foreach ($resAllProducts as $key => $resProduct) {
            $resProduct['uniqueID']  = $uniqueID;
            $currProdID              = $resProduct['productID'];
            $productOptionID         = $resProduct['productOptionID'];
            $resProduct['freeProductsCount'] = ($resProduct['freeProductsCount']>0) ? $resProduct['freeProductsCount']:0;
               
            /* START : to get the minimum tier price */
            $params                  = array(
                'productOptionID' => $productOptionID,
                'userGroupID' => isset($this->ObjCommon->REGISTERED_USER_GROUP_ID) ? ((int) $this->ObjCommon->REGISTERED_USER_GROUP_ID) : 0
            );
            if(empty($bodyStyles) || (!empty($bodyStyles) && !in_array($resProduct['bodyStyle'], $bodyStyles))) {
                $bodyStyles[$keyb] = $resProduct['bodyStyle'];
                $typeArr           = ($typeArr=='')?$resProduct['bodyStyle']:$typeArr."~".$resProduct['bodyStyle'];
                $keyb = $keyb +1;
            }
            //$prodCatID                        = $categoryID;
            if(empty($categoryIDs) && $resProduct['productCategoryID']>0) {
                $prodCatID              =  $resProduct['productCategoryID'];
            }
            //get category key
            $catKey  = $resProduct['productCategoryKey'];//$ObjProductList->getCategoryIdByProductId($prodCatID,'Yes');
            $catName = $resProduct['productCategoryName'];
            $resProduct['catKey']  = $catKey;
            $resProduct['catName'] = $catName;
            $resProduct['listLevel'] = $listLevel;
            $resProduct['showCatBg'] = '';
            $prodBmwCode                      = $resProduct['bmwCode'];
            $resProduct['bmwCode']            = $resProduct['custbmwcode'];
            $resProduct['custbmwcode']        = $prodBmwCode;
            //if($key<=0) {
            if($ckey!=$resProduct['catKey']) {
                $catBgName             = $resProduct['catName'];          
                if($catBgName!='') {
                    $catBgName         = str_replace('BMW', '', $catBgName);
                    $catBgName         = str_replace('Series', '', $catBgName);   
                    $catBgName         = str_replace('-', '', $catBgName);   
                }
                $resProduct['showCatBg']  = $catBgName;
            }  
            
            $ckey = $resProduct['catKey'];
            //}
            /* END : to get the minimum tier price */
            $args                    = array(
                'productID' => $currProdID
            );
            $this->ObjView->assign('toAppend', 'Yes');
            //request URl
            
            $resProduct['listLevel']         = $listLevel;
            $resProduct['body-type']         = $bodyStyle;
            $resProduct['bw-code']           = $bmwCode;

            /* function call for Product option count */
            $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);
                }
            } 
            $resProduct['productDescription'] = strip_tags(html_entity_decode($resProduct['productDescription']));
            if ($resProduct['productEndTime'] != '0000-00-00') {
                $seconds                = strtotime($resProduct['productEndTime']) - strtotime($resProduct['timeZoneConverted']);
                $resProduct['daysLeft'] = ceil($seconds / 3600 / 24);
            }
            $settingsAllowProductReviews = $this->getSettingValue('product_cart_settings', 'allow_product_reviews');
            if ($settingsAllowProductReviews == 'Yes') {
                $prodReviews = $ObjProductList->fetchProductReviews($currProdID);
                $resProduct  = array_merge($resProduct, $prodReviews);
            }
            if($listLevel==3) {
                $resProduct['showTitle']    = $brandInfo['brandName']." ".$resProduct['productTitle']." (".$resProduct['modelYear'].")";
                $resProduct['requestPath']  = $this->ObjView->getSefRequestPath($currProdID, 'product', $originCatalogID);
            } else {
                if($listLevel==1) {
                    if(strtolower($resProduct['bodyStyle'])=='off road') {
                        $resProduct['showTitle']    = $brandInfo['brandName']." ".$resProduct['catName'];
                    } else {
                        $resProduct['showTitle']    = $brandInfo['brandName']." ".$resProduct['catName']." ".$resProduct['bodyStyle'];
                    }
                } else {
                    $resProduct['showTitle']    = $brandInfo['brandName']." ".$resProduct['productShortDescription'];
                }
                if(empty($resProduct['showTitle'])) {
                    $resProduct['showTitle']    = $brandInfo['brandName']." ".$resProduct['productTitle'];
                }
                $resProduct['requestPath']      = (strtolower($resProduct['bodyStyle'])=='off road')?"series/".$resProduct['catKey']."/":"series/".$resProduct['catKey']."/".$resProduct['bodyStyle']."/";
                $bodystyleparam                 = $resProduct['bodyStyle'];//(!empty($urlBodyStyle))?$urlBodyStyle:$resProduct['bodyStyle'];
                if($listLevel==2) {
                    $catparam                 = $resProduct['catKey'];//(!empty($urlCat))?$urlCat:$resProduct['catKey'];
                    /*if(!empty($bodyStyle)) {
                        $resProduct['requestPath']      = "series/".$resProduct['catKey']."/".$bodyStyle."/code/".$resProduct['bmwCode']."/";
                    } else {
                        $resProduct['requestPath']      = "series/".$resProduct['catKey']."/".$resProduct['bodyStyle']."/code/".$resProduct['bmwCode']."/";
                    }*/
                    $resProduct['requestPath']      = (strtolower($bodystyleparam=='off road'))?"series/".$catparam."/code/".$resProduct['bmwCode']."/":"series/".$catparam."/".$bodystyleparam."/code/".$resProduct['bmwCode']."/";
                } else {
                    $resProduct['requestPath']      = (strtolower($bodystyleparam=='off road'))?"series/".$resProduct['catKey']."/":"series/".$resProduct['catKey']."/".$bodystyleparam."/";
                }
                 
            }
            
            $customOptionValues = $ObjCustomOption->getProductCustomOptionsCount($currProdID,'Yes',$languageIDs);
            if(!empty($customOptionValues)) {
                
                foreach($customOptionValues as $det) {
                    if(empty($custOptionName) || (!empty($custOptionName) && !in_array($det['customOptionName'],$custOptionName))) {
                        //$custOptionDet[$det['customOptionName']]   =   $det['customOptionName'];
                        $custOptionName[$incust]                   =   $det['customOptionName'];
                        $custName                                  =   empty($custName) ? $det['customOptionName']:$custName."~".$det['customOptionName'];
                        $incust = $incust + 1;
                    }
                    
                    $getOptions                                     =   $ObjCustomOption->getCustomOptionVariants($languageIDs,$det['customOptionID']);
                    if(!empty($getOptions)) {
                        foreach($getOptions as $keyopt=>$optdet) {
                           
                            if(empty($custOptionNameValue) || (!empty($custOptionNameValue) && !in_array($optdet['value'],$custOptionNameValue))) {
                                //$custOptionDet[$det['customOptionName']][$incustopt][0]   =   $optdet['value'];
                                //$custOptionDet[$det['customOptionName']][$incustopt][1]   =   $optdet['variantCode'];
                                $custOptionNameValue[$incustopt]                          =   $optdet['value'];
                                /*$label                                                    = '<li>        
                                                                                            <input type="checkbox" disabled="" refinehead="'.$det['customOptionName'].'" refineval="'.$det['customOptionName'].'" id="searchCustOptID_'.$det['customOptionName'].'" rel="'.$det['customOptionName'].'" name="searchCustOptID_'.$det['customOptionName'].'[]" value="'.$optdet['variantCode'].'" class="searchCustOptID_'.$det['customOptionName'].'"> 
                                                                                            <label class="attributeSearchLabel" disabled="" id="searchCustLabel_'.$det['customOptionName'].'" for="searchCustOptID_'.$det['customOptionName'].'">'.$optdet['value'].'</label>
                                                                                         </li>';*/
                                $label                                                    = $optdet['variantCode']."|".$optdet['value']."|".$optdet['variantThumbImage'];
                                $labelvalue[$det['customOptionName']]                     = empty($labelvalue[$det['customOptionName']]) ? $label:$labelvalue[$det['customOptionName']]."~".$label;
                                $custOptionDet[$det['customOptionName']]                  = $labelvalue[$det['customOptionName']];
                                $incustopt = $incustopt+1;
                               
                            }
                        }
                    }
                }
            }
            $resProduct['customOptionCount'] = $customOptionValues;
            
            $resProduct['currentCurrencyID']= $this->ObjCommon->_currentcurrency;
            $resProduct['custOptionVals']   = $custOptionDet;
            $resProduct['bodyStyles']       = $typeArr;
            $resProduct['custName']         = $custName;
            $resProducts[] = $resProduct;
        }        
        echo json_encode($resProducts);
        exit;
    }
}
