Subversion Repositories SmartDukaan

Rev

Blame | Last modification | View Log | RSS feed

<?php
App::uses('AppController', 'Controller');
/**
 * StoreProducts Controller
 *
 * @property StoreProduct $StoreProduct
 * @property PaginatorComponent $Paginator
 */
 set_time_limit(180);
        
class StoreProductsController extends AppController {

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

        public function beforeFilter() {
                parent::beforeFilter();
                $this->Auth->allow('bycategory','category','mine','getdeals','getliveprice','search','filter');
                $callback = $this->request->query('callback');  
                $this->livepriceurl = Configure::read('livepriceurl');  
        }

        public function filter($type='brand',$categoryId=3){
                $url = $this->apihost.'deals/brands/?category_id='.$categoryId;
                $brands = $this->make_request($url,null);
                $this->layout = 'innerpages';
                $this->set(compact('brands','categoryId'));
        }

        public function search() {
                $userId = 1;
                if(isset($userId) && !empty($userId)){
                        $this->loadModel('User');
                        $dbuser = $this->User->findById($userId);
                        $this->Auth->login($dbuser['User']);
                }
                $this->layout = 'innerpages';
                $q = $this->request->query('q');
                $page = $this->request->query('page');
                if(!isset($page)){
                        $page = 1;
                }
                $dealsperpage = Configure::read('dealsperpage');
                $offset = ($page - 1)*$dealsperpage;
                $this->loadModel('Campaign');
                $campaigns = $this->Campaign->getActiveCampaigns();
                if(isset($q) && !empty($q)){
                        if (Configure::read('log_solr_queries') === true) {
                                $this->loadModel('SearchTerm');
                                $data = array('user_id' => $this->Auth->User('id'),'search_term' => $q);
                                $this->SearchTerm->create();
                                $this->SearchTerm->save($data);                                 
                        }
                        $result = $this->get_solr_result($q,$page);
                        $this->set(compact('result','q','page'));
                }else{
                        $this->set(compact('campaigns'));
                }
        }

        public function getsearchresults() {
                $this->layout = 'ajax';
                $q = $this->request->query('q');
                $page = $this->request->query('page');
                if(!isset($page)){
                        $page = 1;
                }               
                if(isset($q) && !empty($q)){                    
                        $result = $this->get_solr_result($q,$page);
                        print $result;
                        $this->set(compact('result','q','page'));
                        $this->render('/Elements/searchresult');
                }
        }

        public function mine() {                
                $userId = $this->request->query('user_id');
                if(isset($userId) && !empty($userId)){
                        $this->loadModel('User');
                        $dbuser = $this->User->findById($userId);
                        $this->Auth->login($dbuser['User']);
                }
                // $this->checkMobileNumber();
                $likedDeals = $disLikedDeals = array();
                $this->loadModel('Api');
                $page = $this->request->query('page');
                if(!isset($page)){
                        $page = 1;
                }                               
                //Sort and Direction
                $sort = $this->request->query('sort');
                $direction = $this->request->query('direction');
                $url = $this->getDealsApiUrl($page,$this->Auth->User('id'),0,$sort,$direction);         
                $deals = $this->make_request($url,null);
                $myactions = $this->Api->getMyActions($this->Auth->User('id'));
                $liveScore = $this->Api->getLiveScore();                
                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'];
                                }
                        }
                }
                $title_for_layout = "Amazing Deals on the Go";
                $description = "Hottest Mobile Deals in Hot Hot Summer";
                $this->set(compact('page', 'title_for_layout', 'description', 'deals', 'likedDeals','disLikedDeals','sort','direction','liveScore'));
                $this->render('/Pages/home');
        }

        public function getdeals() {
                $likedDeals = $disLikedDeals = array();
                $this->layout = 'ajax';
                $this->loadModel('Api');
                $page = $this->request->query('page');
                if(!isset($page)){
                        $page = 1;
                }       
                //Sort and Direction
                $sort = $this->request->query('sort');
                $direction = $this->request->query('direction');
                $url = $this->getDealsApiUrl($page,$this->Auth->User('id'),0,$sort,$direction);
                $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'];
                                }
                        }
                }
                $title_for_layout = "Amazing Deals on the Go";
                $description = "Hottest Mobile Deals in Hot Hot Summer";
                $this->set(compact('page', 'title_for_layout', 'description', 'deals', 'likedDeals','disLikedDeals','sort','direction'));
                $this->render('/Elements/deals');
        }       
