<?php
App::uses('AppController', 'Controller');
class CompaignsController extends AppController {

/**
 * Controller name
 *
 * @var string
 */
	public function index(){
		//$this->gradPermission(4);
		
		$inactive_campaign = $this->Compaign->find('list', array('fields'=>array('id'), 'conditions'=>array('Compaign.status'=>ACTIVE, 'Compaign.end_date <' =>date('Y-m-d')))); 
		
		if(!empty($inactive_campaign)){
			$this->Compaign->updateAll(
				array('Compaign.status' =>INACTIVE),
				array('Compaign.id' => $inactive_campaign)
			);
		}
		
		$conditions = array();
		//$conditions = array('Compaign.status != ' => DELETED);
		
		if(!empty($this->request->query['status'])){
			
			if($this->request->query['status'] == 'Active'){
				$conditions['Compaign.status']= 1;
			}else{
				$conditions['Compaign.status']= 0;
			}
		}
		
		$order = $this->paginate['order'] = array('Compaign.start_date' => 'desc', 'Compaign.end_date' => 'desc', 'Compaign.title' => 'asc');
		
		$querystring = $this->request->query;
		$this->set(compact('querystring'));
		if(isset($this->request->query['export'])){ 
			if(!empty($this->request->query['offset'])){
				$offset = (int) $this->request->query['offset'];
				if($offset > 10000){
					$offset = 0;
				}
			}else{
				$offset = 0;
			}
				
			$joins = isset($this->paginate['joins']) ? $this->paginate['joins'] : array();		
			$compaigns = $this->Compaign->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));
  		} else {
		    $compaigns = $this->paginate('Compaign', $conditions);
		}
		$this->set(compact('offset'));
		$this->set('compaigns', $compaigns);
		if(isset($this->request->query['export'])){  
			$this->set('filename','campaigns'); 
			$this->render('export_campaigns','export_xls');
		}
	}
	public function add(){
		//$this->gradPermission(1);
		
		if ($this->request->data){
			//pr($this->data);
			
			$is_exists = $this->Compaign->find('count', array('conditions'=>array('LOWER(Compaign.title)'=>strtolower($this->request->data['Compaign']['title']))));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['Compaign']['title']));
			}else{
				$compaign = $this->Compaign->save($this->request->data);
				if ($this->request->data['Compaign']['depot_id']){
					$data = array();
					foreach ($this->request->data['Compaign']['depot_id'] as $depot_id){
						$data[] = array('compaign_id'=>$compaign['Compaign']['id'], 'depot_id'=>$depot_id);
					}
					
					$this->loadModel('CompaignsDepot');
					$this->CompaignsDepot->primaryKey = null;
					@$this->CompaignsDepot->saveAll($data, false);
				}
				
				if ($this->request->data['Compaign']['region_id']){
					$rdata = array();
					foreach ($this->request->data['Compaign']['region_id'] as $region_id){
						$rdata[] = array('compaign_id'=>$compaign['Compaign']['id'], 'region_id'=>$region_id);
					}
					$this->loadModel('CompaignsRegion');
					$this->CompaignsRegion->primaryKey = null;
					@$this->CompaignsRegion->saveAll($rdata, false);
				}
				
				$this->Session->setFlash(__('Compaign was added sucessfully'));
				$this->redirect(array('action'=>'index'));
			}
		}
		
		$this->loadModel('Brand');
		$this->loadModel('Region');
		$brands = $this->Brand->find('list', array('fields'=>array('id', 'name'), 'order'=>array('name'=>'asc')));
		$regions = $this->Region->find('list', array('fields'=>array('id', 'title'), 'order'=>array('title'=>'asc')));
		$this->set(compact('brands', 'regions'));
		
	}
	
	public function edit($id=0){
		$this->loadModel('Audit');
		$userData = $this->Compaign->read(null, $id);
	//	$this->gradPermission(1);
		/*
		$this->gradPermission(1);
		$this->Compaign->id = $id;
        if (!$this->Compaign->exists()) {
            throw new NotFoundException(__('Invalid Compaign'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->Compaign->save($this->request->data)) {
				$this->Session->setFlash(__('The compaign has been updated'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The compaign could not be saved. Please, try again.'));
			}
		}else {
            $this->request->data = $this->Compaign->read(null, $id);
			$this->_options();
			$this->render('add');
        }
	*/
	
	
	
	
		if ($this->request->data){
			$is_exists = $this->Compaign->find('count', array('conditions'=>array('LOWER(Compaign.title)'=>strtolower($this->request->data['Compaign']['title']), 'Compaign.id !=' => $id)));
			if ($is_exists > 0){
				$this->Session->setFlash(__('"%s" already exists', $this->request->data['Compaign']['title']));
			}else{
				$this->Compaign->save($this->request->data);
				if ($this->request->data['Compaign']['depot_id']){
					$data = array();
					foreach ($this->request->data['Compaign']['depot_id'] as $depot_id){
						$data[] = array('compaign_id'=>$id, 'depot_id'=>$depot_id);
					}
					
					$this->loadModel('CompaignsDepot');
					$this->CompaignsDepot->primaryKey = null;
					$this->CompaignsDepot->deleteAll(array('compaign_id'=>$id), false);
					//pr($data);
					
					@$this->CompaignsDepot->saveAll($data, array());
					
				}
				
				if ($this->request->data['Compaign']['region_id']){
					$rdata = array();
					foreach ($this->request->data['Compaign']['region_id'] as $region_id){
						$rdata[] = array('compaign_id'=>$id, 'region_id'=>$region_id);
					}
					
					$this->loadModel('CompaignsRegion');
					$this->CompaignsRegion->primaryKey = null;
					$this->CompaignsRegion->deleteAll(array('compaign_id'=>$id), false);
					@$this->CompaignsRegion->saveAll($rdata);
				
				}
				$this->Audit->saveDeletedData($userData['Compaign']['id'], 'Compaign', $this->Auth->user('id') , serialize($userData),'Compaign Has been updated', STATUS_EDIT);
				$this->Session->setFlash(__('Compaign was updated sucessfully'));
				$this->redirect(array('action'=>'index'));
				
			}
		}
		
		if (!empty($id)){
			$this->Compaign->id = $id;
			$this->request->data = $this->Compaign->read();
			$region_ids = array();
			if ($this->request->data['Region']){
				
				foreach ($this->request->data['Region'] as $regions){
					$region_ids[] = $regions['id'];
				}
			}
			$this->request->data['Compaign']['region_id'] = $region_ids;
			$depot_ids = array();
			if ($this->request->data['Depot']){
				
				foreach ($this->request->data['Depot'] as $depots){
					$depot_ids[] = $depots['id'];
				}
			}
			$this->request->data['Compaign']['depot_id'] = $depot_ids;
			//pr($this->request->data);
		}
		$this->loadModel('Brand');
		$this->loadModel('Region');
		$this->loadModel('Depot');
		$brands = $this->Brand->find('list', array('fields'=>array('id', 'name'), 'order'=>array('name'=>'asc')));
		$regions = $this->Region->find('list', array('fields'=>array('id', 'title'), 'order'=>array('title'=>'asc')));
		$depots = $this->Depot->find('list', array('fields'=>array('id', 'title'), 'conditions'=>array('region_id'=>$region_ids), 'order'=>array('title'=>'asc')));
		$this->set(compact('brands', 'regions', 'depots'));
		//$this->render('add');
		
	
	
	}
	
	
	public function delete($id=0){
	//	$this->gradPermission(1);
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		if(!$id){
			$this->redirect('/cmpaigns');
		}
		$this->Compaign->id = $id;
		$compaign = $this->Compaign->read();//pr($compaign);die();

		$data = array();
		$data['serialize'] = serialize($compaign);
		$data['model_id'] = $compaign['Compaign']['id'];
		$this->Compaign->id = $id;
		$this->Compaign->delete();
		$this->loadModel('Audit');
			$this->Audit->saveDeletedData($data['model_id'], 'Compaign', $this->Auth->user('id') , $data['serialize'],'Compaign Has been Deleted',STATUS_DELETE);
		$this->Session->setFlash(__('Compaign was deleted sucessfully'));
		$this->redirect(array('action'=>'index'));
	}
	
	function _options(){
		$this->loadModel('Region');
		$this->loadModel('Depot');
		$this->loadModel('Brand');
		
		$depots = $this->Depot->getList();
		$regions = $this->Region->getList();
		$brands = $this->Brand->find('list', array('fields'=>array('id','name')));
		
		$this->set(compact('depots', 'regions','brands'));
	}
	
	function customerCompaigns(){
		$conditions = array('Compaign.status'=>ACTIVE, "'".date('Y-m-d')."' between Compaign.start_date AND Compaign.end_date");
		if( !empty($this->request->data['cId']) ){
			$this->loadModel('Customer');
			$this->Customer->id = $this->request->data['cId'];
			$customer = $this->Customer->read();
			//pr($customer);
			if ($customer){
				$conditions[] = "Compaign.id IN (SELECT compaign_id FROM compaigns_depots WHERE depot_id = ".$customer['Customer']['depot_id'].")";
			}
		}
		$this->Compaign->unbindModel(array('hasAndBelongsToMany' => array('Depot', 'Region')));
		
		$compaigns = $this->Compaign->find('all', array('conditions' => $conditions));
		$compaignArray = array();
		
		if($compaigns){
			foreach($compaigns as $compaign){
				$brandId = $compaign['Compaign']['brand_id'];
				$compaignArray[$brandId][] = $compaign['Compaign'];
			}
		}
		$this->set(compact('compaigns', 'compaignArray', 'customer'));
	}
