Subversion Repositories SmartDukaan

Rev

Rev 18207 | Rev 18223 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

<?php
App::uses('AppController', 'Controller');
/**
 * Categories Controller
 *
 * @property Category $Category
 * @property PaginatorComponent $Paginator
 */
class CategoriesController extends AppController {

/**
 * Components
 *
 * @var array
 */
        public $components = array('Paginator');
        public $apihost;
        public $limit;

        public function beforeFilter() {
                parent::beforeFilter();
                $this->Auth->allow('deals');
                $this->apihost = Configure::read('pythonapihost');
                $this->limit = Configure::read('dealsperpage');
        }

/**
 * index method
 *
 * @return void
 */
        public function index() {
                // $this->Category->recursive = 0;
                // $this->set('categories', $this->Paginator->paginate());
                $userId = $this->request->query('user_id');
                $this->loadModel('UserCategory');
                $options = array('conditions' => array('user_id'=>$userId),'order'=>array('rank','asc'),'recursive'=>-1);
                $userCategories = $this->UserCategory->find('all',$options);            
                $this->response->type('json');
                $this->layout = 'ajax';
                $conditions = array(array('Category.parent_id !='=>0));
                if(!empty($userCategories)){
                        foreach ($userCategories as $key => $value) {
                                $categoryIds[] = $value['UserCategory']['category_id'];
                        }
                        array_push($conditions,array('Category.id'=>$categoryIds));
                }
                $this->Category->recursive = -1;                
                $categories = $this->Paginator->paginate(null,$conditions);
                $callback = $this->request->query('callback');
                $result = array('categories' => $categories);
                $this->set(array(
                    'result' => $result,
                    'callback' => $callback,
                    '_serialize' => array('result')
                ));
                $this->render('/Elements/jsonp');
        }

