Subversion Repositories SmartDukaan

Rev

Rev 20274 | Blame | Compare with Previous | Last modification | View Log | RSS feed

<?php
App::uses('AppController', 'Controller');
/**
 * Orders Controller
 *
 * @property Order $Order
 * @property PaginatorComponent $Paginator
 */
class OrdersController extends AppController {

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

        public function beforeFilter() {                
                parent::beforeFilter();
//              $this->Auth->allow('add','mine','pendingcashbacks','all');
                $this->Auth->allow('add','all');
                $this->apihost = Configure::read('pythonapihost');
        }
        
        
        public function getOrderFilters($type='user') {
                $cachekey = 'orderfilters-'.$type;
                $filters = Cache::read($cachekey);
                if(empty($filters)) {
                        $url = $this->apihost."orderfilters/?type=".$type;
                        $response = $this->make_request($url, null);
                        echo $response;
                        if(!empty($response)){
                                $filters = $response;
                                Cache::write($cachekey,$filters);
                        }
                }
        return $filters;
        }
        
        public function mine() {
                $type = $this->request->query('type');
                $page = $this->request->query('page');
                $page = isset($page)?$page:1;
                $userId = $this->request->query('user_id');
                $this->layout = "innerpages";
                $url = $this->apihost."storeorder/user/".$this->Auth->User('id')."?page=$page&window=10";
                if(isset($type) && !empty($type)) {
                        $url .= '&type='.$type;
                }
                $response = $this->make_request($url,null);
                $totalPages = $response['totalPages'];
                if(!empty($response['data'])){
                        $this->set('orders',$response['data']);
                }
                $ignoredFields = array('imgUrl','status','productTitle','estimatedDeliveryDate','productCode','merchantSubOrderId','productUrl','closed','tracingkUrl','detailedStatus');
                $storemapping = Configure::read('storemapping');
                $activestores = Configure::read('activestores');
                $amazonorderurl = Configure::read('amazonorderurl');
                $this->set(compact('ignoredFields','page','totalPages','userId','activestores','storemapping','amazonorderurl'));
        }

        public function by($userId) {
                $page = $this->request->query('page');
                $page = isset($page)?$page:1;           
                $this->layout = "innerpages";
                $url = $this->apihost."storeorder/user/".$userId."?page=$page&window=10";
                $response = $this->make_request($url,null);
                $totalPages = $response['totalPages'];
                if(!empty($response['data'])){
                        $this->set('orders',$response['data']);
                }
                $ignoredFields = array('imgUrl','status','productTitle','estimatedDeliveryDate','productCode','merchantSubOrderId','productUrl','closed','tracingkUrl','detailedStatus');
                $storemapping = Configure::read('storemapping');
                $activestores = Configure::read('activestores');
                $amazonorderurl = Configure::read('amazonorderurl');
                $this->set(compact('ignoredFields','page','totalPages','userId','activestores','storemapping','amazonorderurl'));
        }