/**
 * activeCompaign method
 * get active compaign
 */
	function activeCompaign(){
		$compaigns = $this->Compaign->find('all', array('conditions'=>array('Compaign.status'=>ACTIVE, "'".date('Y-m-d')."' between Compaign.start_date AND Compaign.end_date")));
		$this->set('compaigns', $compaigns);
	}
	public function getDepotOptions(){
		$result = array();
		if (!empty($this->data['regionIds'])){
			$this->loadModel('Depot');
			
			$depots = $this->Depot->find('list', array('conditions'=>array('region_id'=>$this->data['regionIds'])));
			$result['options'] = $depots;
		}
		echo json_encode($result);
		exit;
	}
	
	public function getActiveCompaigns(){
		$conditions = array('Compaign.status'=>ACTIVE, "'".date('Y-m-d')."' between Compaign.start_date AND Compaign.end_date");
		$joins = array();
		switch($this->user['Role']['grade']){
			case 3:
				$joins = array(array('table'=>'compaigns_regions', 'alias'=>'CompaignsRegion', 'type'=>'inner', 'conditions'=>array('Compaign.id = CompaignsRegion.compaign_id AND region_id = '.$this->user['region_id']))); 
			break;
			case 4:
			case 5:
			case 6:
				$joins = array(array('table'=>'compaigns_depots', 'alias'=>'CompaignsDepot', 'type'=>'inner', 'conditions'=>array('Compaign.id = CompaignsDepot.compaign_id AND depot_id = '.$this->user['depot_id']))); 
			break;
		}
		$this->paginate['order'] = array('Compaign.title' => 'asc');
		$this->paginate['joins'] = $joins;
		$compaigns = $this->paginate('Compaign', $conditions);
		$this->set('compaigns', $compaigns);
	}

	/**
	 * orderdelete action
	 */
	 public function orderdelete($id){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		$this->loadModel('Compaign');
        $this->Order->id = $id;
		$order = $this->Order->read();
        if (!$order) {
            throw new NotFoundException(__('Invalid Order'));
        }
		//$this->loadModel('Customer');
		//$this->Customer->id = $order['Order']['customer_id'];
		//$depot_id = $this->Customer->field('depot_id');
		//$sales = $this->Sale->find('all', array('conditions'=>array('order_id'=>$id)));
		
		//$this->loadModel('FreeItem');
		//$stockStatus = array();
		
		if ($this->Order->delete()){
			//if ($stockStatus){
			//	$this->Sale->updateStockStatus($stockStatus);
			//}
			$this->Session->setFlash(__('Compaign was deleted'));
			$this->redirect(array('action' => 'index'));
		}
	}
	
	public function deleteAllCampaigns(){
		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
		$this->loadModel('Compaign');
		if(!empty($this->request->data['deleteAllValue'])){
			$this->Compaign->deleteAll(array('Compaign.id'=>explode(",", $this->request->data['deleteAllValue'])) );
			$this->Session->setFlash(__('All selected Compaign was deleted successfully') );
			$this->redirect(array('action'=>'index'));
		}
		exit;
	}
 }