<?php
App::uses('CakeTime', 'Utility');
class LeadsController extends AdminAppController {
    public $helpers = array('Html', 'Form','Session','Paginator','Js'=> array('Jquery'));
    public $components = array('Session','Paginator','search-master.Prg');
    public $presetVars = true;
    var $paginate = array('page'=>1,'order'=>array('Lead.id'=>'desc'));
    public function index($id=null)
    {
        $this->loadModel('User');
        $this->loadModel('Type');
        $this->loadModel('Status');
          $this->loadModel('Contract');


        $this->set('type',$this->Type->find('list'));
        $this->set('status',$this->Status->find('list',array('order'=>array('Status.name'=>'asc'))));
        $this->set('projectName',$this->CustomFunction->agencyWiseList($this->userType,$this->agencyId));
         $this->set('contract',$this->Contract->find('list'));
        
        
//        echo "<pre>";
//        print_r( $this);
//        echo"</pre>";
//        exit;
        
      /*  echo $id;
        exit;
        */
        $condition = array();
        //$condition=$this->CustomFunction->userWisePermission($id,$this->luserId,$this->userType,$this->agencyId,'Lead.project_id','Lead.user_id');
        
   // $condition['Leads.user_id'] = 110;
        $this->set('agent', $this->User->find('list', array(
			'fields' => array(
				'id',
				'name'
			) ,
			'conditions' => array(
				'User.status' => 'Active',
				'User.ugroup_id' => '2',
				$condition
			) ,
			'order' => array(
				'User.name' => 'asc'
			)
		)));
      /*  echo '<pre>';
        print_r($this->adminValue['User']['id']);
        exit;*/
        
        if ($this->userType == 'AGT') {
			$condition[] = array(
                            'Lead.user_id' => intval($this->adminValue['User']['id']) #AR 
			);
		}
        
        
        // echo $_POST['data']['Lead']['client_id'];
        /*if (isset($this->params['named']['agent']) && strlen($this->params['named']['agent']) > 0) {
			$condition[] = array(
				'Property.user_id' => intval($this->params['named']['agent'])
			);
		}*/
        if (isset($this->params['named']['agent']) && strlen($this->params['named']['agent']) > 0) {
			$condition[] = array(
				'Lead.user_id' => intval($this->params['named']['agent'])
			);
		}

        if (isset($this->params['named']['project_id']) && strlen($this->params['named']['project_id']) > 0) {
			$condition[] = array(
				'Lead.project_id' => intval($this->params['named']['project_id'])
			);
		}
        if (isset($this->params['named']['client_id']) && strlen($this->params['named']['client_id']) > 0) {
			$condition[] = array(
				'Lead.client_id' => intval($this->params['named']['client_id'])
			);
		}
        if (isset($this->params['named']['property_id']) && strlen($this->params['named']['property_id']) > 0) {
			$condition[] = array(
				'Lead.property_id' => intval($this->params['named']['property_id'])
			);
		}
        if (isset($this->params['named']['type_id']) && strlen($this->params['named']['type_id']) > 0) {
			$condition[] = array(
				'Property.type_id' => intval($this->params['named']['type_id'])
			);
		}
        if (isset($this->params['named']['status_id']) && strlen($this->params['named']['status_id']) > 0) {
			$condition[] = array(
				'Lead.status_id' => intval($this->params['named']['status_id'])
			);
		}
        if (isset($this->params['named']['follow_up_to']) && strlen($this->params['named']['follow_up_to']) > 0) {
			$condition[] = array(
				'DATE(Lead.follow_up) >=' => date('Y/m/d', strtotime($this->params['named']['follow_up_to']))
			);
		}
        if (isset($this->params['named']['follow_up_from']) && strlen($this->params['named']['follow_up_from']) > 0) {
			$condition[] = array(
				'DATE(Lead.follow_up) <=' => date('Y/m/d', strtotime($this->params['named']['follow_up_from']))
			);
		}
           
           
        
         $this->set('userType', $this->userType);                        
        $this->Prg->commonProcess();
        $this->Paginator->settings = $this->paginate;
        $this->Paginator->settings['conditions'] = array($this->Lead->parseCriteria($this->Prg->parsedParams()),$condition);
	$this->Paginator->settings['limit']=$this->pageLimit;
        $this->Paginator->settings['maxLimit']=$this->maxLimit;
        $this->set('Lead', $this->Paginator->paginate());
	if ($this->request->is('ajax'))
        {
            $this->render('index','ajax'); // View, Layout
        }
    }
    