        public function pendingcashbacks() {
                $userId = $this->request->query('user_id');
                $this->layout = "innerpages";
                $url = $this->apihost."storeorder/user/".$userId."?page=1&window=50&searchMap=%7B\"subOrders.cashBackStatus\"%3A%20%7B\"%24in\"%3A%20%5B\"Approved\"%2C%20\"Pending\"%5D%7D%7D";
                $response = $this->make_request($url,null);
                // debug($response);
                $creditedOrders = $pendingOrders = $approvedOrders = array();
                $creditedAmount = $pendingAmount = $approvedAmount = 0;
                if(!empty($response['data'])){
                        foreach ($response['data'] as $key => $order) {
                                if(!empty($order['subOrders'])){
                                        foreach ($order['subOrders'] as $key => $suborder) {
                                                $suborder['storeId'] = $order['storeId'];
                                                if($order['storeId']!=4){
                                                        $suborder['merchantOrderId'] = $order['merchantOrderId'];
                                                } else {
                                                        $suborder['merchantOrderId'] = $suborder['merchantSubOrderId'];
                                                }
                                                if(!empty($order['orderTrackingUrl'])){
                                                        $suborder['orderSuccessUrl'] = $order['orderTrackingUrl'];
                                                }
                                                switch($suborder['cashBackStatus']){
                                                        case 'Approved':
                                                        $approvedOrders[] = $suborder;
                                                        $approvedAmount += $suborder['cashBackAmount'];
                                                        break;
                                                        case 'Pending':
                                                        $pendingOrders[] = $suborder;
                                                }
                                        }
                                }
                        }
                }
                $url = $this->apihost.'pending-cashbacks/user/'.$userId;
                $result = $this->make_request($url,null);
                $pendingAmount = $result['amount'];
                //Get pending cashbacks
                $url = $this->apihost.'pending-refunds/user/'.$userId;
                $pendingCashbacks = $this->make_request($url,null);
                //Get credited cashbacks
                $url = $this->apihost.'refund/user/'.$userId;
                $creditedCashbacks = $this->make_request($url,null);
                
                $totalcreditedcashback = 0;
                if(!empty($creditedCashbacks)){
                        $totalcreditedcashback = $creditedCashbacks['credited'];
                }
                
                $creditKeyArray = array();
                $creditValueArray = array();
                $total_credited_amount = 0;
                if(!empty($creditedCashbacks)){
                        foreach ($creditedCashbacks['data'] as $key => $value) {
                                $creditedAmount += $value['userAmount'];                                
                                $data = array('subOrders.batchId'=>$value['batch']);
                                $jsonVar = json_encode($data);
                                $url = $this->apihost."storeorder/user/".$this->Auth->User('id')."?page=1&window=50&searchMap=$jsonVar";
                                $creditedOrders[$value['batch']] = $this->make_request($url,null);
                                $total_credited_amount =$total_credited_amount + $value['userAmount'];
                                if($value['type']== 'Order')
                                {
                                        $creditValueArray['amount'] = $value['userAmount'];
                                        $creditValueArray['type'] = $value['type'];
                                        $creditValueArray['fortbatchid'] = $value['batch'];
                                        $creditValueArray['creditedDate'] = date('Y-m-d',strtotime($value['timestamp']));
                                        $creditValueArray['description'] = '';
                                        // $creditKeyArray[date('Y-m-d',strtotime($value['timestamp']))] = $creditValueArray;
                                        $creditKeyArray[$value['batch'].$value['type']] = $creditValueArray;
                                }
                                elseif($value['type']== 'Refund'){
                                        $creditValueArray['amount'] = $value['userAmount'];
                                        $creditValueArray['type'] = $value['type'];
                                        $creditValueArray['fortbatchid'] = $value['batch'];
                                        $creditValueArray['creditedDate'] = date('Y-m-d',strtotime($value['timestamp']));
                                        $creditValueArray['description'] = $value['description'];
                                        $creditKeyArray[$value['batch'].$value['type']] = $creditValueArray;
                                        
                                }
                                elseif($value['type']== 'Adjustment'){
                                        $creditValueArray['amount'] = $value['userAmount'];
                                        $creditValueArray['type'] = $value['type'];
                                        $creditValueArray['fortbatchid'] = $value['batch'];
                                        $creditValueArray['creditedDate'] = date('Y-m-d',strtotime($value['timestamp']));
                                        $creditValueArray['description'] = $value['description'];
                                        $creditKeyArray[$value['batch'].$value['type']] = $creditValueArray;
                                }
                                elseif($value['type']== 'Offer'){
                                        $creditValueArray['amount'] = $value['userAmount'];
                                        $creditValueArray['type'] = $value['type'];
                                        $creditValueArray['fortbatchid'] = $value['batch'];
                                        $creditValueArray['creditedDate'] = date('Y-m-d',strtotime($value['timestamp']));
                                        $creditValueArray['description'] = $value['description'];
                                        $creditKeyArray[$value['batch'].$value['type']] = $creditValueArray;
                                }
                        }
                }
                $storemapping = Configure::read('storemapping');
                $activestores = Configure::read('activestores');
                //App related cashbacks
                $this->loadModel('UserAppCashback');
                $this->loadModel('UserAppInstall');
                //Compute last two fortnight ids
                $fortnightIds = array();
                if(date('d',time())<=15){
                        $fortnightIds[] = 2*(date('m',time())-1)-1;
                        $fortnightIds[] = 2*(date('m',time())-1);
                }else{
                        $fortnightIds[] = 2*(date('m',time())-1);
                        $fortnightIds[] = 2*(date('m',time())-1)+1;
                }
                $cashBacks = array();

                // Approved Start

                $url = $this->apihost.'appUserCashBack/'.$userId.'/Approved';
                $getapproved = $this->make_request($url,null);
                $fortnight = array();
                $fortnight_amount = array();
                $counter = 0;
                $total_approved_amount = 0;
                $current_date =  date("Y");
                foreach ($getapproved["UserAppCashBack"] as $key => $value) {
                         $fortnight[$counter] = $value["fortnightOfYear"];
                         $fortnight_amount[$counter] = $value["amount"];
                         $total_approved_amount += $value["amount"];
                         $counter++;
                }
                $approvedFortnight = array();
                for($i=0; $i<count($fortnight); $i++){
                        $url = $this->apihost.'appUserBatchDrillDown/'.$userId.'/'.$getapproved["UserAppCashBack"][$i]['fortnightOfYear'].'/'.$getapproved["UserAppCashBack"][$i]['yearVal'];
                        $approvedFortnight[$i] = $this->make_request($url,null);
                // $url = $this->apihost.'appUserBatchDrillDown/1/16/2015';
                // $approvedFortnight[] = $this->make_request($url,null);
                }
                // debug($approvedFortnight);
                $this->set(compact('fortnight','total_approved_amount','fortnight_amount','approvedFortnight'));                
        // Approved End 

        // App Credit Start
                $creditedFortnight = array();
                $url = $this->apihost.'appUserCashBack/'.$userId.'/Credited';
                $getcredited = $this->make_request($url,null);
                // debug($getcredited);
                foreach ($getcredited['UserAppCashBack'] as $key => $value) {



                        $url = $this->apihost.'appUserBatchDrillDown/'.$userId.'/'.$value['fortnightOfYear'].'/'.$value['yearVal'];
                        $creditedFortnight[$value['fortnightOfYear']] = $this->make_request($url,null);

                        $creditValueArray['amount'] = $value['amount'];
                        // $total_credited_amount = $total_credited_amount + $value['amount'];
                        $creditValueArray['type'] = 'App';
                        $creditValueArray['fortbatchid'] = $value['fortnightOfYear'];
                        $creditValueArray['creditedDate'] = $value['creditedDate'];
                        $creditValueArray['description'] = '';
                        $creditKeyArray[$value['batchCreditId'].'App'] = $creditValueArray;
                        // echo "total credit",$total_credited_amount;
                        // echo $url;
                }
                
                ksort($creditKeyArray);
                $this->set(compact('getcredited','creditedFortnight','creditKeyArray','total_credited_amount'));
                // debug($creditedFortnight);
        // App Credit End


                foreach ($fortnightIds AS $fortnightId){
                        $appInstalls = array();
                        $options = array('conditions'=>array('fortnightOfYear'=>$fortnightId,'user_id'=>$this->Auth->User('id')),'fields'=>array('status','amount'));
                        $temp = $this->UserAppCashback->find('first',$options);
                        if(isset($temp) && !empty($temp)){
                                $cashBacks[$temp['UserAppCashback']['status']]['amount'] = $temp['UserAppCashback']['amount'];
                                $cashBacks[$temp['UserAppCashback']['status']]['fortnightOfYear'] = $fortnightId;
                                // debug($fortnightId);
                                $options = array('conditions'=>array('fortnightOfYear'=>$fortnightId,'user_id'=>$this->Auth->User('id')),'fields'=>array('sum(payoutAmount) AS amount','sum(installCount) AS installs','transaction_date'),'group'=>'transaction_date');
                                $installs = $this->UserAppInstall->find('all',$options);                        
                                if(!empty($installs)){
                                        foreach ($installs as $key => $value) {
                                                $appInstalls[$value['UserAppInstall']['transaction_date']] = $value[0];                                 
                                        }
                                        $cashBacks[$temp['UserAppCashback']['status']]['installs'] = $appInstalls;
                                }
                        }
                }
                
//              offerresponse start
                
                $cachekey = 'target-'.$userId;
                $getoffer = Cache::read($cachekey,'target');
                
                $offerresponse = "";
                $getcashback = 0;
                if($getoffer === false){
                        $offerurl = $this->apihost."getOfferForUser/?user_id=".$userId;
                        $offerresponse = $this->make_request($offerurl,null);
                        Cache::write($cachekey , $offerresponse ,'target');
                        if(empty($offerresponse)){
                                $offerresponse = "";
                        }
                }else{
                        if(!empty($getoffer)){
                                $offerresponse  = $getoffer;
                                
                                }
                }
                
                
                if(!empty($offerresponse)){
                        $totalval = $offerresponse['delivered_order_value'] + $offerresponse['pending_order_value'];
                        
                        if($totalval< $offerresponse['target1']){
                                $getcashback = 0;
                        }
                        else if($totalval< $offerresponse['target2']){
                                if($offerresponse['maxCashBack']< intval(($totalval*$offerresponse['target1_cash_back_percetage'])/100)){
                                        $getcashback = $offerresponse['maxCashBack'];
                                }
                                else{
                                        $getcashback = intval(($totalval*$offerresponse['target1_cash_back_percetage'])/100);
                                }
                                        
                        }
                        else{
                                if($offerresponse['maxCashBack']< intval(($totalval*$offerresponse['target2_cash_back_percetage'])/100)){
                                        $getcashback = $offerresponse['maxCashBack'];
                                }
                                else{
                                        $getcashback = intval(($totalval*$offerresponse['target2_cash_back_percetage'])/100);
                                }
                                        
                        }
                }
//              offerresponse end
                
                $targetuser = array(); 
                $this->set(compact('getcashback','targetuser','userId','storemapping','activestores','pendingOrders','approvedOrders','creditedOrders','pendingCashbacks','creditedCashbacks','pendingAmount','approvedAmount','creditedAmount','cashBacks'));
        }

