<?php
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
class RedistributorsController extends AppController {

    /**
     * Controller name
     *
     * @var string
     */
    var $components = array('FileUpload' => array(
        'allow_non_image_files' => false
    ),'Option');
    public function index(){

        $conditions = array('Redistributor.status !=' => DELETED);
        if (!empty($this->request->query['q']) ){
            $conditions['OR']['Redistributor.first_name LIKE'] =  '%'.$this->request->query['q'].'%';
            $conditions['OR']['Redistributor.last_name LIKE'] =  '%'.$this->request->query['q'].'%';
        }
        if (!empty($this->request->query['st']) ){
            $conditions['Redistributor.state_id'] = $this->request->query['st'];
        }
        if(!empty($this->request->query['dv']) && empty($this->request->query['rg']) && empty($this->request->query['dp'])){
            $divisionRegion = ClassRegistry::init('DivisionsRegion');
            $rIds = $divisionRegion->find('list', array('fields' => array('region_id'), 'conditions' => array('division_id' =>$this->request->query['dv'])));
            $conditions['Redistributor.region_id IN'] = $rIds;
        }
        if (!empty($this->request->query['rg']) ){
            $conditions['Redistributor.region_id'] = $this->request->query['rg'];
        }
        if (!empty($this->request->query['dp']) ){
            $conditions['Redistributor.depot_id'] = $this->request->query['dp'];
        }

        $this->_userCondition($conditions);
        $order = $this->paginate['order'] = array('Redistributor.first_name'=>'asc', 'Redistributor.last_name'=>'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();
            $redistributors = $this->Redistributor->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));