    public function propertysearchAR()

	{
		$this->autoRender = false;
		$this->request->onlyAllow('ajax');
		// get the search term from URL
		$this->loadModel('Property');
		$term = $this->request->query['q'];
		$cond = array();
		$cond1 = array();
		$deal = isset($this->request->query['leads']) ? $this->request->query['leads'] : false;
		if(!$deal){
			if ($this->request->query['q1']) {
				$cond = array(
					'Property.type_id' => $this->request->query['q1']
				);
			}
			if ($this->request->query['q2']) {
				$cond1 = array(
					'Property.contract_id' => $this->request->query['q2']
				);
			}
		}
		$condition = $this->CustomFunction->agencyWisePermission(NULL, $this->userType, $this->agencyId, 'Property.project_id');
		$config = array(
			'fields' => array(
				'Property.id',
				'Property.name',
				'Location.name'
			),
			'conditions' => array(
				'Property.name LIKE' => '%' . $term . '%',
				//$cond,
				//!$deal ? array('Property.status' => 'Available') : array(),
				//$cond1,
				$condition
			)
		);
		if($deal){
			$config['joins'] = array(
		        array(
		            'table' => 'leads',
		            'alias' => 'Leads',
		            'type' => 'INNER',
		            'conditions' => array(
		                'Leads.property_id = Property.id'
		            )
		        )
		    );
		}
		$users = $this->Property->find('all', $config);
		// Format the result for select2
		$result = array();
		foreach($users as $key => $user){
			$result[$key]['id'] = (int)$user['Property']['id'];
			$result[$key]['text'] = sprintf('%s, %s',$user['Property']['name'],$user['Location']['name']);
		}
		$users = $result;
		echo json_encode($users);
	}
    