        public function getAppByDate($date) {
                $url = $this->apihost.'appUserBatchDateDrillDown/1/'.$date;
                $getApp = $this->make_request($url,null);
                echo $getApp;
        }

        public function usercashbacks($userId) {        
                $this->set('byUser',$userId);
                $this->layout = "innerpages";
                $url = $this->apihost."storeorder/user/".$userId."?page=1&window=50&searchMap=%7B\"subOrders.cashBackStatus\"%3A%20%7B\"%24in\"%3A%20%5B\"Approved\"%2C%20\"Pending\"%5D%7D%7D";
                $response = $this->make_request($url,null);
                // debug($response);
                $creditedOrders = $pendingOrders = $approvedOrders = array();
                $creditedAmount = $pendingAmount = $approvedAmount = 0;
                echo $response['data'];
                if(!empty($response['data'])){
                        foreach ($response['data'] as $key => $order) {
                                if(!empty($order['subOrders'])){
                                        foreach ($order['subOrders'] as $key => $suborder) {
                                                $suborder['storeId'] = $order['storeId'];
                                                if($order['storeId']!=4){
                                                        $suborder['merchantOrderId'] = $order['merchantOrderId'];
                                                } else {
                                                        $suborder['merchantOrderId'] = $suborder['merchantSubOrderId'];
                                                }
                                                if(!empty($order['orderTrackingUrl'])){
                                                        $suborder['orderSuccessUrl'] = $order['orderTrackingUrl'];
                                                }
                                                $suborder['cashBackStatus'];
                                                switch($suborder['cashBackStatus']){
                                                        // case 'Credited to wallet'://Credited
                                                        // $creditedOrders[] = $suborder;
                                                        // break;
                                                        case 'Approved':
                                                        $approvedOrders[] = $suborder;
                                                        $approvedAmount += $suborder['cashBackAmount'];
                                                        break;
                                                        case 'Pending':
                                                        $pendingOrders[] = $suborder;
                                                        // $pendingAmount += $suborder['cashBackAmount'];
                                                }
                                        }
                                }
                        }
                }
                $url = $this->apihost.'pending-cashbacks/user/'.$userId;
                $result = $this->make_request($url,null);
                $pendingAmount = $result['amount'];
                //Get pending cashbacks
                $url = $this->apihost.'pending-refunds/user/'.$userId;
                $pendingCashbacks = $this->make_request($url,null);
                //Get credited cashbacks
                $url = $this->apihost.'refund/user/'.$userId;
                $creditedCashbacks = $this->make_request($url,null);
                
                $totalcreditedcashback = 0;
                if(!empty($creditedCashbacks)){
                        $totalcreditedcashback = $creditedCashbacks['credited'];
                }
                
                $creditKeyArray = array();
                $creditValueArray = array();
                $total_credited_amount = 0;
                if(!empty($creditedCashbacks)){
                        foreach ($creditedCashbacks['data'] as $key => $value) {
                                $creditedAmount += $value['userAmount'];                                
                                $data = array('subOrders.batchId'=>$value['batch']);
                                $jsonVar = json_encode($data);
                                $url = $this->apihost."storeorder/user/".$userId."?page=1&window=50&searchMap=$jsonVar";
                                $creditedOrders[$value['batch']] = $this->make_request($url,null);
                                $total_credited_amount =$total_credited_amount + $value['userAmount'];
                                if($value['type']== 'Order')
                                {
                                        $creditValueArray['amount'] = $value['userAmount'];
                                        $creditValueArray['type'] = $value['type'];
                                        $creditValueArray['fortbatchid'] = $value['batch'];
                                        $creditValueArray['creditedDate'] = date('Y-m-d',strtotime($value['timestamp']));
                                        // $creditKeyArray[date('Y-m-d',strtotime($value['timestamp']))] = $creditValueArray;
                                        $creditValueArray['description'] = '';
                                        $creditKeyArray[$value['batch'].$value['type']] = $creditValueArray;
                                }
                                elseif($value['type']== 'Refund'){
                                        $creditValueArray['amount'] = $value['userAmount'];
                                        $creditValueArray['type'] = $value['type'];
                                        $creditValueArray['fortbatchid'] = $value['batch'];
                                        $creditValueArray['creditedDate'] = date('Y-m-d',strtotime($value['timestamp']));
                                        $creditValueArray['description'] = $value['description'];
                                        $creditKeyArray[$value['batch'].$value['type']] = $creditValueArray;
                                                
                                }
                                elseif($value['type']== 'Adjustment'){
                                        $creditValueArray['amount'] = $value['userAmount'];
                                        $creditValueArray['type'] = $value['type'];
                                        $creditValueArray['fortbatchid'] = $value['batch'];
                                        $creditValueArray['creditedDate'] = date('Y-m-d',strtotime($value['timestamp']));
                                        $creditValueArray['description'] = $value['description'];
                                        $creditKeyArray[$value['batch'].$value['type']] = $creditValueArray;
                                }
                                
                                elseif($value['type']== 'Offer'){
                                        $creditValueArray['amount'] = $value['userAmount'];
                                        $creditValueArray['type'] = $value['type'];
                                        $creditValueArray['fortbatchid'] = $value['batch'];
                                        $creditValueArray['creditedDate'] = date('Y-m-d',strtotime($value['timestamp']));
                                        $creditValueArray['description'] = $value['description'];
                                        $creditKeyArray[$value['batch'].$value['type']] = $creditValueArray;
                                }
                                
                        }
                }

                $storemapping = Configure::read('storemapping');
                $activestores = Configure::read('activestores');
                //App related cashbacks
                $this->loadModel('UserAppCashback');
                $this->loadModel('UserAppInstall');
                //Compute last two fortnight ids
                $fortnightIds = array();
                if(date('d',time())<=15){
                        $fortnightIds[] = 2*(date('m',time())-1)-1;
                        $fortnightIds[] = 2*(date('m',time())-1);
                }else{
                        $fortnightIds[] = 2*(date('m',time())-1);
                        $fortnightIds[] = 2*(date('m',time())-1)+1;
                }
                $cashBacks = array();

                // Approved Start

                $url = $this->apihost.'appUserCashBack/'.$userId.'/Approved';
                $getapproved = $this->make_request($url,null);
                $fortnight = array();
                $fortnight_amount = array();
                $counter = 0;
                $total_approved_amount = 0;
                $current_date =  date("Y");
                foreach ($getapproved["UserAppCashBack"] as $key => $value) {
                         $fortnight[$counter] = $value["fortnightOfYear"];
                         $fortnight_amount[$counter] = $value["amount"];
                         $total_approved_amount += $value["amount"];
                         $counter++;
                }
                $approvedFortnight = array();
                for($i=0; $i<count($fortnight); $i++){
                        $url = $this->apihost.'appUserBatchDrillDown/'.$userId.'/'.$getapproved["UserAppCashBack"][$i]['fortnightOfYear'].'/'.$getapproved["UserAppCashBack"][$i]['yearVal'];
                        $approvedFortnight[$i] = $this->make_request($url,null);
                // $url = $this->apihost.'appUserBatchDrillDown/1/16/2015';
                // $approvedFortnight[] = $this->make_request($url,null);
                }
                // debug($approvedFortnight);
                $this->set(compact('fortnight','total_approved_amount','fortnight_amount','approvedFortnight'));                
        // Approved End 

        // App Credit Start
                $creditedFortnight = array();
                $url = $this->apihost.'appUserCashBack/'.$userId.'/Credited';
                $getcredited = $this->make_request($url,null);
                // debug($getcredited);
                foreach ($getcredited['UserAppCashBack'] as $key => $value) {



                        $url = $this->apihost.'appUserBatchDrillDown/'.$userId.'/'.$value['fortnightOfYear'].'/'.$value['yearVal'];
                        $creditedFortnight[$value['fortnightOfYear']] = $this->make_request($url,null);

                        $creditValueArray['amount'] = $value['amount'];
                        // $total_credited_amount = $total_credited_amount + $value['amount'];
                        $creditValueArray['type'] = 'App';
                        $creditValueArray['fortbatchid'] = $value['fortnightOfYear'];
                        $creditValueArray['creditedDate'] = $value['creditedDate'];
                        $creditValueArray['description'] = '';
                        $creditKeyArray[$value['batchCreditId'].'App'] = $creditValueArray;
                        // echo "total credit",$total_credited_amount;
                        // echo $url;
                }
                
                ksort($creditKeyArray);
                $this->set(compact('getcredited','creditedFortnight','creditKeyArray','total_credited_amount', 'creditedOrders', 'pendingAmount', 'pendingOrders','approvedAmount', 'approvedOrders'));

        }

/*
        public function index() {
                throw new NotFoundException(__('Access Denied'));
                $this->Order->recursive = 0;
                $this->set('orders', $this->Paginator->paginate());
        }


        public function view($id = null) {
                throw new NotFoundException(__('Access Denied'));
                if (!$this->Order->exists($id)) {
                        throw new NotFoundException(__('Invalid order'));
                }
                $options = array('conditions' => array('Order.' . $this->Order->primaryKey => $id));
                $this->set('order', $this->Order->find('first', $options));
        }
*/
        
/**
 * add method
 *
 * @return void
 */