/**
 * index method
 *
 * @return void
 */
        public function index($user_id=null) {
                $this->response->type('json');
                $this->layout = 'ajax';
                $limit = 20;
                $this->StoreProduct->recursive = -1;
                $count = $this->StoreProduct->find('count');
                $this->StoreProduct->Behaviors->attach('Containable');
                $this->Paginator->settings = array('order'=>array('rank'=>'asc'),'contain'=>array('Product'),'limit'=>$limit,'fields'=>array('Product.category_id','StoreProduct.id','StoreProduct.title','StoreProduct.thumbnail','StoreProduct.available_price','StoreProduct.cashback','StoreProduct.tagline','StoreProduct.offer','StoreProduct.cashback','StoreProduct.available_price','Product.name'));
                $result = array('products' => $this->Paginator->paginate(),'maxresults'=>ceil($count/$limit));
                $callback = $this->request->query('callback');
                $this->set(array(
                    'result' => $result,
                    'callback' => $callback,
                    '_serialize' => array('result')
                ));
                $this->render('/Elements/json');
        }

        public function category($user_id=null,$categoryId=null) {
                $this->response->type('json');
                $this->layout = 'ajax';
                $limit = 20;
                $this->StoreProduct->recursive = -1;
                // $count = $this->StoreProduct->find('count');
                $this->StoreProduct->Behaviors->attach('Containable');
                $this->Paginator->settings = array('order'=>array('rank'=>'asc'),'conditions'=>array('StoreProduct.category_id'=>$categoryId),'contain'=>array('Product'),'limit'=>$limit,'fields'=>array('Product.category_id','StoreProduct.id','StoreProduct.title','StoreProduct.thumbnail','StoreProduct.available_price','StoreProduct.cashback','StoreProduct.tagline','StoreProduct.offer','StoreProduct.available_price'));
                $result = array('products' => $this->Paginator->paginate());
                $callback = $this->request->query('callback');
                $this->set(array(
                    'result' => $result,
                    'callback' => $callback,
                    '_serialize' => array('result')
                ));
                $this->render('/Elements/json');
        }

        public function bycategory($userId=null) {
                $this->loadModel('UserCategory');
                $options = array('conditions' => array('user_id'=>$userId),'recursive'=>-1);
                $userCategories = $this->UserCategory->find('all',$options);            
                $this->response->type('json');
                $this->layout = 'ajax';
                $limit = 20;
                $conditions = null;
                $this->StoreProduct->recursive = -1;
                $this->StoreProduct->Behaviors->attach('Containable');
                $products = array();
                // if(!empty($userCategories)){
                if(1==2){
                        foreach ($userCategories as $key => $value) {
                                $categoryIds[] = $value['UserCategory']['category_id'];
                                $conditions = array('StoreProduct.category_id'=>$value['UserCategory']['category_id']);
                                $this->Paginator->settings = array('contain'=>array('Product'),'limit'=>$limit,'fields'=>array('Product.category_id','StoreProduct.id','StoreProduct.title','StoreProduct.thumbnail','StoreProduct.available_price','StoreProduct.cashback','StoreProduct.available_price','StoreProduct.tagline','StoreProduct.offer'),'conditions'=>$conditions);
                                $rows = $this->Paginator->paginate();                           
                                foreach($rows AS $key => $product){
                                        $products[$value['UserCategory']['category_id']][$key][] = $product;
                                }
                        }
                }else{
                        //Fetch all categories
                        $categories = $this->StoreProduct->Product->Category->find('all');
                        foreach ($categories as $key => $value) {
                                $categoryIds[] = $value['Category']['id'];
                                $conditions = array('StoreProduct.category_id'=>$value['Category']['id']);
                                $this->Paginator->settings = array('contain'=>array('Product'),'limit'=>$limit,'fields'=>array('Product.category_id','StoreProduct.id','StoreProduct.title','StoreProduct.thumbnail','StoreProduct.available_price','StoreProduct.cashback','StoreProduct.available_price','StoreProduct.tagline','StoreProduct.offer'),'conditions'=>$conditions);
                                $rows = $this->Paginator->paginate();                           
                                foreach($rows AS $key => $product){
                                        $products[$value['Category']['id']][$key][] = $product;
                                }
                        }
                }               
                $this->log(print_r($products,1),'bycategory')   ;               
                $result = array('products' => $products);//,'categories'=>$categoryIds);
                $callback = $this->request->query('callback');
                $this->set(array(
                    'result' => $result,
                    'callback' => $callback,
                    '_serialize' => array('result')
                ));
                $this->render('/Elements/json');
        }

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function view($id = null,$bundleId=null) {
                $this->layout = "innerpages";
                $cachekey = 'storeproduct-'.$id;
                $product = Cache::read($cachekey,'fivemin');
                if(empty($product)) {
                        $url = $this->apihost.'masterData/getSkuById/'.$id;
                        $product = $this->make_request($url,null);
                        Cache::write($cachekey,$product,'fivemin');                     
                }
                $storeProduct = json_decode($product[0],1);
                $activestores = Configure::read('activestores');
                $url = $this->livepriceurl."?bundleId=$bundleId";
                $storeitems = $this->make_request($url,null);
                usort($storeitems, function($a, $b) {
                    if($a["available_price"] == $b["available_price"])
                        return 0;
                    return $a["available_price"] > $b["available_price"]? 1: -1;
                });
                $storeShown = array();
                foreach($activestores AS $storeName => $store){
                        foreach ($storeitems as $storedeal) {
                                if($storedeal['source_id']==$store['store_id']){
                                        $storeShown[$store['store_id']] = true;
                                        break;
                                }
                        }
                }
                foreach($activestores AS $storeName => $store){
                        if(empty($storeShown[$store['store_id']])){
                                $storeShown[$store['store_id']] = false;
                        }
                }

                
                $this->set(compact('storeProduct','activestores','storeitems','storeShown'));
        }

        public function my_sort($a, $b)
        {
            if ($a->available_price > $b->available_price) {
                return -1;
            } else if ($a->available_price < $b->available_price) {
                return 1;
            } else {
                return 0; 
            }
        }

        public function getliveprice($bundleId=null,$storeId=null) {
                // $cachekey = 'liveprice-'.$bundleId.'-'.$storeId;
                // $this->log($cachekey,'api');
                // $products = Cache::read($cachekey,'fivemin');
                // if(empty($products)) {
                session_write_close();
                $result = array();
                $this->response->type('json');
                $this->layout = 'ajax';
                $url = $this->livepriceurl."?bundleId=$bundleId";
                $products = $this->make_request($url,null);
                        // Cache::write($cachekey,$products,'fivemin');                 
                // }
                if(!empty($products)){
                        $result['products'] = array();
                        foreach($products AS $product) {
                                // debug($product);
                                array_push($result['products'],$product);
                        }
                        $products = json_decode(stripslashes(json_encode($products)));
                        $result['success'] = true;
                        // $result['products'] = $products;
                } else{
                        $result['success'] = false;
                }
                $this->response->type('json');
                $this->layout = 'ajax';
                $this->set(array(
                    'result' => $result,
                    '_serialize' => array('result')
                ));
                $this->render('/Elements/json');
        }

/**
 * add method
 *
 * @return void
 */
        public function add() {
                if ($this->request->is('post')) {
                        $this->StoreProduct->create();
                        if ($this->StoreProduct->save($this->request->data)) {
                                $this->Session->setFlash(__('The store product has been saved.'));
                                return $this->redirect(array('action' => 'index'));
                        } else {
                                $this->Session->setFlash(__('The store product could not be saved. Please, try again.'));
                        }
                }
                $stores = $this->StoreProduct->Store->find('list');
                $products = $this->StoreProduct->Product->find('list');
                $this->set(compact('stores', 'products'));
        }

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

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

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

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

/**
 * admin_add method
 *
 * @return void
 */
        public function admin_add() {
                if ($this->request->is('post')) {
                        $this->StoreProduct->create();
                        if ($this->StoreProduct->save($this->request->data)) {
                                $this->Session->setFlash(__('The store product has been saved.'));
                                return $this->redirect(array('action' => 'index'));
                        } else {
                                $this->Session->setFlash(__('The store product could not be saved. Please, try again.'));
                        }
                }
                $stores = $this->StoreProduct->Store->find('list');
                $products = $this->StoreProduct->Product->find('list');
                $this->set(compact('stores', 'products'));
        }

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

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