    public function propertysearch()
    {
        $this->autoRender = false;
	//$this->request->onlyAllow('ajax');
        // get the search term from URL
        $this->loadModel('Property');
        $term = $this->request->query['q'];
        $cond=array();
        if($this->request->query['q1'])
        {
            $type=$this->request->query['q1'];
            $cond[]=array('Property.type_id' => $type);
        }
	if(isset($this->request->query['q2']) && strlen($this->request->query['q2'])>0)
        {
            $cond[]=array('Property.project_id' => $this->request->query['q2']);
        }
        $condition=$this->CustomFunction->agencyWisePermission(NULL,$this->userType,$this->agencyId,'Property.project_id');
        $users = $this->Property->find('all',array('conditions' => array('Property.name LIKE' => '%'.$term.'%','Property.status'=>'Available',$cond,$condition)));
        // Format the result for select2
        $result = array();
        foreach($users as $key => $user)
        {
            $result[$key]['id'] = (int) $user['Property']['id'];
            $result[$key]['text'] = $user['Property']['name'];
        }
        $users = $result;        
        echo json_encode($users);
    }
    public function clientsearch()
    {
        $this->autoRender = false;
        $this->request->onlyAllow('ajax');
        // get the search term from URL
        $this->loadModel('Client');
        $term = $this->request->query['q'];
        $condition=$this->CustomFunction->agencyWisePermission(NULL,$this->userType,$this->agencyId,'Client.project_id');
        $users = $this->Client->find('all',array('fields'=>array('Client.id','Client.name'),'conditions' => array('Client.name LIKE' => '%'.$term.'%',$condition)));
        // Format the result for select2
        $result = array();
        foreach($users as $key => $user)
        {
            $result[$key]['id'] = (int) $user['Client']['id'];
            $result[$key]['text'] = $user['Client']['name'];
        }
        $users = $result;        
        echo json_encode($users);
    }
    public function add()
    {
        
        $this->loadModel('Property');
        $this->loadModel('Project');
        $this->loadModel('Type');
        $this->loadModel('Status');
        $this->loadModel('User');
         $this->loadModel('Contract');
        //$this->set('propertyId',$this->Property->find('list',array('fields'=>array('id','name'))));
	$this->set('projectName',$this->CustomFunction->agencyWiseList($this->userType,$this->agencyId));
        $this->set('type',$this->Type->find('list'));
        $this->set('status',$this->Status->find('list',array('order'=>array('Status.name'=>'asc'))));
	$this->set('agencyId',$this->agencyId);
	$this->set('luserId',$this->luserId);
        $this->set('contract',$this->Contract->find('list'));
	$projectId=null;
	if($this->userType=='AGY'){
	    $this->set('agentList',$this->User->find('list',array('conditions'=>array('User.project_id'=>$this->agencyId,'User.ugroup_id'=>2))));		    
	}
	if ($this->request->is('post'))
        {
            $this->Lead->create();
            if($this->userType=='AGT' || $this->userType=='AGY'){
		$this->request->data['Lead']['project_id']=$this->agencyId;		    
	    }
	    if($this->userType=='AGT')
	    $this->request->data['Lead']['user_id']=$this->luserId;
	    try
            {
                if ($this->Lead->save($this->request->data))
                {
                    $this->Session->setFlash(__('Lead has been saved.'),'flash',array('alert'=>'success'));
                    return $this->redirect(array('action' => 'add'));
                }
            }
            catch (Exception $e)
            {
                $this->Session->setFlash(__('Please Select Property Name'),'flash',array('alert'=>'danger'));
            }
	    $projectId=$this->request->data['Lead']['project_id'];
        }
	$this->set('agentName',$this->User->find('list',array('conditions'=>array('User.project_id'=>$projectId,'User.ugroup_id'=>2))));
    }
    public function addcsv()
    {
 
        $this->loadModel('Property');
        $this->loadModel('Project');
        $this->loadModel('Type');
        $this->loadModel('Status');
        $this->loadModel('User');
         $this->loadModel('Contract');
        //$this->set('propertyId',$this->Property->find('list',array('fields'=>array('id','name'))));
	$this->set('projectName',$this->CustomFunction->agencyWiseList($this->userType,$this->agencyId));
        $this->set('type',$this->Type->find('list'));
        $this->set('status',$this->Status->find('list',array('order'=>array('Status.name'=>'asc'))));
	$this->set('agencyId',$this->agencyId);
	$this->set('luserId',$this->luserId);
        $this->set('contract',$this->Contract->find('list'));
	$projectId=null;
   
	if($this->userType=='AGY'){
	    $this->set('agentList',$this->User->find('list',array('conditions'=>array('User.project_id'=>$this->agencyId,'User.ugroup_id'=>2))));		    
	}
	if ($this->request->is('post'))
        {
            
            
            $file = $_FILES['csv']['tmp_name']; 
$handle = fopen($file,"r"); 

$matrix = array();
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) 
{
$matrix[] = $row;
}
  

foreach ($matrix as $key => $value) {
   if($value[0] >= 1){
       echo "<pre>";
       print_r($value);
       echo"</pre>";
       exit;
   }
}

echo "<pre>";
print_r($matrix);
echo"</pre>";
exit;
            
            
            
            $tmpName = $_FILES['csv']['tmp_name'];
            $data = array_map('str_getcsv', file($tmpName));
            $rows   = array_map(function($data) { return str_getcsv($data,";");}
    , file($filePath_product_names_t));
$header = array_shift($rows);
$csv    = [];
foreach($rows as $row) {
    $row = array_pad($row, count($header), "");
    $csv[] = array_combine($header, $row);
}

echo "<pre>";
print_r($csv);
echo"</pre>";
exit;
            
            
                $tmpName = $_FILES['csv']['tmp_name'];
                $csvAsArray = array_map('str_getcsv', file($tmpName));
                $csv = csvToArray($csvAsArray);
                
             //   $csvFile = file_get_contents($csvAsArray);
                echo "<pre>";
                print_r($csv);
                echo"</pre>";
                exit;
                
                
$csvAsArray = array_map('str_getcsv', file($tmpName));
$csvAsArray = explode("\n",$csvAsArray);
//$csvAsArray =  explode(" ",$csvAsArray);
foreach ($csvAsArray as $key => $value) {
      //$value = explode(';', $value);
    echo "<pre>";
    print_r($value);
    echo"</pre>";
    
    if(is_int($value[0])){
        echo "<pre>";
        print_r($value);
        echo"</pre>";
        exit;
    }
}


echo "<pre>";
print_r($csvAsArray);
echo"</pre>";
exit;      
            
               $tmpName = $_FILES['csv']['tmp_name'];
            $file = tmpfile();
$path = stream_get_meta_data($file)['uri']; // eg: /tmp/phpFx0513a
      
            $path = tempnam(sys_get_temp_dir(), 'prefix');
            $file = fopen($path.''.$tmpName.".csv","r");
            print_r(fgetcsv($file));
            fclose($file);
            exit;
            $this->Lead->create();
            if($this->userType=='AGT' || $this->userType=='AGY'){
		$this->request->data['Lead']['project_id']=$this->agencyId;		    
	    }
	    if($this->userType=='AGT')
	    $this->request->data['Lead']['user_id']=$this->luserId;
	    try
            {
                if ($this->Lead->save($this->request->data))
                {
                    $this->Session->setFlash(__('Lead has been saved.'),'flash',array('alert'=>'success'));
                    return $this->redirect(array('action' => 'add'));
                }
            }
            catch (Exception $e)
            {
                $this->Session->setFlash(__('Please Select Property Name'),'flash',array('alert'=>'danger'));
            }
	    $projectId=$this->request->data['Lead']['project_id'];
        }
    
        
	$this->set('agentName',$this->User->find('list',array('conditions'=>array('User.project_id'=>$projectId,'User.ugroup_id'=>2))));
    }
    public function edit($id = null)
    {
        if (!$id)
        {
            throw new NotFoundException(__('Invalid post'));
        }
        $ids=explode(",",$id);
        $post=array();
	$this->loadModel('User');
        $this->loadModel('leadslogs');
        $this->set('agencyId',$this->agencyId);
	foreach($ids as $k=>$id)
        {
            $k++;
            $post[$k]=$this->Lead->findByid($id);
            $this->set("agentName$k", $this->User->find('list',array('fields'=>array('id','name'),'conditions'=>array('project_id'=>$post[$k]['Lead']['project_id'],'User.ugroup_id'=>2),'order'=>array('User.name'=>'asc'))));
        }
        $this->set('Lead',$post);
        if($this->userType=='AGY'){
	    $this->set('agentList',$this->User->find('list',array('conditions'=>array('User.project_id'=>$this->agencyId,'User.ugroup_id'=>2))));		    
	}
	if (!$post)
        {
            throw new NotFoundException(__('Invalid post'));
        }
        $this->loadModel('Type');
        $this->loadModel('Project');
        $this->loadModel('Status');
        $this->set('type',$this->Type->find('list'));
        $this->set('status',$this->Status->find('list'));
        $this->set('agency',$this->CustomFunction->agencyWiseList($this->userType,$this->agencyId));
//        $leadslogs = $this->leadslogs->findByid($id);
        $leadslogs = $this->leadslogs->find('all',array('conditions'=>array('leadslogs.lead_id'=>$id)));
         $this->set('leadslogs',$leadslogs);
        if ($this->request->is(array('post', 'put')))
        {
            $this->Lead->id = $id;
            try
            {
                   $data = array(
                    'leadslogs' => array(
                        'lead_id' => $id,
                        'status_id' => $post[1]['Lead']['status_id'],
                        'follow_up' => $post[1]['Lead']['follow_up'],
                        'remarks' => $post[1]['Lead']['remarks']
                    )
                );
              
              
              $this->leadslogs->create();
              $this->leadslogs->save($data);
                
                if ($this->Lead->saveAll($this->request->data))
                {
                    $this->Session->setFlash(__('Lead has been updated.'),'flash',array('alert'=>'success'));
                    return $this->redirect(array('action' => 'index'));
                }
            }
            catch (Exception $e)
            {
                $this->Session->setFlash(__('Please Select Client Name & Property Name.'),'flash',array('alert'=>'danger'));
                return $this->redirect(array('action' => 'index'));
            }
     
            
            $this->set('isError',true);
            
        $this->loadModel('leadslogs');
//        $this->set('lead_id',$id);
//        $this->set('status_id',$id);
//        $this->set('follow_up',$id);
//        $this->set('remarks',$id);
       // $this->set('created',strtotime('Y-m-d'));
        
     
        }
        else
        {
            $this->layout = null;
            $this->set('isError',false);
        }
        if (!$this->request->data)
        {
            $this->request->data = $post;
        }
    }    
    public function deleteall()
    {
        if ($this->request->is('post'))
        {
            foreach($this->data['Lead']['id'] as $key => $value)
            {
                $this->Lead->delete($value);
            }
            $this->Session->setFlash(__('Lead has been deleted.'),'flash',array('alert'=>'success'));
        }        
        $this->redirect(array('action' => 'index'));
    }
    public function view($id = null)
    {
        $this->layout = null;
        if (!$id)
        {
            $this->Session->setFlash(__('Invalid Post.'),'flash',array('alert'=>'danger'));
            $this->redirect(array('action' => 'index'));
        }
        $post = $this->Lead->findById($id);
        $this->set('post',$post);
    }
}