        public function postOrders($order=null) {
                // Configure::load('live');
                $apihost = Configure::read('pythonapihost');
                $url = $apihost."storeorder";
                if(!empty($order)) {
                        $params = array('sourceId'=>$order['Order']['store_id'],'orderId'=>$order['Order']['id'],'subTagId'=>$order['Order']['sub_tag'],'userId'=>$order['Order']['user_id'],'rawHtml'=>$order['Order']['rawhtml'],'orderSuccessUrl'=>$order['Order']['order_url']);
                        $jsonVar = json_encode($params);
                        return $this->make_request($url,$jsonVar);
                }else{
                        $result = array('success'=>false,'message'=>'Empty order array');
                        return $result;
                }
        }

        public function add() {
                $this->log(print_r($this->request->data,1),'orders');
                if ($this->request->is('post')) {
                        if($this->request->data['zip']){
                                $this->request->data['rawhtml'] = gzuncompress(base64_decode($this->request->data['rawhtml'])); 
                        }
                        $this->log(print_r($this->request->data,1),'orders');
                        if(empty($this->request->data['id'])) {
                                $this->Order->create();
                        }
                        $this->request->data['ip'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
                        if ($this->Order->save($this->request->data)) {
                                //$this->loadModel('PythonApi');        
                                if(empty($this->request->data['id'])) {
                                        $id = $this->Order->getLastInsertID();
                                }else{
                                        $id = $this->request->data['id'];
                                }
                                $order = $this->Order->find('first',array('conditions'=>array('id'=>$id),'recursive'=>-1));
                                $response = $this->postOrders($order);
                                $this->log(print_r($response,1),'orders');
                                if(!empty($response) && $response['result']) {
                                        //if($response['result'] == 'HTML_REQUIRED' || $response['result'] == 'requireHtml') {
                                        if($response['htmlRequired'] == 1) {
                                                $this->loadModel('Rawhtml');
                                                $data = array('order_id' => $order['Order']['id'],'url' => $response['url'], 'status' => 'new');
                                                $this->Rawhtml->create();
                                                $this->Rawhtml->save($data); 
                                                //$result =array('success'=>true,'message'=>__('requireHtml'),'url' => $response['url'],'orderId' => $response['orderId']);
                                                $result =  $response;
                                                $sql = "UPDATE orders SET status = '".$response['result']."' WHERE id = ".$order['Order']['id'];
                                        }/* elseif($response['result'] == 'IGNORED') {
                                                $result =array('success'=>true,'message'=>__('IGNORED'));
                                                $sql = "UPDATE orders SET status = 'deleted' WHERE id = ".$order['Order']['id'];
                                        } elseif($response['result'] == 'PARSE_ERROR') {
                                                $result =array('success'=>true,'message'=>__('PARSE_ERROR'));
                                                $sql = "UPDATE orders SET status = 'deleted' WHERE id = ".$order['Order']['id'];
                                        } */
                                        else {
                                                $result =array('success'=>true,'message'=> $response['result']);
                                                $sql = "UPDATE orders SET status = '".$response['result']."' WHERE id = ".$order['Order']['id'];
                                        }
                                        $this->Order->query($sql);
                                }
                                //$result = array('success'=>true,'message'=>__('HTML_REQUIRED'),'url'=>'https://www.amazon.in/gp/css/summary/edit.html?orderID=404-7369214-6566739');
/*
                                $options = array('conditions'=>array('status'=>'mapped'),'recursive'=>-1);
                                $order = $this->Order->find('first',$options);
                                if(!empty($orders)) {
                                        foreach($orders AS $order) {
                                                $response = $this->PythonApi->postOrders($order);
                                                if(!empty($response) && $response['result']) {
                                                        $sql = "UPDATE orders SET status = 'processed' WHERE id = ".$order['Order']['id'];
                                                        $this->Order->query($sql);
                                                }
                                        }
                                }
*/
                        } else {
                                $this->log(print_r($this->Order->validationErrors,1),'orders');
                                $result = array('success'=>false,'message'=>__('The order could not be saved. Please, try again.'));
                        }
                        $this->response->type('json');
                        $this->layout = 'ajax';
                        $this->set(array(
                            'result' => $response,
                            // 'callback' => $callback,
                            '_serialize' => array('result')
                        ));
                        $this->render('/Elements/json');                
                }                       
        }

/*

        public function edit($id = null) {
                throw new NotFoundException(__('Access Denied'));
                if (!$this->Order->exists($id)) {
                        throw new NotFoundException(__('Invalid order'));
                }
                if ($this->request->is(array('post', 'put'))) {
                        if ($this->Order->save($this->request->data)) {
                                $this->Session->setFlash(__('The order has been saved.'));
                                return $this->redirect(array('action' => 'index'));
                        } else {
                                $this->Session->setFlash(__('The order could not be saved. Please, try again.'));
                        }
                } else {
                        $options = array('conditions' => array('Order.' . $this->Order->primaryKey => $id));
                        $this->request->data = $this->Order->find('first', $options);
                }
                $users = $this->Order->User->find('list');
                $stores = $this->Order->Store->find('list');
                $storeOrders = $this->Order->StoreOrder->find('list');
                $this->set(compact('users', 'stores', 'storeOrders'));
        }


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

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

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

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

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

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

        public function all() {
                $orderFilters = $this->getOrderFilters("monitor");
                $page = $this->request->query('page');
                $filter = $this->request->query('filter');
                $page = isset($page)?$page:1;
                // $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->layout = "innerpages";
                $url = $this->apihost."orders/?page=$page&window=20";
                if (!empty($filter)) $url .= "&filter=".$filter."&filtertype=monitor";
                $response = $this->make_request($url,null);
                $this->log(print_r($response,1), 'orderresponse');
                $totalPages = $response['totalPages'];          
                if(!empty($response['data'])){
                        $this->set('orders',$response['data']);
                }
                $ignoredFields = array('imgUrl','status','productTitle','estimatedDeliveryDate','productCode','merchantSubOrderId','productUrl','closed','tracingkUrl','detailedStatus');
                $storemapping = Configure::read('storemapping');
                $activestores = Configure::read('activestores');
                $amazonorderurl = Configure::read('amazonorderurl');
                $allusers = $this->Order->User->find('all',array('fields'=>array('first_name','id'),'recursive'=>-1));
                foreach($allusers AS $user){
                        $users[$user['User']['id']] = $user['User']['first_name'];
                }
                $this->layout = 'admin';
                $this->set(compact('ignoredFields','page','totalPages','userId','activestores','storemapping','amazonorderurl','users', 'orderFilters', 'type'));
        }

        public function monitor() {
                $orderFilters = $this->getOrderFilters("monitor");
                $page = $this->request->query('page');
                $filter = $this->request->query('filter');
                if(!empty($this->request->query('requiredetail'))){
                                $orderId=$this->request->query('requiredetail');
                }
                $page = isset($page)?$page:1;
                $this->layout = "innerpages";
                $url = $this->apihost."orders/?page=$page&window=20";
                $apihost = 'http://104.200.25.40:8057/';
                if (!empty($filter)) $url .= "&filter=".$filter."&filtertype=monitor";
                $response = $this->make_request($url,null);
                $totalPages = $response['totalPages'];          
                if(!empty($response['data'])){
                        $this->set('orders',$response['data']);
                }
                $ignoredFields = array('imgUrl','status','productTitle','estimatedDeliveryDate','productCode','merchantSubOrderId','productUrl','closed','tracingkUrl','detailedStatus');
                $storemapping = Configure::read('storemapping');
                $activestores = Configure::read('activestores');
                $amazonorderurl = Configure::read('amazonorderurl');
                $allusers = $this->Order->User->find('all',array('fields'=>array('first_name','id'),'recursive'=>-1));
                foreach($allusers AS $user){
                        $users[$user['User']['id']] = $user['User']['first_name'];
                }
                $this->layout = 'admin';
                $this->set(compact('ignoredFields','page','totalPages','userId','activestores','storemapping','amazonorderurl','users', 'orderFilters', 'filter', 'apihost'));
        }
        
        public function orderdetail(){
                $orderId = $this->request->query('order_id');
                $userId = $this->Auth->User('id');
                $next = "order/".$orderId;                                      
                $redirectUrl = $this->getAutoLoginUrl($userId,$next);
                $this->layout = "innerpages";
                $this->log($redirectUrl,'headers');
                $this->set(compact('redirectUrl','next'));
        }
}