            $redistributors = $this->Redistributor->find('all',array('conditions'=>$conditions));

        } else {
            $redistributors = $this->paginate('Redistributor', $conditions);
        }
        $this->set('redistributors', $redistributors);
        $this->_selectOptions();
        $this->set(compact('offset'));
        if(isset($this->request->query['export'])){
            $this->set('filename', 'Redistributor');
            $this->render('export_index','export_xls');
        }
    }
    function _userCondition(&$conditions){
        switch($this->user['Role']['grade']){
            case 3:
                $conditions['Redistributor.region_id'] = $this->user['region_id'];
                break;
            case 4:
            case 5:
            case 6:
                $conditions['OR']['Redistributor.region_id'] = $this->user['region_id'];
                $conditions['OR']['Redistributor.depot_id'] = $this->user['depot_id'];
                break;

        }
    }


    public function add(){
        //$this->gradPermission(1);
        if ($this->request->data){
            $is_exists = 0;
            if(empty($this->request->data['Redistributor']['depot_id'])){
                $this->request->data['Redistributor']['depot_id'] = $this->Auth->user('depot_id');
            }
            if(empty($this->request->data['Redistributor']['region_id'])){
                $this->request->data['Redistributor']['region_id'] = $this->Auth->user('region_id');
            }
            if (!empty($this->request->data['Redistributor']['email'])){
                $is_exists = $this->Redistributor->find('count', array('conditions'=>array('LOWER(Redistributor.email)'=>strtolower($this->request->data['Redistributor']['email']), 'Redistributor.depot_id'=>$this->request->data['Redistributor']['depot_id'])));
            }
            if ($is_exists > 0){
                $this->Session->setFlash(__('This customer already exists in selected depot'));
            }else{
                $image_ok = true;

                if (!empty($this->request->data['Redistributor']['image']['name'])){
                    if ($this->FileUpload->upload($this->request->data['Redistributor'],'image')) {
                        $this->request->data['Redistributor']['file_id'] = $this->FileUpload->fileId;
                    } else {
                        $image_ok = false;
                    }
                }
                if ($image_ok){
                    $this->request->data['Redistributor']['user_id'] = $this->Auth->user('id');
                    $this->Redistributor->save($this->request->data);
                    $this->Session->setFlash(__('Redistributor was added sucessfully'));
                    $this->redirect(array('action'=>'index'));
                }
            }
        }
        $this->_selectOptions();
    }

    public function edit($id=0){
        $this->loadModel('Audit');
        $this->roleBasePermission(array(SUPPORT));
        //$set_var=$this->gradPermission(1);
        $userData = $this->Redistributor->read(null, $id);
        if(!$id){
            $this->redirect(array('action'=>'index') );
        }
        if ($this->request->data){
            $is_exists = 0;
            if(empty($this->request->data['Redistributor']['depot_id'])){
                $this->request->data['Redistributor']['depot_id'] = $this->Auth->user('depot_id');
            }
            if(empty($this->request->data['Redistributor']['region_id'])){
                $this->request->data['Redistributor']['region_id'] = $this->Auth->user('region_id');
            }
            if (!empty($this->request->data['Redistributor']['email'])){
                $is_exists = $this->Redistributor->find('count', array('conditions'=>array('LOWER(Redistributor.email)'=>strtolower($this->request->data['Redistributor']['email']), 'Redistributor.depot_id'=>$this->request->data['Redistributor']['depot_id'], 'Redistributor.id !='=>$id)));
            }
            if ($is_exists > 0){
                $this->Session->setFlash(__('This customer email already associated with another customer in selected depot'));
            }else{
                $image_ok = true;

                if (!empty($this->request->data['Redistributor']['image']['name'])){
                    if ($this->FileUpload->upload($this->request->data['Redistributor'],'image')) {
                        $this->request->data['Redistributor']['file_id'] = $this->FileUpload->fileId;
                        if ($this->request->data['Redistributor']['oldFile_id']){
                            $this->FileUpload->removeFileId($this->request->data['Redistributor']['oldFile_id']);
                        }
                    } else {
                        $image_ok = false;
                    }
                }
                if ($image_ok){
                    $this->request->data['Redistributor']['user_id'] = $this->Auth->user('id');
                    $this->Redistributor->save($this->request->data);
                    $this->Audit->saveDeletedData($userData['Redistributor']['id'], 'Redistributor', $this->Auth->user('id') , serialize($userData),'Redistributor Has been updated', STATUS_EDIT);
                    $this->Session->setFlash(__('Redistributor was updated sucessfully'));
                    $this->redirect(array('action'=>'index'));
                }

            }
        }else{

            $this->Redistributor->id = $id;
            $this->request->data = $this->Redistributor->read();
        }
        $this->_selectOptions();
        //	if($set_var){
        $this->render('add');
        //}
    }

    /**
     * view method
     *
     * @param string $id
     * @return void
     */

    public function view($id = null){
        $this->Redistributor->id = $id;
        if (!$this->Redistributor->exists()) {
            throw new NotFoundException(__('Invalid redistributor'));
        }
        $this->set('redistributor', $this->Redistributor->read(null, $id));
    }

    /**
     * delete method
     *
     * @param string $id
     * @return void
     */
    public function delete($id = null) {
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->Redistributor->id = $id;
        $redistributor = $this->Redistributor->read();
        if (!$redistributor) {
            throw new NotFoundException(__('Invalid Redistributor'));
        }
        $data = array();
        $data['serialize'] = serialize($redistributor);//pr($data['serialize']);die();
        $data['model_id'] = $redistributor['Redistributor']['id'];
        if ($this->Redistributor->delete()) {
            $this->loadModel('Audit');
            if ($redistributor['Redistributor']['file_id']){
                $this->FileUpload->removeFileId($redistributor['Redistributor']['file_id']);
            }
            $this->Audit->saveDeletedData($data['model_id'], 'Redistributor', $this->Auth->user('id') , $data['serialize'],'Redistributor Has been Deleted',STATUS_DELETE);
            $this->Session->setFlash(__('Redistributor was deleted successfully'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Redistributor was not deleted'));
        $this->redirect(array('action' => 'index'));
    }


    function _selectOptions(){
        /*$this->loadModel('State');
        $this->loadModel('Depot');
        $this->loadModel('Region');
        $this->loadModel('LgArea');
        $states = $this->State->find('list', array('fields'=>array('id','state'), 'order'=>array('state'=>'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'), 'order'=>array('title'=>'asc')));
        $lgAreas = $this->LgArea->find('list', array('fields'=>array('id','name'), 'order'=>array('name'=>'asc')));

        $this->set(compact('states','regions','depots','lgAreas'));*/
        $Opdata = isset($this->request->data['Redistributor'] ) ? $this->request->data['Redistributor']  : array();
        $this->Option->Options($Opdata, $this->user);
    }

    /**
     * sales method: listed all redistributor sales
     *
     */
    public function sales(){

        $this->loadModel('RedistributorSale');
		

	
		
		
        $conditions = array();

        if (!empty($this->request->query['q'])){
            //$conditions['OR']['concat_ws(" ", User.first_name, User.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
            $conditions['OR']['concat_ws(" ", Customer.first_name, Customer.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
        }
        if (!empty($this->request->query['usr']) ){
            $conditions['RedistributorSale.user_id'] = $this->request->query['usr'];
        }
		
		if (!empty($this->request->query['cid'])){
            $conditions['RedistributorSale.customer_id'] = $this->request->query['cid'];
        }
		
        if ( !empty($this->request->query['mfrom']) && !empty($this->request->query['mto'])){
            $conditions[] = array('RedistributorSale.modified BETWEEN ? AND ?' => array($this->request->query['mfrom'], $this->request->query['mto']));
        }
		
		if (empty($this->request->query['from'])){
			$this->request->query['from'] = date('Y-m-01');
		}
		
        if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
            $conditions[] = array('RedistributorSale.sale_date BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));

        } elseif (!empty($this->request->query['from'])){
            $conditions['RedistributorSale.sale_date >= '] = $this->request->query['from'];
        } elseif (!empty($this->request->query['to'])){
            $conditions['RedistributorSale.sale_date <= '] = $this->request->query['to'];
        }
		
		$this->paginate['group'] = array('RedistributorSale.id');
		$this->paginate['joins'] = array(array('table'=>'redistributor_saleitems', 'alias'=>'RedistributorSaleitem', 'conditions'=>'RedistributorSale.id=RedistributorSaleitem.redistributor_sale_id'));
		 
		 $depot_id = "";
        if (!empty($this->request->query['dv']) || !empty($this->request->query['dp']) || !empty($this->request->query['rg']) ){
            
           
            if (!empty($this->request->query['dv']) && empty($this->request->query['rg']) && empty($this->request->query['dp']) ) {
                $conditions[] = 'RedistributorSaleitem.depot_id IN (SELECT id from depots WHERE region_id IN (SELECT region_id from divisions_regions WHERE division_id = ' . $this->request->query['dv'] . '))';
            }
            if (!empty($this->request->query['rg']) && empty($this->request->query['dp']) ){
                $conditions[] = 'RedistributorSaleitem.depot_id IN (SELECT id from depots WHERE region_id = '.$this->request->query['rg'].')';
            }
            if (!empty($this->request->query['dp'])){
                $depot_id = $conditions['RedistributorSaleitem.depot_id'] = $this->request->query['dp'];
            }
        }
        if (isset($this->request->query['sts'])&& $this->request->query['sts']!=''){
            $conditions['RedistributorSale.status'] = $this->request->query['sts'];
        }
		
		if (isset($this->request->query['via_app']) && $this->request->query['via_app']!='' ){
            $conditions['RedistributorSale.via_app'] = $this->request->query['via_app'];
        }

        //Not On Day Route 
        if (isset($this->request->query['not_on_day_route']) && $this->request->query['not_on_day_route'] == 1 ){
            $conditions['RedistributorSale.not_on_day_route'] = $this->request->query['not_on_day_route'];
        }
		
        $this->RedistributorSale->_userSalesCondition($conditions, $this->user);
        $order = $this->paginate['order'] = array('RedistributorSale.sale_date' => 'desc', 'RedistributorSale.created' => 'desc');
		
		$joins = isset($this->paginate['joins']) ? $this->paginate['joins'] : array(); 
		
		$totals = $this->RedistributorSale->find('all', array('fields'=>array('SUM(RedistributorSaleitem.amount) AS totalAmount', 'SUM(RedistributorSaleitem.cal_qty) AS totalCalQty'), 'conditions'=>$conditions,'joins'=>$joins)); //pr($totals );

        $querystring = $this->request->query;

        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;
            }

            
            $rdsales = $this->RedistributorSale->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));

        } else {
            $rdsales = $this->paginate('RedistributorSale', $conditions);
        }

         $this->set(compact('querystring','rdsales', 'totals'));
        /* $this->loadModel('Division');
        $this->loadModel('Depot');
        $depots = $this->Depot->getList();
        $this->loadModel('Region');
        $divisions = $this->Division->find('list', array('fields'=>array('id','title'), 'order'=>array('title'=>'asc')));
        $regions = $this->Region->find('list', array('fields'=>array('id','title'), 'order'=>array('title'=>'asc'))); */
		
		$Opdata =  array();
		$param = isset($querystring ) ? $querystring  : array();
		$this->Option->Options($Opdata, $this->user,$param);
		
		$this->loadModel('User');
		$users = $this->User->usersList($depot_id);
		
        $this->set(compact('offset', 'users'));

        if(isset($this->request->query['export'])){
            $this->set('filename','sales');
            $this->render('export_sales','export_xls');
        }
    }

    public function addsale(){
        $this->loadModel('RedistributorSale');
        $this->loadModel('Sale');
        $this->loadModel('Brand');
        if ($this->request->data){
            $data = $stockStatus = array();

            $totalBrands = count( $this->request->data['brand_id'] );

            if( ($totalBrands != count(array_filter($this->request->data['unit']))) || empty($this->request->data['unit_price']) || ($totalBrands != count(array_filter($this->request->data['unit_price']))) || ($totalBrands != count(array_filter($this->request->data['qty']))) )
            {
                $this->Session->setFlash(__('Something missing, Please check your sale data entry table'));
            }
            else
            {
                $orderData = array('redistributor_id' => $this->request->data['RedistributorSale']['redistributor_id'], 'customer_id' => $this->request->data['RedistributorSale']['customer_id'], 'sale_date'=>$this->request->data['RedistributorSale']['sale_date'], 'user_id'=>$this->user['id'], 'items'=>count($this->request->data['brand_id']), 'total' => $this->request->data['grand_total'] );

                $order = $this->RedistributorSale->save($orderData);

                $this->loadModel('Customer');
                $this->Customer->id = $this->request->data['RedistributorSale']['customer_id'];
                $depot_id = $this->Customer->field('depot_id');

                //Get customer's depot_id
                $customer = $this->Customer->findById($this->request->data['RedistributorSale']['customer_id']);

                $this->Customer->verify_status($this->request->data['RedistributorSale']['customer_id']);
                $order_id = $order['RedistributorSale']['id'];

                /*****----- Check if entry is on correct route -----*****/
                /* $uid = $order['RedistributorSale']['user_id']; 
                $date = date('Y-m-d', strtotime($order['RedistributorSale']['sale_date']));
                
                $this->loadModel('Route');
                $userDayRouteIds = $this->Route->getUserDayRouteIds($uid,$date); 
                
                if(!empty($userDayRouteIds)){
                    if (!in_array($customer['Customer']['route_id'],$userDayRouteIds)){
                        // Customer's route_id is not in $userDayRouteIds array
                        $this->RedistributorSale->id = $order_id ;
                        $this->RedistributorSale->saveField('not_on_day_route', 1);
                        
                        // find routes title
                        $userDayRoutes = $this->Route->find('list', array('fields' => array('id', 'title'), 'conditions' => array('id' => $userDayRouteIds)));
                        
                        //Send notifying email
                        ### Email  ###
                            $email = new CakeEmail('smtp');
                            $email->from(array('support@drupway.com'=> 'Y3 Support'));
                            $email->to(array('drupwaycrm@gmail.com','y3hqfin@fastmail.fm')); //y3hqfin@fastmail.fm = Anya
                            $email->emailFormat('html');
                            $email->subject("Y3 CRM ALERT - Redistributor Sale entry on a day other than the user's day routes.");
                            $email->viewVars(array('model' => 'RedistributorSale', 'data' => $order, 'customer'=> $customer, 'username' => $this->user['username'], 'userDayRoutes' => $userDayRoutes));
                            $email->template('entry_on_different_route');
                            $email->send('entry_on_different_route'); 
                        ### ----------------------------------------------------- ###
                    }
                } */
                /*****------------------------------------*****/

                foreach ($this->request->data['brand_id'] as $key => $val ){
                    $stockStatus[$val]['entity_id'] = $depot_id;
                    $stockStatus[$val]['entity'] = 'Depot';

                    //Check  brand model is loaded
                    $group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$val)));
					
					$stockStatus[$val]['brand_group_id'] = $group_id[$val];

                    $data[] = array(
                        'brand_id'=> $val,
                        'brand_group_id' =>$group_id[$val],
                        'redistributor_sale_id'=> $order_id,
                        'redistributor_id' => $this->request->data['RedistributorSale']['redistributor_id'],
                        'user_id'=>$this->user['id'],
                        'depot_id'=>$depot_id,
                        'customer_id'=>$this->request->data['RedistributorSale']['customer_id'],
                        'sale_date'=>$this->request->data['RedistributorSale']['sale_date'],
                        'unit'=>$this->request->data['unit'][$key],
                        'unit_price'=>$this->request->data['unit_price'][$key],
                        'quantity' =>$this->request->data['qty'][$key],
                        'cal_qty' => $this->Sale->calQty($val, $this->request->data['unit'][$key], $this->request->data['qty'][$key]),
                        'amount'=>$this->request->data['amount'][$key]
                    );


                }
                //Free Data
                $this->loadModel('RedistributorSaleitem');
                $this->loadModel('RdFreeItem');
                $freeData = array();
                if (!empty($this->request->data['freeItem'])){

                    foreach ($this->request->data['freeItem']['brand_id'] as $key => $val ){

                        //Check  brand model is loaded
                        $group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$val)));


                        $freeData[] = array(
                            'redistributor_sale_id' => $order_id,
                            'brand_id' => $val,
                            'brand_group_id' =>$group_id[$val],
                            'depot_id'=>$depot_id,
                            'sale_date' => $this->request->data['RedistributorSale']['sale_date'],
                            'unit' => $this->request->data['freeItem']['unit'][$key],
                            'quantity' => $this->request->data['freeItem']['quantity'][$key],
                            'compaign_id' => $this->request->data['freeItem']['compaign_id'][$key],
                            'cal_qty' => $this->Sale->calQty($val, $this->request->data['freeItem']['unit'][$key], $this->request->data['freeItem']['quantity'][$key])
                        );


                    }
                }
                if ($data){
                    $this->RedistributorSaleitem->saveAll($data);
                    if ($freeData){
                        $this->RdFreeItem->saveAll($freeData);
                    }


                    $this->Session->setFlash(__('Redistributor Sales was saved successfully'));
                    $this->redirect(array('action'=>'sales'));

                }
            }
        }

        $this->_options();

    }

    function _options(){
        $this->loadModel('Customer');
        $this->loadModel('Brand');
        $customers = $this->Customer->customerListByRole($this->user);

        $brands = $this->Brand->find('all', array(''));
        $brandList = array();
        $brandsObj = array();
        foreach ($brands as $brand ){
            $brandList[$brand['Brand']['id']] = $brand['Brand']['name'];
            $brankdsObj['b'.$brand['Brand']['id'].'b'] = array('Case' => $brand['Brand']['rd_case_price'], 'Roll' => $brand['Brand']['rd_roll_price'],'Pack' => $brand['Brand']['rd_pack_price'], '2Pack' => $brand['Brand']['rd_2pack_price']);
        }
        //Get All active compaign
        $this->loadModel('Compaign');
        $compaigns = $this->Compaign->find('all', array('conditions'=>array('Compaign.status'=>ACTIVE, "'".date('Y-m-d')."' between Compaign.start_date AND Compaign.end_date")));
        $compaignArray = array();
        if($compaigns){

            foreach($compaigns as $compaign){
                $cId = $compaign['Compaign']['id'];
                $compaignArray[$cId] = $compaign['Compaign'];
            }
        }

        $redistributors = $this->Redistributor->redistributorListByRole($this->user);
        $this->set( compact('customers','brands', 'brandList','brankdsObj','compaignArray', 'redistributors'));
    }

    /**
     * rdsaleview method
     *
     */
    public function rdsaleview($id){
        $this->loadModel('RedistributorSale');
        $this->loadModel('RedistributorSaleitem');

       /*  $this->RedistributorSale->belongsTo = array(
            'User' => array('className' => 'User', 'foreignKey' => 'user_id', 'fields' => array('first_name', 'last_name'), 'type'=>'inner'),
            'Customer' => array('className' => 'Customer', 'foreignKey' => 'customer_id', 'fields' => array('id', 'first_name','last_name'), 'type'=>'inner'),
            'Redistributor' => array('className' => 'Redistributor', 'foreignKey' => 'redistributor_id', 'fields' => array('id', 'first_name','last_name'), 'type'=>'inner'),
            'VerifyBy' => array('className' => 'User', 'foreignKey' => 'verify_by', 'fields' => array('first_name', 'last_name'), 'type'=>'left')
        ); */
        $this->RedistributorSale->id = $id;
        $order = $this->RedistributorSale->read(); //pr($order);
       /*  $joins1 = array(array('table'=>'brands', 'alias' => 'Brand', 'type'=>'inner', 'conditions' => 'Brand.id = RedistributorSaleitem.brand_id')); 

        $sales = $this->RedistributorSaleitem->find('all', array('conditions' => array('redistributor_sale_id'=>$id),'fields'=>array('RedistributorSaleitem.*', 'Brand.name'), 'joins'=>$joins1 ));
        $this->loadModel('RdFreeItem');
         $joins = array(array('table'=>'brands', 'alias' => 'Brand', 'type'=>'inner', 'conditions' => 'Brand.id = RdFreeItem.brand_id'));
        $freeItems = $this->RdFreeItem->find('all', array('fields'=>array('RdFreeItem.*', 'Brand.name'), 'conditions'=>array('redistributor_sale_id' => $id), 'joins'=>$joins)); */
        $this->set(compact('order', 'sales', 'freeItems'));
    }


    /*rdsaleedit method*/
    /** Task : introduced rdsaleedit 26-5-2025**/
    public function rdsaleedit($id=0){
        if ($this->request->data){
            //pr($this->request->data);die();

            $this->loadModel('RedistributorSaleitem');
            $this->loadModel('Sale');
            $this->loadModel('Customer');
            $this->loadModel('RdFreeItem');
            $this->loadModel('Brand');
            $this->loadModel('RedistributorSale');

            $data = $stockStatus = array();
            $this->RedistributorSale->id = $id;
			$this->RedistributorSale->bindModel(
            array(
            'belongsTo'=>array(
                'User' => array('className' => 'User', 'foreignKey' => 'user_id', 'fields' => array('first_name', 'last_name', 'role_id'), 'type'=>'inner'),
            )));
        
			$AuditData = $this->RedistributorSale->read();
			
            $totalBrands = count( $this->request->data['brand_id'] );
            
            if(($totalBrands != count(array_filter($this->request->data['unit']))) || ($totalBrands != count(array_filter($this->request->data['qty']))))
            {               
                $this->Session->setFlash(__('Something missing, Please check your sale data entry table'));
            }
            else{
                    $order_total = $this->RedistributorSale->find('all', array('conditions'=>array('RedistributorSale.id'=>$id)));
                    $total_grnd = $order_total[0]['RedistributorSale']['total'];

                    if(empty($this->request->data['grand_total'])){
                        $gtotal = $total_grnd;
                    }else{
                        $gtotal = $this->request->data['grand_total'];
                    }

                // Start transaction
                $this->RedistributorSale->getDataSource()->begin();
                try {
                    $this->RedistributorSaleitem->deleteAll(array('redistributor_sale_id'=>$id), false);
                    $this->RdFreeItem->deleteAll(array('redistributor_sale_id'=>$id), false);
                    
                    $orderData = array('id'=>$id, 'redistributor_id' => $this->request->data['RedistributorSaleitem']['redistributor_id'],'customer_id' => $this->request->data['RedistributorSaleitem']['customer_id'],'user_id'=>$this->request->data['RedistributorSaleitem']['user_id'],'sale_date'=>$this->request->data['RedistributorSaleitem']['sale_date'], 'items'=>count($this->request->data['brand_id']), 'total' => $gtotal,'modified'=>  date('Y-m-d H:i:s'));


                    //pr($orderData); die();
                    $order = $this->RedistributorSale->save($orderData);
                    $order_id = $order['RedistributorSale']['id'];
                    $created = $order['RedistributorSale']['created'];

                    $this->Customer->id = $this->request->data['RedistributorSaleitem']['customer_id'];
                    $depot_id = $this->Customer->field('depot_id');

                    $this->Customer->verify_status($this->request->data['RedistributorSaleitem']['customer_id']);

                    foreach ($this->request->data['brand_id'] as $key => $val ){
                
                        $stockStatus1[$val]['entity_id'] = $depot_id;
                        $stockStatus1[$val]['entity'] = 'Depot';

                        $group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$val)));

                        $stockStatus[$val]['brand_group_id'] = $group_id[$val];

                        
                        $data[] = array(
                            'brand_id'=> $val,
                            'brand_group_id' =>$group_id[$val],
                            'redistributor_sale_id'=> $order_id,
                            'redistributor_id' => $this->request->data['RedistributorSaleitem']['redistributor_id'],
                            'user_id'=>$order['RedistributorSale']['user_id'],
                            'depot_id'=>$depot_id, 
                            'customer_id'=>$this->request->data['RedistributorSaleitem']['customer_id'],
                            'sale_date'=>$this->request->data['RedistributorSaleitem']['sale_date'],
                            'unit'=>$this->request->data['unit'][$key], 
                            'unit_price'=>$this->request->data['unit_price'][$key],
                            'quantity' =>$this->request->data['qty'][$key], 
                            'cal_qty' => $this->Sale->calQty($val, $this->request->data['unit'][$key], $this->request->data['qty'][$key]), 
                            'amount'=>$this->request->data['amount'][$key],
                            'created'=>$created
                        );
                    
                        $unit = strtolower($this->request->data['unit'][$key]);
                        @$stockStatus[$val][$unit] += $this->request->data['qty'][$key];

                    }
                    //Free Data
                    $freeData = array();
                    if (!empty($this->request->data['freeItem'])){

                        
                        foreach ($this->request->data['freeItem']['brand_id'] as $key => $val ){

                            $group_id = $this->Brand->find('list', array('fields'=> array('id','brand_group_id'), 'conditions'=>array('Brand.id'=>$val)));

                            $freeData[] = array(
                                'redistributor_sale_id' => $order_id,
                                'brand_group_id' =>$group_id[$val],
                                'brand_id' => $val,
                                'user_id'=>$order['RedistributorSale']['user_id'],
                                'depot_id'=>$depot_id,
                                'sale_date' =>$this->request->data['RedistributorSaleitem']['sale_date'],
                                'unit' => $this->request->data['freeItem']['unit'][$key],
                                'quantity' => $this->request->data['freeItem']['quantity'][$key],
                                'compaign_id' => $this->request->data['freeItem']['compaign_id'][$key],
                                'created'=>$created,
                                'cal_qty' => $this->Sale->calQty($val, $this->request->data['freeItem']['unit'][$key], $this->request->data['freeItem']['quantity'][$key])
                            );
                            
                        }
                    }

                    if (!empty($data)){ //pr($data);die();
                        if (!$this->RedistributorSaleitem->saveAll($data)) {
                            throw new Exception(__('Failed to save sale data.'));
                        }
                        
                        if ($freeData){
                            if (!$this->RdFreeItem->saveAll($freeData)) {
                                throw new Exception(__('Failed to save free items.'));
                            }
                            $this->RdFreeItem->saveAll($freeData);
                        }
                    
						/**** Audit START ****/
							$AuditSaleData['RsSale'] = $AuditData['RedistributorSaleitem'];

							$this->loadModel('Audit');
							$this->Audit->saveDeletedData($AuditData['RedistributorSale']['id'], 'RedistributorSale', $this->Auth->user('id') , serialize($AuditData),'RedistributorSale Has been updated',STATUS_EDIT , serialize($AuditSaleData));
							 
						/**** Audit END ****/

                        // Commit the transaction
                        $this->RedistributorSale->getDataSource()->commit();
                            
                        $this->Session->setFlash(__('Redistributor Sales was updated successfully'));
                        $this->redirect(array('action'=>'sales','?'=>$this->request->query));
                        $this->set(compact('orders','sales'));
                    }
                }catch (Exception $e) {
                    // Rollback the transaction if anything fails
                    $this->Order->getDataSource()->rollback();
                    $this->Session->setFlash(__('Error: ' . $e->getMessage()));
                }
            }
        }else{
        if(!empty($id)){
            $this->loadModel('RedistributorSale');
            $this->loadModel('Redistributor');
            $this->loadModel('Customer');
            
            $this->RedistributorSale->id = $id;
            $this->RedistributorSale->belongsTo['VerifyBy'] = array('className' => 'User', 'foreignKey' => 'verify_by', 'fields' => array('first_name', 'last_name'), 'type'=>'left');
            
            $order = $this->RedistributorSale->read(); //pr($order);exit;
            //pr($order); die();
            if (!$order) {
                throw new NotFoundException(__('Invalid Sale'));
            }
                    
            $this->_options();
                    
            
            $this->loadModel('RedistributorSaleitem');
            $sales = $this->RedistributorSaleitem->find('all', array('conditions'=>array('redistributor_sale_id'=>$id)));
            //pr($sales); die();

            $this->loadModel('RdFreeItem');
            $joins = array(array('table'=>'brands', 'alias'=>'Brand', 'type'=>'inner', 'conditions'=>'Brand.id = RdFreeItem.brand_id'));
            $freeItems = $this->RdFreeItem->find('all', array('fields'=>array('RdFreeItem.*', 'Brand.name'), 'conditions'=>array('redistributor_sale_id'=>$id), 'joins'=>$joins));
            //pr($freeItems);exit;
            
            $this->set(compact('order', 'sales','redistributors', 'freeItems'));
                                        
        }
    }   
    }

    public function rdsaledelete($id){
        $this->loadModel('RedistributorSaleitem');
        $this->loadModel('RedistributorSale');
        $this->loadModel('Audit');
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->loadModel('RedistributorSale');
        $this->RedistributorSale->id = $id;
		$this->RedistributorSale->bindModel(
            array(
            'belongsTo'=>array(
                'User' => array('className' => 'User', 'foreignKey' => 'user_id', 'fields' => array('first_name', 'last_name', 'role_id'), 'type'=>'inner'),
            )));
		$orderData = $this->RedistributorSale->read();
        $this->RedistributorSaleitem->unBindModelAll();
        $this->RedistributorSale->unBindModelAll();
        $data = array();
        $order = $this->RedistributorSale->read();
        $rsales['RsSale'] = $this->RedistributorSaleitem->find('all', array('conditions'=>array('redistributor_sale_id'=>$id)));
        $data['RsSale'] = serialize($rsales);
        if (!$this->RedistributorSale->exists()) {
            throw new NotFoundException(__('Invalid Redistributor Sale'));
        }
        $customerId = $this->RedistributorSale->field('customer_id');
        if ($this->RedistributorSale->delete()) {
            $this->loadModel('Customer');

            $this->Customer->verify_status( $customerId );
            $this->Audit->saveDeletedData($order['RedistributorSale']['id'], 'RedistributorSale', $this->Auth->user('id') , serialize($orderData),'RedistributorSale Has been Deleted',STATUS_DELETE , $data['RsSale']);
            $this->Session->setFlash(__('Redistributor Sale was deleted successfully'));
            $this->redirect(array('action' => 'sales'));
        }
        $this->Session->setFlash(__('Redistributor Sale was not deleted'));
        $this->redirect(array('action' => 'sales'));
    }


    public function reports(){
        //$this->gradPermission(4);
        $conditions = array();
        $this->loadModel('RedistributorSaleitem');
        $this->loadModel('RedistributorSale');

        $this->RedistributorSaleitem->belongsTo = array(
            'User' => array('className' => 'User', 'foreignKey' => 'user_id', 'fields' => array('first_name', 'last_name'), 'type'=>'inner'),
            'Brand' => array('className' => 'Brand', 'foreignKey' => 'brand_id', 'type'=>'inner'),
            'Depot' => array('className' => 'Depot', 'foreignKey' => 'depot_id', 'fields' => array('id', 'title','region_id'), 'type'=>'left'),
            'Customer' => array('className' => 'Customer', 'foreignKey' => 'customer_id', 'fields' => array('id', 'first_name','last_name'), 'type'=>'inner'),
            'Redistributor' => array('className' => 'Redistributor', 'foreignKey' => 'redistributor_id', 'fields' => array('id', 'first_name','last_name'), 'type'=>'inner'),
        );

        if (!empty($this->request->query['q'])){
            $conditions['OR']['concat_ws(" ", User.first_name, User.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
            $conditions['OR']['concat_ws(" ", Customer.first_name, Customer.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
            $conditions['OR']['concat_ws(" ", Redistributor.first_name, Redistributor.last_name) LIKE'] =  '%'.$this->request->query['q'].'%';
        }

        if (!empty($this->request->query['dv']) ) {
            $division_id = $this->request->query['dv'];
            if(empty($this->request->query['rg']) && empty($this->request->query['dp'])) {
                $conditions[] = 'RedistributorSaleitem.depot_id IN (SELECT id from depots WHERE region_id IN (SELECT region_id from divisions_regions WHERE division_id = ' . $this->request->query['dv'] . '))';
            }
        }else{
            $division_id = 0;
            if(!empty($this->user['division_id']) && $this->user['role_id'] == DIVISIONMANAGER){
                $this->request->query['dv'] = $division_id = $this->user['division_id'];
                if (empty($this->request->query['rg']) && empty($this->request->query['dp'])) {
                    $conditions[] = 'RedistributorSaleitem.depot_id IN (SELECT id from depots WHERE region_id IN (SELECT region_id from divisions_regions WHERE division_id = ' . $this->request->query['dv'] . '))';
                }
            }
        }
        if (!empty($this->request->query['rg']) && empty($this->request->query['dp']) ){
            $region_id = $this->request->query['rg'];
            if(empty($this->request->query['dp'])){
                $conditions[] = 'RedistributorSaleitem.depot_id IN (SELECT id from depots WHERE region_id = '.$this->request->query['rg'].')';
            }
        }else{
            $region_id = 0;
            if ($this->user['Role']['grade'] == 3){
                $region_id = $this->user['region_id'];
            }
        }
        if (!empty($this->request->query['dp'])){
            $conditions['RedistributorSaleitem.depot_id'] = $this->request->query['dp'];
        }

        if ( !empty($this->request->query['brd'])){
            //$conditions['RedistributorSaleitem.brand_id'] = $this->request->query['brd'];
            $conditions['RedistributorSaleitem.brand_group_id'] = $this->request->query['brd'];

        }
        if ( !empty($this->request->query['unt'])){
            $conditions['RedistributorSaleitem.unit'] = $this->request->query['unt'];
        }
		
		if (empty($this->request->query['from'])){
			$this->request->query['from'] = date('Y-m-01');
		}
		
        if ( !empty($this->request->query['from']) && !empty($this->request->query['to'])){
            $conditions[] = array('RedistributorSaleitem.sale_date BETWEEN ? AND ?' => array($this->request->query['from'], $this->request->query['to']));

        }elseif (!empty($this->request->query['from'])){
            $conditions['RedistributorSaleitem.sale_date >= '] = $this->request->query['from'];
        } elseif (!empty($this->request->query['to'])){
            $conditions['RedistributorSaleitem.sale_date <= '] = $this->request->query['to'];
        }
        if (isset($this->request->query['sts'])&& $this->request->query['sts']!=''){
            $conditions['RedistributorSaleitem.status'] = $this->request->query['sts'];
        }
		
		if (isset($this->request->query['via_app']) && $this->request->query['via_app']!='' ){
            $conditions['RedistributorSaleitem.via_app'] = $this->request->query['via_app'];
        }
		
        $order = $this->paginate['order'] = array('RedistributorSaleitem.created' => 'desc');
        $this->RedistributorSale->_userSalesItemsCondition($conditions, $this->user);
		


		$totals = $this->RedistributorSaleitem->find('all', array('fields'=>array('SUM(RedistributorSaleitem.amount) AS totalAmount', 'SUM(RedistributorSaleitem.cal_qty) AS totalCalQty'), 'conditions'=>$conditions)); //pr($totals );

        $this->RedistributorSaleitem->belongsTo['RedistributorSale'] = array('className' => 'RedistributorSale', 'foreignKey' => 'redistributor_sale_id', 'fields' => array('id', 'created', 'modified'), 'type'=>'left');
		
        $querystring = $this->request->query;

        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();
            $sales = $this->RedistributorSaleitem->find('all',array('conditions' =>$conditions,'order'=>$order, 'joins' => $joins ,'limit'=>10000, 'offset'=>$offset));
        }else{
            $sales = $this->paginate('RedistributorSaleitem', $conditions);
        }
        $this->set(compact('querystring', 'sales', 'totals'));

        $this->loadModel('Depot');
        $this->loadModel('Brand');
        $this->loadModel('BrandGroup');

        //$brands = $this->Brand->find('list', array('conditions'=>array('status'=>ACTIVE), 'fields'=>array('id','name')));

        $brands = $this->BrandGroup->find('list', array('fields'=>array('id','name')));


        //$redistributors = $this->Redistributor->redistributorListByRole($this->user);
        $this->set(compact('offset','brands'));
        $this->_selectOptions2();
        if(isset($this->request->query['export'])){
            $this->set('filename', 'RedistributorSale');
            $this->render('export_redistributor','export_xls');
        }
    }

    function _selectOptions2(){
        $Opdata = isset($this->request->data['Redistributor'] ) ? $this->request->data['Redistributor']  : array();
        $param = !empty($this->request->query ) ? $this->request->query  : array();
        $this->Option->Options2($Opdata, $this->user,$param);
    }

    public function deleteAllRedistributors(){
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }

        if(!empty($this->request->data['deleteAllValue'])){
            $this->Redistributor->deleteAll(array('Redistributor.id'=>explode(",", $this->request->data['deleteAllValue'])) );
            $this->Session->setFlash(__('All selected Redistributor Visit was deleted successfully') );
            $this->redirect(array('action'=>'index'));
        }
        exit;
    }
    public function deleteAllRedistributorSales(){
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }

        $this->loadModel('RedistributorSale');

        if(!empty($this->request->data['deleteAllValue'])){
            $this->RedistributorSale->deleteAll(array('RedistributorSale.id'=>explode(",", $this->request->data['deleteAllValue'])) );
            $this->Session->setFlash(__('All selected redistributor sales was deleted successfully') );
            $this->redirect(array('action'=>'sales'));
        }
        exit;
    }
    //RedistributorSale
}