        public function deals(){
                $userId = $this->request->query('user_id');
                $error = $this->request->query('error');
                if(isset($userId) && !empty($userId)){
                        $this->loadModel('User');
                        $dbuser = $this->User->findById($userId);
                        $this->Auth->login($dbuser['User']);    
                }
                $likedDeals = $disLikedDeals = array();
                // $this->loadModel('Api');
                // $apideals = $this->Api->getCategoryDeals($this->Auth->User('id'),1);
                // $categorydeals = $apideals['products'];
                $page = $this->request->query('page');
                if(!isset($page)){
                        $page = 1;
                }
                $offset = ($page - 1) * $this->limit;
                $url = $this->apihost.'deals/'.$this->Auth->User('id').'?categoryId=0&limit='.$this->limit.'&offset='.$offset;
                //debug($url);
                $deals = $this->make_request($url,null);                
                $myactions = $this->Api->getMyActions($this->Auth->User('id'));         
                if(!empty($myactions)) {
                        foreach ($myactions['actions'] as $key => $value) {
                                if($value['UserAction']['action'] == 'like'){
                                        $likedDeals[$value['UserAction']['store_product_id']] = $value['UserAction']['id'];
                                }else{
                                        $disLikedDeals[$value['UserAction']['store_product_id']] = $value['UserAction']['id'];
                                }
                        }
                }
                
                $errorstr = '';
                                
                if(isset($error)){
                        $errorstr = 'Oops!! Some Error Occured. <br> Please try after Some Time';
                }
                $rows = sizeof($categorydeals);
                if($rows>=1){
                        $this->set('deals',$categorydeals);
                        $this->set('likedDeals',$likedDeals);
                        $this->set('disLikedDeals',$disLikedDeals);
                        $this->set('errorstr',$errorstr);
                        $this->render('categorydeals');
                }else{
                        foreach ($categorydeals as $key => $dealarr) {
                                foreach ($dealarr as $key => $deal) {
                                        $deals[] = $deal[0];
                                }                               
                        }
                        $this->set(compact('deals','likedDeals','disLikedDeals','errorstr'));
                }               
        }
/*
        *
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function view($id = null) {
                $searchableSubCategories = array('20'=>'Tempered Glasses', '19^27'=>'Mobile Covers');
                $userId = $this->request->query('user_id');
                
                if(isset($userId) && !empty($userId)) {
                        $this->loadModel('User');
                        $dbuser = $this->User->findById($userId);
                        $this->Auth->login($dbuser['User']);
                }                               
                $page = $this->request->query('page');
                $searchfor = $this->request->query('searchFor');
                // echo "page=>",$page;
                $error = $this->request->query('error');
                if(!isset($page)){
                        $page = 1;
                }

                $sort = $this->request->query('sort');
                $direction = $this->request->query('direction');
                //$filter = $this->request->query('filter');
                // $brands = $this->request->query('brands');
                if($id != 2) {
                        //Fetch deals
                        $likedDeals = $disLikedDeals = array();
                        $brandschosen = $_COOKIE['brandschosen'];
                        $subcategorieschosen = $_COOKIE['subcategorieschosen'];                 
                        
                        // echo "Cookie val", $_COOKIE['old_id'];
                        // echo "id val", $id;

                        if(!empty($searchfor) || $searchfor != null)
                        {
                                unset($brandschosen);
                                setcookie('brandschosen', null, -1, '/');
                                unset($subcategorieschosen);
                                setcookie('subcategorieschosen', null, -1, '/');
                        }

                        if((isset($_COOKIE['old_cid'])) && ($_COOKIE['old_cid'] != $id)) {

                                
                                unset($brandschosen);
                                // setcookie('brandschosen', 1, time()-1, '/');
                                // unset($_COOKIE['brandschosen']);
                        setcookie('brandschosen', null, -1, '/');
                                unset($subcategorieschosen);
                                setcookie('subcategorieschosen', 1, time()-1, '/');
                                
                        }               

                        if((isset($_COOKIE['brandschosen'])) && ($_COOKIE['old_cid'] != $id)) {
                                
                                unset($brandschosen);
                                // setcookie('brandschosen', 1, time()-10, '/');
                                // unset($_COOKIE['brandschosen']);
                        setcookie('brandschosen', null, -1, '/');
                                unset($subcategorieschosen);
                                setcookie('subcategorieschosen', 1, time()-1, '/');
                                
                        }

                        setcookie('old_cid', $id, -1, '/');
                        
                        
                                if(!empty($brandschosen) && !empty($subcategorieschosen)){
                                        $filter = 'brand|subcategory';
                                }                       
                                else if(!empty($brandschosen) && empty($subcategorieschosen)){
                                        $filter = 'brand';
                                }
                                if(!empty($subcategorieschosen) && empty($brandschosen)){
                                        $filter = 'subcategory';
                                }
                        
                        $brands = str_replace(',', '^', $brandschosen);
                        $subcategories = str_replace(',', '^', $subcategorieschosen);
                        $url = $this->getDealsApiUrl($page,$this->Auth->User('id'),$id,$sort,$direction,$filter,$brands,$subcategories);
                        // $url = $this->apihost.'deals/'.$this->Auth->User('id').'?categoryId='.$id;
                        $response = $this->make_request($url,null);
                        $deals = array();
                        
                        $response_count =1;
                        if($response == '')
                        {
                                $response_count = 0;
                        }
                        // debug($response_count);
                        if(!empty($response)){
                                foreach ($response as $key => $value) {
                                        if(!empty($value)){
                                                $deals[] = $value;
                                        }
                                }
                        }
                        #print_r($deals);
                        $this->loadModel('Api');
                        $myactions = $this->Api->getMyActions($this->Auth->User('id'));
                        if(!empty($myactions)) {
                                foreach ($myactions['actions'] as $key => $value) {
                                        if($value['UserAction']['action'] == 'like'){
                                                $likedDeals[$value['UserAction']['store_product_id']] = $value['UserAction']['id'];
                                        }else{
                                                $disLikedDeals[$value['UserAction']['store_product_id']] = $value['UserAction']['id'];
                                        }
                                }
                        }
                        $this->loadModel('NotificationRule');
                        $notification = $this->NotificationRule->getNotification($this->Auth->User('id'));      
                    $filterstr = '';
                        if(isset($filter) && !empty($filter)){
                                
                            $filterstr = '&filter='.$filter.'&brands='.$brands.'&subcategories='.$subcategories;
                        } 


                        $get_url = "'".$_SERVER['REQUEST_URI']."'";
                        $urlArray = explode('=',$_SERVER['REQUEST_URI']);
                        $last = $urlArray[sizeof($urlArray)-1];
                        
                        // <Code for url used after scrolling...>
                        if(!isset($filter) && empty($filter)){
                                if (strpos($get_url,'filter=brand&brands') !== false)
                                {
                                        $filterstr= "&filter=brand&brands=".$last;
                                }
                                if (strpos($get_url,'filter=subcategory&subcategories') !== false)
                                {
                                        $filterstr= "&filter=subcategory&subcategories=".$last;
                                }

                        }

                  
                        if(!empty($subcategorieschosen) && isset($subcategorieschosen) && empty($brandschosen) && !isset($brandschosen)){       
                                        $filterstr= "&filter=subcategory&subcategories=".$subcategorieschosen;                          
                        }
                        
                        $errorstr = '';
                        
                        if(isset($error)){
                                $errorstr = 'Oops!! Some Error Occured. <br> Please try after Some Time';
                        }

                        
                        $nexturl = "/categories/getdeals/".$id."/?page=".($page+1)."&sort=".$sort."&direction=".$direction."".$filterstr;                       
                        $this->set(compact('response_count','deals','id','likedDeals','disLikedDeals','page','sort','direction','notification','filter','brands','filterstr','brandschosen','subcategories','subcategorieschosen','errorstr','nexturl','searchfor', 'searchableSubCategories'));
                }else{
                        //Check for apk support of sharing
                        $sharable = 0;
                        if(isset($_COOKIE['shareApps']) && !empty($_COOKIE['shareApps'])) {
                                $sharable = 1;
                        }                       
                        $url = $this->apihost."appOffers/1";
                        $appOffers = $this->make_request($url,null);
                        $this->set(compact('page','id','sharable','appOffers'));
                        $this->render('viewapps');
                }
        }

        public function getapps($id=null){
                $this->layout = 'ajax';
                $page = $this->request->query('page');
                if(!isset($page)){
                        $page = 1;
                }
                $this->loadModel('AppOffer');
                $this->AppOffer->recursive = -1;
                $options = array('conditions'=>array('offer_active'=>1,'show'=>1),'limit' => Configure::read('searchresultsperpage'),'page'=>$page);
                $this->Paginator->settings = $options;
                try{
                        $appOffers = $this->Paginator->paginate('AppOffer');
                } catch (NotFoundException $e) {
                //get current page
                $page = $this->request->params['named']['page'];
                $appOffers = array();   
                }
                debug($appOffers);              
                if(!empty($appOffers)){
                        $this->set(compact('page','id','appOffers'));
                        $this->render('/Elements/appoffers');
                }else{
                        $this->render('/Elements/nooffers');
                }               
        }

        public function getdeals($id = null) {
        
                $this->log('getdeal id '.$id,'api');
                $likedDeals = $disLikedDeals = array();
                $this->layout = 'ajax';
                $page = $this->request->query('page');
                if(!isset($page)){
                        $page = 1;
                }
                $sort = $this->request->query('sort');
                $direction = $this->request->query('direction');
                // $filter = $this->request->query('filter');
                // $brands = $this->request->query('brands');
                $brandschosen = $_COOKIE['brandschosen'];        
                $subcategorieschosen = $_COOKIE['subcategorieschosen'];         
                
                // Replace with the below content
                // if(!empty($brandschosen)){
                //      $filter = 'brand';
                // }

                //I have replaced the above content
                if(!empty($brandschosen) && !empty($subcategorieschosen)){
                        $filter = 'brand|subcategory';
                }                       
                else if(!empty($brandschosen) && empty($subcategorieschosen)){
                        $filter = 'brand';
                }
                if(!empty($subcategorieschosen) && empty($brandschosen)){
                        $filter = 'subcategory';
                }
                //Replaced end

                $brands = str_replace(',', '^', $brandschosen);
                $subcategories = str_replace(',', '^', $subcategorieschosen);
                $url = $this->getDealsApiUrl($page,$this->Auth->User('id'),$id,$sort,$direction,$filter,$brands,$subcategories);
                $response = $this->make_request($url,null);
                $deals = array();
                if(!empty($response)){
                        foreach ($response as $key => $value) {
                                if(!empty($value)){
                                        $deals[] = $value;
                                }
                        }
                }
                // if (!$this->Category->exists($id)) {
                        // throw new NotFoundException(__('Invalid category'));
                // }
                $this->loadModel('Api');
                // $apideals = $this->Api->getDealsByCategory($this->Auth->User('id'),$id,$page);
                // $deals = $apideals['products'];
                $myactions = $this->Api->getMyActions($this->Auth->User('id'));
                if(!empty($myactions)) {
                        foreach ($myactions['actions'] as $key => $value) {
                                if($value['UserAction']['action'] == 'like'){
                                        $likedDeals[$value['UserAction']['store_product_id']] = $value['UserAction']['id'];
                                }else{
                                        $disLikedDeals[$value['UserAction']['store_product_id']] = $value['UserAction']['id'];
                                }
                        }
                }
                $filterstr = '';

                $get_url = "'".$_SERVER['REQUEST_URI']."'";
                $urlArray = explode('=',$_SERVER['REQUEST_URI']);
                $last = $urlArray[sizeof($urlArray)-1];

                if(!isset($filter) && empty($filter)){
                        if (strpos($get_url,'filter=brand&brands') !== false)
                        {
                                $filterstr= "&filter=brand&brands=".$last;
                        }
                        if (strpos($get_url,'filter=subcategory&subcategories') !== false)
                        {
                                $filterstr= "&filter=subcategory&subcategories=".$last;
                        }

                }               

                if(isset($filter) && !empty($filter)){
                    // $filterstr = '&filter='.$filter.'&brands='.$brands;
                    $filterstr = '&filter='.$filter.'&brands='.$brands.'&subcategories='.$subcategories;
                } 

                if(!empty($subcategorieschosen) && isset($subcategorieschosen)&& empty($brandschosen) && !isset($brandschosen)){

                                $filterstr= "&filter=subcategory&subcategories=".$subcategorieschosen;
                }

                $nexturl = "/categories/getdeals/".$id."/?page=".($page+1)."&sort=".$sort."&direction=".$direction."".$filterstr;

                $this->set(compact('nexturl','deals','id','page','likedDeals','disLikedDeals','sort','direction','brands','filter','filterstr'));
                if(!empty($deals) && !empty($deals[0])){
                        $this->render('/Elements/deals');
                }else{
                        $this->render('/Elements/nodeals');
                }



        }

        public function dealdetail($item_id = null){
                $this->layout = "innerpages";
                $deal = array();
                $dealinfo = json_decode('{"entity":{"id":1015088,"url":"mobile-phones/lava-iris-atom-2-1015088","keySpecs":["Dual-SIM, 4.5-inch display, Android KitKat","1.3GHz quad core processor, 512MB RAM","5MP rear and VGA front camera"],"detailedSpecs":[{"title":"Look n Feel","specs":[{"name":"Weight","values":["130 g"]},{"name":"Size","values":["134 x 66 x 9.15 mm"]},{"name":"Form factor","values":["Candybar"]},{"name":"Keyboard","values":["Touchscreen QWERTY keyboard, Touchscreen T9 keyboard"]},{"name":"Hard keys","values":["Power button, Volume keys"]},{"name":"Color","values":["White, Black"]}]},{"title":"Display","specs":[{"name":"Type","values":["TFT LCD"]},{"name":"Screen size","values":["4.5 inch"]},{"name":"Touchscreen type","values":["Capacitive touchscreen"]},{"name":"Resolution","values":["854 x 480 px"]},{"name":"Number of colors","values":["16 M"]},{"name":"Sensors","values":["Accelerometer sensor"]}]},{"title":"Camera","specs":[{"name":"Back camera","values":["5 megapixels"]},{"name":"Flash","values":["LED"]},{"name":"Image formats","values":["JPEG"]},{"name":"Front camera","values":["VGA"]},{"name":"Additional camera features","values":["Panaroma capture, HDR, Digital zoom, Video recording"]}]},{"title":"Hardware","specs":[{"name":"Processor","values":["1.3 GHz Quad core"]}]},{"title":"Memory","specs":[{"name":"Built-in","values":["8 GB"]},{"name":"RAM","values":["512 MB"]},{"name":"Expansion type","values":["MicroSD card"]},{"name":"Expansion capacity","values":["32 GB"]}]},{"title":"Connectivity","specs":[{"name":"GPRS","values":["Yes"]},{"name":"EDGE","values":["Yes"]},{"name":"3G","values":["Yes"]},{"name":"Wi-Fi","values":["Wi-Fi 802.11 b/g/n"]},{"name":"Bluetooth","values":["v2.0"]},{"name":"USB","values":["MicroUSB v2.0"]},{"name":"GPS type","values":["Integrated GPS, A-GPS"]}]},{"title":"Communication","specs":[{"name":"Multiple SIM","values":["Dual-SIM"]},{"name":"2G network","values":["Dualband (GSM 900/1800)"]},{"name":"3G network","values":["WCDMA 2100"]},{"name":"Communication facilities","values":["SMS, Email, Instant messaging"]}]},{"title":"Software","specs":[{"name":"OS","values":["Android v4.4 (KitKat)"]},{"name":"OS upgradeable","values":["Android  v5.1 (Lollipop)"]}]},{"title":"Battery","specs":[{"name":"Capacity","values":["Talk time 2G - 16 hours,Talk time 3G - 6 hours","Standby time 2G - 6 days"]},{"name":"Battery type","values":["Li-Ion 1750 mAh battery"]},{"name":"Charger connector pin","values":["MicroUSB"]}]},{"title":"Music","specs":[{"name":"Music formats","values":["MP3"]},{"name":"Earphone","values":["3.5mm headset"]},{"name":"FM radio","values":["Yes"]}]},{"title":"Video","specs":[{"name":"File formats","values":["MP4"]},{"name":"Video recording","values":["Yes"]}]},{"title":"Miscellaneous","specs":[{"name":"Organizer","values":["Calculator, Alarm, Clock, Calendar"]},{"name":"Other features","values":["oogle Play, Google Search, Gmail, Hangout, Opera Mini, Torch, Clean Master, Note, Auto call recording, Smart gesture control"]}]}],"warranty":"1 year manufacturer\u0027s warranty","pinCode":"110001","logisticsInfo":{"business_days":1,"cod_delivery_estimate":"Mon 11-Jan-16","is_cod_available_for_location":true,"delivery_estimate":"Tomorrow, Sat 09-Jan-16","on_time_guarantee":true},"name":"Lava Iris Atom 2","categoryName":"Mobile Phone","categoryUrl":"mobile-phone/10006","breadCrumb":"\u003ca href\u003d\u0027/\u0027\u003eHome\u003c/a\u003e\u0026nbsp;\u0026gt;\u0026nbsp;\u003ca href\u003d\u0027/mobile-phone/10006\u0027\u003eMobile Phone\u003c/a\u003e\u0026nbsp;\u0026gt;\u0026nbsp;\u003ca href\u003d\u0027/lava\u0027\u003eLava\u003c/a\u003e\u0026nbsp;\u003ca\u003eIris Atom 2\u003c/a\u003e","exclusiveAffiliateInfo":[],"dtrAffiliateJSON":{"map":{"products":{"myArrayList":[{"map":{"source_product_name":"Lava Iris Atom 2 (White)","gross_price":0,"codAvailable":1,"available_price":3949.0,"marketPlaceUrl":"http://www.amazon.in/gp/offer-listing/B013SS1Z3Q","_id":25655,"source_id":1,"offer":"","coupon":""}},{"map":{"source_product_name":"Lava Iris Atom 2 (Black)","gross_price":0,"codAvailable":1,"available_price":4049.0,"marketPlaceUrl":"http://www.amazon.in/gp/offer-listing/B013SS1HMU","_id":25656,"source_id":1,"offer":"","coupon":""}},{"map":{"source_product_name":"Lava Iris Atom 2 8 GB(White)","gross_price":4189.0,"codAvailable":0,"available_price":3980,"marketPlaceUrl":"https://paytm.com/shop/p/lava-iris-atom-2-8-gb-white-MOBLAVA-IRIS-ATSURP492176AE8F567","_id":26991,"source_id":6,"offer":"","coupon":"SAVE5"}},{"map":{"source_product_name":"Lava Iris Atom 2(White, 8 GB)","gross_price":0,"codAvailable":1,"available_price":4049,"marketPlaceUrl":"http://www.flipkart.com/lava-iris-atom-2/p/itmea7n9uaebk2wg?pid\u003dMOBEA7N9CFEUQAGF","_id":26205,"source_id":2,"offer":"","coupon":""}},{"map":{"source_product_name":"Lava Iris Atom 2(Black, 8 GB)","gross_price":0,"codAvailable":1,"available_price":3900,"marketPlaceUrl":"http://www.flipkart.com/lava-iris-atom-2/p/itmea7n9uaebk2wg?pid\u003dMOBEA7N9UZVFS9WJ","_id":26206,"source_id":2,"offer":"","coupon":""}},{"map":{"source_product_name":"Lava Iris Atom 2 8gb White","gross_price":0,"codAvailable":1,"available_price":4049.0,"marketPlaceUrl":"http://www.snapdeal.com/product/lava-iris-atom-2-8gb/625585008444","_id":26203,"source_id":3,"offer":"","coupon":""}},{"map":{"source_product_name":"Lava Iris Atom 2 8gb Black","gross_price":0,"codAvailable":1,"available_price":4049.0,"marketPlaceUrl":"http://www.snapdeal.com/product/lava-iris-atom-2-8gb/641089836520","_id":26204,"source_id":3,"offer":"","coupon":""}},{"map":{"source_product_name":"Lava Iris Atom 2 (Black)","gross_price":4049,"codAvailable":0,"available_price":3847,"marketPlaceUrl":"https://paytm.com/shop/p/lava-iris-atom-2-black-MOBLAVA-IRIS-ATTHE-340303C4506A8","_id":28212,"source_id":6,"offer":"","coupon":"SAVE5"}}]}}},"defaultImageUrl":"http://static2.saholic.com/images/media/1015088/lava-iris-atom-2-default-1442230687000.jpg","iconImageUrl":"http://static2.saholic.com/images/media/1015088/lava-iris-atom-2-icon-1442230687000.jpg","thumbnailImageUrl":"http://static2.saholic.com/images/media/1015088/lava-iris-atom-2-thumbnail-1442230687000.jpg","images":[{"title":"Image 1","url":"http://static2.saholic.com/images/media/1015088/lava-iris-atom-2-default-1442230644000.jpg"},{"title":"Image 2","url":"http://static2.saholic.com/images/media/1015088/lava-iris-atom-2-2-1442230653000.jpg"},{"title":"Image 3","url":"http://static2.saholic.com/images/media/1015088/lava-iris-atom-2-3-1442230662000.jpg"},{"title":"Image 4","url":"http://static2.saholic.com/images/media/1015088/lava-iris-atom-2-4-1442230668000.jpg"}],"videos":[],"packageContents":["Handset","Battery","Charger","Headset","Data cable","User guide "],"items":[{"sellingPrice":4049.0,"id":20889,"color":"White","minEmi":250.0,"buttonText":"BUY NOW","showSellingPrice":true,"comingSoon":false,"dealPojo":{"itemId":20889,"dealTextOption":1,"dealText":"","isCod":true,"dealPrice":3949.0,"dealFreebieOption":1,"freebieItemId":0}},{"sellingPrice":4049.0,"id":20963,"color":"Black","minEmi":250.0,"buttonText":"NOTIFY ME","showSellingPrice":true,"comingSoon":false,"dealPojo":{"itemId":20963,"dealTextOption":1,"dealText":"","isCod":true,"dealPrice":3949.0,"dealFreebieOption":1,"freebieItemId":0}}],"title":"Lava Iris Atom 2 Price in India | Specifications, Features and Reviews","metaDescription":"Buy Lava Iris Atom 2 at 4049.0. All mobile phones are 100% Original and carry full Manufacturers Warranty since we procure directly from the Brand. Free Next Day Delivery."}}',true);
                $deal = json_decode('{"coupon": "", "marketPlaceUrl": "http://www.saholic.com/mobile-accessories/imported-thread-usb-cable-(10-retail-packs)-1015160", "buyBoxFlag": 1, "showMrp": 0.0, "rank": 0, "brand_id": 420, "ppq": 14, "videoLink": "", "priceUpdatedOn": 1452163605232, "sourceCategoryId": "", "category": "Accs", "cash_back": 0.0, "subCategory": "Cable", "updatedOn": 1452163605232, "tagline": "<p>One meter length</p>\r\n", "stock_status": "In Stock", "shippingCost": 0.0, "cash_back_type": 1, "gross_price": 0, "cashback": "", "filterLink": "/category/6?searchFor=Cable&filter=subcategory&subcategories=8", "persPoints": 6199.0, "source_product_name": "Imported Thread USB Cable (10 PCS)", "product_name": "Imported Thread USB Cable (10 PCS)", "status": 4, "showVideo": 0.0, "identifier": "1015160", "offer": "", "brand": "Imported", "availabilityInfo": [{"minBuyQuantity": 1, "color": "", "quantityStep": 1, "sellingPriceType": "Private deal price", "maxQuantity": 20, "item_id": 20970, "sellingPrice": 140.0, "availability": 105, "bulkPricing": [{"price": 450.0, "quantity": 4}, {"price": 250.0, "quantity": 2}]}], "source_url": "", "ignorePricing": 0, "in_stock": 1, "sourceProductId": "", "source_id": 4, "skuBundleId": 4566, "available_price": 140, "dp": 899, "is_shortage": 0, "subCategoryId": 8, "category_id": 6, "snapdealSpecialItem": 0, "showDp": 0, "url": "", "codAvailable": 1, "mrp": 0, "maxPrice": 0, "thumbnail": "http://static2.saholic.com/images/media/1015160/imported-thread-usb-cable-(10-pcs)-default-1449817265000.jpg", "source": "saholic", "secondaryIdentifier": "", "filterText": "More Cable", "_id": 27183, "model_name": "Thread USB Cable", "addedOn": 1447936529901, "quantity": 10}',true);
                
                $this->set(compact('deal','dealinfo'));
        }
        
        public function getdealsforsearchterm($searchterm,$page = null){
                $likedDeals = $disLikedDeals = array();
                $this->layout = 'ajax';
                $page = $this->request->query('page');
                $subcategorieschosen = $_COOKIE['subcategorieschosen']; 
                if(!isset($page)){
                        $page = 1;
                        $offset = 0;
                        $limit=10;
                }
                else{
                        $offset = ($page*20) - 30;
                        $limit = 20;
                }
                $sort = $this->request->query('sort');
                $direction = $this->request->query('direction');

                $url = $this->apihost."searchSubCategory/?offset=".$offset."&limit=".$limit."&searchTerm=".urlencode($searchterm)."&subCategoryId=".$subcategorieschosen;
                $response = $this->make_request($url,null);
                $deals = array();
                if(!empty($response)){
                        foreach ($response as $key => $value) {
                                if(!empty($value)){
                                        $deals[] = $value;
                                }
                        }
                }

                $this->loadModel('Api');

                $myactions = $this->Api->getMyActions($this->Auth->User('id'));
                if(!empty($myactions)) {
                        foreach ($myactions['actions'] as $key => $value) {
                                if($value['UserAction']['action'] == 'like'){
                                        $likedDeals[$value['UserAction']['store_product_id']] = $value['UserAction']['id'];
                                }else{
                                        $disLikedDeals[$value['UserAction']['store_product_id']] = $value['UserAction']['id'];
                                }
                        }
                }
                
                $nexturl = "/categories/getdealsforsearchterm/".urlencode($searchterm)."/?page=".($page+1);
        
                $this->set(compact('deals','id','page','likedDeals','disLikedDeals','sort','direction','brands','filter','nexturl'));
                if(!empty($deals) && !empty($deals[0])){
                        $this->render('/Elements/deals');
                }else{
                        $this->render('/Elements/nodeals');
                }


        }
/**
 * add method
 *
 * @return void
 */
        public function add() {
                if ($this->request->is('post')) {
                        $this->Category->create();
                        if ($this->Category->save($this->request->data)) {
                                $this->Session->setFlash(__('The category has been saved.'));
                                return $this->redirect(array('action' => 'index'));
                        } else {
                                $this->Session->setFlash(__('The category could not be saved. Please, try again.'));
                        }
                }
        }

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function edit($id = null) {
                if (!$this->Category->exists($id)) {
                        throw new NotFoundException(__('Invalid category'));
                }
                if ($this->request->is(array('post', 'put'))) {
                        if ($this->Category->save($this->request->data)) {
                                $this->Session->setFlash(__('The category has been saved.'));
                                return $this->redirect(array('action' => 'index'));
                        } else {
                                $this->Session->setFlash(__('The category could not be saved. Please, try again.'));
                        }
                } else {
                        $options = array('conditions' => array('Category.' . $this->Category->primaryKey => $id));
                        $this->request->data = $this->Category->find('first', $options);
                }
        }

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function delete($id = null) {
                $this->Category->id = $id;
                if (!$this->Category->exists()) {
                        throw new NotFoundException(__('Invalid category'));
                }
                $this->request->onlyAllow('post', 'delete');
                if ($this->Category->delete()) {
                        $this->Session->setFlash(__('The category has been deleted.'));
                } else {
                        $this->Session->setFlash(__('The category could not be deleted. Please, try again.'));
                }
                return $this->redirect(array('action' => 'index'));
        }

/**
 * admin_index method
 *
 * @return void
 */
        public function admin_index() {
                $this->Category->recursive = 0;
                $this->set('categories', $this->Paginator->paginate());
        }

/**
 * admin_view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function admin_view($id = null) {
                if (!$this->Category->exists($id)) {
                        throw new NotFoundException(__('Invalid category'));
                }
                $options = array('conditions' => array('Category.' . $this->Category->primaryKey => $id));
                $this->set('category', $this->Category->find('first', $options));
        }

/**
 * admin_add method
 *
 * @return void
 */
        public function admin_add() {
                if ($this->request->is('post')) {
                        // print_r($this->request->data);die;
                        $this->Category->create();
                        if ($this->Category->save($this->request->data)) {
                                $this->Session->setFlash(__('The category has been saved.'));
                                return $this->redirect(array('action' => 'index'));
                        } else {
                                $this->Session->setFlash(__('The category could not be saved. Please, try again.'));
                        }
                }
                $this->set('parent_id',$this->Category->find('list'));
        }

/**
 * admin_edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function admin_edit($id = null) {
                if (!$this->Category->exists($id)) {
                        throw new NotFoundException(__('Invalid category'));
                }
                if ($this->request->is(array('post', 'put'))) {
                        if ($this->Category->save($this->request->data)) {
                                $this->Session->setFlash(__('The category has been saved.'));
                                return $this->redirect(array('action' => 'index'));
                        } else {
                                $this->Session->setFlash(__('The category could not be saved. Please, try again.'));
                        }
                } else {
                        $options = array('conditions' => array('Category.' . $this->Category->primaryKey => $id));
                        $this->request->data = $this->Category->find('first', $options);
                }
        }

/**
 * admin_delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function admin_delete($id = null) {
                $this->Category->id = $id;
                if (!$this->Category->exists()) {
                        throw new NotFoundException(__('Invalid category'));
                }
                $this->request->onlyAllow('post', 'delete');
                if ($this->Category->delete()) {
                        $this->Session->setFlash(__('The category has been deleted.'));
                } else {
                        $this->Session->setFlash(__('The category could not be deleted. Please, try again.'));
                }
                return $this->redirect(array('action' => 'index'));
        }}