<?php
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
App::uses('CakeEmail', 'Network/Email');
ini_set('max_execution_time', 900);
App::uses('Contact', 'Contact');
class ContactsController 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('Contact.id'=>'desc'));
    public function index($id=null)
    {
                            
        $condition = array();
    	if($this->userType=='AGT'){
		    $condition=$this->CustomFunction->agencyWisePermission($id,$this->userType,$this->agencyId,'Contact.project_id');
	    }else{
            $condition=$this->CustomFunction->agencyWisePermission($id,$this->userType,$this->luserId,'Contact.project_id');
        }
        
        if($this->userType=='AT'){ #Hide contact from other agent on same agency 
		    $condition[]=array('Contact.user_id'=>$this->agencyId);
	    }
	    
	    if($this->userType=='AGT'){
           $condition[]=array('Contact.user_id'=>$this->adminValue['User']['id']);
	    }


        $this->loadModel('Category');
        $this->set('category',$this->Category->find('list'));
        $this->loadModel('Location');
        $this->set('location',$this->Location->find('list'));
        $location_id = 0;
        if(isset($this->params['named']['location_id']) && strlen($this->params['named']['location_id'])>0)
	    {
    	    $location_id = $this->params['named']['location_id'];
    	    $condition[]=array('Contact.location_id'=>$location_id);
	   }
	   $this->set('location_id',$location_id);
       if(isset($this->params['named']['user_id']) && strlen($this->params['named']['user_id'])>0)
       	{
       	    $condition[]=array('Contact.user_id'=>$this->params['named']['user_id']);
       	}
        if(isset($this->params['named']['client_id']) && strlen($this->params['named']['client_id'])>0)
    	{
    	    $condition[]=array('Contact.id'=>$this->params['named']['client_id']);
    	}
        $this->Prg->commonProcess();
        $this->Paginator->settings = $this->paginate;
        $this->Paginator->settings['conditions'] = array($this->Contact->parseCriteria($this->Prg->parsedParams()),$condition);

        if(isset($this->params->query['export']) && $this->params->query['export'] == 'Excel'){
            $this->Paginator->settings['limit']=40000;
        	$this->Paginator->settings['maxLimit']=40000;
        }else{
		    $this->Paginator->settings['limit']=$this->pageLimit;
        	$this->Paginator->settings['maxLimit']=$this->maxLimit;
        }
        $Contacts = $this->Paginator->paginate();
        $this->set('Contact', $Contacts);
        if(isset($this->params->query['export']) && $this->params->query['export'] == 'Excel'){
	        //Excel Export
	        include(APP.'Plugin/Excel/PHPExcel.php');
		$Excel = new PHPExcel();
		$Excel->getProperties()->setCreator('Umer Umair')
			->setLastModifiedBy('Umer Umair')
			->setTitle('Properties')
			->setSubject('All Properties List');
		$Excel->setActiveSheetIndex(0);
		$Sheet = $Excel->getActiveSheet();
		$Sheet->setTitle('Account Report');
		//Setting Headers
		$Sheet->setCellValue('A1','#')
			->setCellValue('B1','Name')
			->setCellValue('C1','Company Name')
			->setCellValue('D1','Location')
			->setCellValue('E1','Intrested In')
			->setCellValue('F1','Company Number')
			->setCellValue('G1','Email')
			->setCellValue('H1','District');

		//Writing Data
		foreach($Contacts as $K=>$Row){
			$Sheet->setCellValue(sprintf('A%d',$K+2),$Row['Contact']['id'])
				->setCellValue(sprintf('B%d',$K+2),$Row['Contact']['name'])
				->setCellValue(sprintf('B%d',$K+2),$Row['Contact']['company_name'])
				->setCellValue(sprintf('D%d',$K+2),$Row['Location']['name'])
				->setCellValue(sprintf('E%d',$K+2),$Row['Contact']['intrest_in'])
				->setCellValue(sprintf('F%d',$K+2),$Row['Contact']['mobile'])
				->setCellValue(sprintf('G%d',$K+2),$Row['Contact']['email'])
				->setCellValue(sprintf('H%d',$K+2),$Row['Contact']['district']);
		}

		//Downloading File
		$Writer = PHPExcel_IOFactory::createWriter($Excel, 'Excel2007');
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;Filename="Contacts.xlsx"');
		$Writer->save('php://output');
		return $this->redirect(array('controller'=>'Contacts','action' => 'index'));
	}
	$this->set('luserId',$this->luserId);
	if ($this->request->is('ajax'))
        {
            $this->render('index','ajax'); // View, Layout
        }
    }
    	public function clientsearch()

	{
		$this->autoRender = false;
		$this->request->onlyAllow('ajax');
		// get the search term from URL
		$this->loadModel('Client');
		$term = $this->request->query['q'];
		$conditions = array(
			'Client.name LIKE' => '%' . $term . '%'
		);
		/*if($this->luserId != 1){
		$conditions += array('Client.project_id'=>$this->luserId);
		}*/
		if ($this->userType == 'AGT') {
			$conditions+= (array)$this->CustomFunction->agencyWisePermission(null, $this->userType, $this->agencyId, 'Client.project_id');
		}
		else {
			// $condition += (array)$this->CustomFunction->agencyWisePermission(null,$this->userType,$this->luserId,'Client.project_id');
		}
		$users = $this->Client->find('all', array(
			'conditions' => $conditions
		));
		// 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('Category');
        $this->set('category',$this->Category->find('list',array('conditions'=>array('type'=>NULL))));
        $this->set('agency',$this->CustomFunction->agencyWiseList($this->userType,$this->agencyId));
        $this->loadModel('Location');
        $this->set('location',$this->Location->find('list'));
        if ($this->request->is('post'))
        {

           // echo '<pre>';print_r($this->$this->request->is('post'));
            //die;
            $this->Contact->create();
            try
            {
                $passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha256'));
                $password = rand();
                $this->request->data['Contact']['password'] = $passwordHasher->hash($password);
		if($this->userType=='AGT'){
		    $this->request->data['Contact']['project_id']=$this->agencyId;
		}
		if($this->userType=='AGY'){
			$this->request->data['Contact']['project_id']=$this->luserId;
		}
		$this->request->data['Contact']['user_id']=$this->luserId;
                
             
                if ($this->Contact->save($this->request->data))
                {
                    $email=$this->request->data['Contact']['email'];$clientName=$this->request->data['Contact']['name'];
                    $mobileNo=$this->request->data['Contact']['phone'];
                    $siteName=$this->siteName;$contactNo=$this->contact;$url=$this->siteDomain;
                    if($email)
                    {
                        if($this->emailNotification)
                        {
                            /* Send Email */
                            $this->loadModel('Emailtemplate');
                            $emailSettingArr=$this->Emailtemplate->findByType('CLC');
                            if($emailSettingArr['Emailtemplate']['status']=="Published")
                            {
                                $message=eval('return "' . addslashes($emailSettingArr['Emailtemplate']['description']) . '";');
                                $Email = new CakeEmail();
                                $Email->transport($this->emailSettype);
                                if($this->emailSettype=="Smtp")
                                $Email->config(array('host' => $this->emailHost,'port' =>  $this->emailPort,'username' => $this->emailUsername,'password' => $this->emailPassword));
                                $Email->from(array($this->siteEmail =>$this->siteName));
                                $Email->to($email);
                                $Email->template('default');
                                $Email->emailFormat('html');
                                $Email->subject($emailSettingArr['Emailtemplate']['name']);
                                $Email->send($message);
                                /* End Email */
                            }
                        }
                    }
                    if($mobileNo)
                    {
                        if($this->smsNotification)
                        {
                            /* Send Sms */
                            $this->loadModel('Smstemplate');
                            $smsTemplateArr=$this->Smstemplate->findByType('CLC');
                            if($smsTemplateArr['Smstemplate']['status']=="Published")
                            {
                                $url="$this->siteDomain";
                                $message=eval('return "' . addslashes($smsTemplateArr['Smstemplate']['description']) . '";');
                                $this->CustomFunction->sendSms($mobileNo,$message,$this->smsSettingArr);
                            }
                            /* End Sms */
                        }
                    }
                    $this->Session->setFlash(__('Your Contact Manager has been saved.'),'flash',array('alert'=>'success'));
                    return $this->redirect(array('action' => 'add'));
                }
            }
            catch (Exception $e)
            {
                $this->Session->setFlash($e->getMessage(),'flash',array('alert'=>'danger'));
                return $this->redirect(array('action' => 'index'));
            }
        }
    }
    public function addcsv()
    {

        
        
        $this->loadModel('Category');
        $this->loadModel('Smssetting');
        $this->loadModel('Smstemplate');
        $this->set('category',$this->Category->find('list',array('conditions'=>array('type'=>NULL))));
        $this->set('agency',$this->CustomFunction->agencyWiseList($this->userType,$this->agencyId));
        $this->loadModel('Location');
        $this->set('location',$this->Location->find('list'));
        if ($this->request->is('post'))
        {
            $smsSettingArr=$this->Smssetting->findById(1);
            $welcomeSmsTemplate=$this->Smstemplate->findById(11);
            
            
            $mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
            if(in_array($_FILES['csv']['type'],$mimes)){
              // do something
            } else {
              //die("Sorry, mime type not allowed");
              $this->Session->setFlash('csv comma delimited file allowed only','flash',array('alert'=>'danger'));
                 return $this->redirect(array('action' => 'addcsv'));
            }



                        $file = $_FILES['csv']['tmp_name']; 
$handle = fopen($file,"r"); 

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

$error = '';
$count = 0;
  $this->loadModel('User');
foreach ($matrix as $key => $value) {
   if($value[0] >= 1){
     $clent = $value[1];
     $phone = $value[2];
     $email = $value[3];
     $city = $value[4];
     $city = $value[4];
     $user_name = $value[5];
     $address = $value[6];
     $phone = str_replace('p:+', '0', $phone);
     
     //$user_name =  'aliraza';
     $conditions = array(
			'username' => $user_name
		);
	
		$users = $this->User->find('first', array(
			'conditions' => $conditions
		));
                
              
                if($users){
                    try
            { 
                        $count++;
                            $this->request->data['Contact']['user_id']=$users['User']['id'];
                            $this->request->data['Contact']['project_id']=$users['User']['project_id'];
                            $this->request->data['Contact']['name']=$clent;
                            $this->request->data['Contact']['mobile']=$phone;
                            $this->request->data['Contact']['phone']=$phone;
                            $this->request->data['Contact']['email']=$email;
                            $this->request->data['Contact']['state']=$city;
                            $this->request->data['Contact']['address']=$address;
                            $this->request->data['Contact']['category_id']=5;
                            $this->request->data['Contact']['location_id']=1;
                            $this->request->data['Contact']['pincode']=2;
                            $this->request->data['Contact']['district']=$city;
                          //  $this->request->data['Contact']['location']=116;
                            
                               
                $this->Contact->create();
                if(!empty($welcomeSmsTemplate)){
                    $template = $welcomeSmsTemplate['Smstemplate']['description'];
                    $template = preg_replace(array('/\[LEAD\_NAME\]/i','/\[CONSULTANT\_NAME\]/i'),array($clent,$user_name),$template);
                    $output = $this->CustomFunction->sendSms($phone,$template,$smsSettingArr);
                }
                $passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha256'));
                $password = rand();
              //  $this->request->data['Contact']['password'] = $passwordHasher->hash($password);
                $this->Contact->save($this->request->data);
          
//                echo "<pre>";
//                print_r($this->request->data);
//                print_r($this->Contact->save($this->request->data));
//                echo"</pre>";
//                exit;
                
                }
            catch (Exception $e)
            {
                $this->Session->setFlash($e->getMessage(),'flash',array('alert'=>'danger'));
              //  return $this->redirect(array('action' => 'addcsv'));
            }
                            
                            
                }else{
                  $error .= '- '+$user_name;
                }
                
//                echo "<pre>";
//                print_r($users);
//                echo"</pre>";
//                exit;
     
    // $this->Contact->findByid($id);
     

    //  $this->request->data['Contact']['client_id']=$this->luserId;
   }
}

if(empty($error)){
      $this->Session->setFlash(__('Your Contact Manager has been saved. Total'.$count ),'flash',array('alert'=>'success'));
      return $this->redirect(array('action' => 'addcsv'));
}else{
     $this->Session->setFlash('user name not found saved Total = '.$count,'flash',array('alert'=>'danger'));
     return $this->redirect(array('action' => 'index')); 
}
exit;

        }
    }
    public function addnew() {
        $this->layout = null;
        $this->loadModel('Category');
        $this->set('category', $this->Category->find('list', array('conditions' => array('type' => NULL))));
        $this->set('agency', $this->CustomFunction->agencyWiseList($this->userType, $this->agencyId));
        $this->loadModel('Location');
        $this->set('location', $this->Location->find('list'));
        if ($this->request->is('post')) {

            // echo '<pre>';print_r($this->$this->request->is('post'));
            //die;
            $this->Contact->create();
            try {
                $passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha256'));
                $password = rand();
                $this->request->data['Contact']['password'] = $passwordHasher->hash($password);
                if ($this->userType == 'AGT') {
                    $this->request->data['Contact']['project_id'] = $this->agencyId;
                }
                if ($this->userType == 'AGY') {
                    $this->request->data['Contact']['project_id'] = $this->luserId;
                }
                $this->request->data['Contact']['user_id'] = $this->luserId;
                if ($this->Contact->save($this->request->data, array('validate' => false))) {
                    $email = $this->request->data['Contact']['email'];
                    $clientName = $this->request->data['Contact']['name'];
                    $mobileNo = $this->request->data['Contact']['phone'];
                    $siteName = $this->siteName;
                    $contactNo = $this->contact;
                    $url = $this->siteDomain;
//                    
//echo "<pre>";
//print_r($this->Contact);
//echo"</pre>";
//exit;
                    /*  if($email)
                      {
                      if($this->emailNotification)
                      {
                      /* Send Email */
                    /*      $this->loadModel('Emailtemplate');
                      $emailSettingArr=$this->Emailtemplate->findByType('CLC');
                      if($emailSettingArr['Emailtemplate']['status']=="Published")
                      {
                      $message=eval('return "' . addslashes($emailSettingArr['Emailtemplate']['description']) . '";');
                      $Email = new CakeEmail();
                      $Email->transport($this->emailSettype);
                      if($this->emailSettype=="Smtp")
                      $Email->config(array('host' => $this->emailHost,'port' =>  $this->emailPort,'username' => $this->emailUsername,'password' => $this->emailPassword));
                      $Email->from(array($this->siteEmail =>$this->siteName));
                      $Email->to($email);
                      $Email->template('default');
                      $Email->emailFormat('html');
                      $Email->subject($emailSettingArr['Emailtemplate']['name']);
                      $Email->send($message);
                      /* End Email */
                    /*         }
                      }
                      }
                      /*  if($mobileNo)
                      {
                      if($this->smsNotification)
                      {
                      /* Send Sms */
                    /*          $this->loadModel('Smstemplate');
                      $smsTemplateArr=$this->Smstemplate->findByType('CLC');
                      if($smsTemplateArr['Smstemplate']['status']=="Published")
                      {
                      $url="$this->siteDomain";
                      $message=eval('return "' . addslashes($smsTemplateArr['Smstemplate']['description']) . '";');
                      $this->CustomFunction->sendSms($mobileNo,$message,$this->smsSettingArr);
                      }
                      /* End Sms */
                    /*    }
                      } */

                    $result = array();
                    $result['type'] = 'success';
                    $result['c_id'] = $this->Contact->id;
                    $result['c_name'] = $this->request->data['Contact']['name'];
                    echo json_encode($result);
                    exit;
                    //$this->Session->setFlash(__('Your Contact Manager has been saved.'),'flash',array('alert'=>'success'));
//                    return $this->redirect(array('action' => 'add'));
                    //  return $this->redirect(array('controller' => 'Leads' , 'action' => 'add', '?' => array('cont_id' => 12)));
                }
            } catch (Exception $e) {

                $result = array();
                $result['type'] = 'error';
                $result['msg'] = $e->getMessage();
                echo json_encode($result);
                exit;
                //$this->Session->setFlash($e->getMessage(),'flash',array('alert'=>'danger'));
                //return $this->redirect(array('action' => 'index'));
            }
        }
    }

    public function edit($id = null)
    {
        if (!$id)
        {
            throw new NotFoundException(__('Invalid post'));
        }
        $ids=explode(",",$id);
        $post=array();
        foreach($ids as $k=>$id)
        {$k++;
            $post[$k]=$this->Contact->findByid($id);
	    if($this->userType=='AGT') {
		if($post[$k]['Contact']['user_id']!=$this->luserId) {
		    $this->Session->setFlash(__('Invalid Post'),'flash',array('alert'=>'danger'));
		    return $this->redirect(array('action' => 'index'));
		}
	    }
	    elseif($this->userType=='AGY') {
		if($post[$k]['Contact']['project_id']!=$this->agencyId) {
		    $this->Session->setFlash(__('Invalid Post'),'flash',array('alert'=>'danger'));
		    return $this->redirect(array('action' => 'index'));
		}
	    }
        }
        $this->set('Contact',$post);
        if (!$post)
        {
            throw new NotFoundException(__('Invalid post'));
        }
        $this->loadModel('Category');
        $this->set('category',$this->Category->find('list'));
        $this->loadModel('Location');
        $this->set('location',$this->Location->find('list'));
        if ($this->request->is(array('post', 'put')))
        {
            try
            {
                if ($this->Contact->save(isset($this->request->data[1]) ? $this->request->data[1] : $this->request->data[0]))
                {
                    $this->Session->setFlash(__('Your Contact Manager has been Updated.'),'flash',array('alert'=>'success'));
                    return $this->redirect(array('action' => 'index'));
                }
            }
            catch (Exception $e)
            {
                $this->Session->setFlash(__('Invalid Post.'),'flash',array('alert'=>'danger'));
                return $this->redirect(array('action' => 'index'));
            }
            $this->set('isError',true);
        }
        else
        {
            $this->layout = null;
            $this->set('isError',false);
        }
        if (!$this->request->data)
        {
            $this->request->data = $post;
        }
    }
    public function deleteall()
    {
        try
        {
            if ($this->request->is('post'))
            {
                foreach($this->data['Contact']['id'] as $key => $value)
                {
		    if($value > 0) {
			$prop[$key]=$this->Contact->findByid($value);
			if($this->userType=='AGT') {
			    if($prop[$key]['Contact']['user_id']!=$this->luserId) {
				$this->Session->setFlash(__('Invalid Post'),'flash',array('alert'=>'danger'));
				return $this->redirect(array('action' => 'index'));
			    }
			}
			elseif($this->userType=='AGY') {
			    if($prop[$key]['Contact']['project_id']!=$this->agencyId) {
				$this->Session->setFlash(__('Invalid Post'),'flash',array('alert'=>'danger'));
				return $this->redirect(array('action' => 'index'));
			    }
			}
                    $this->Contact->delete($value);
		    }
                }
                $this->Session->setFlash(__('Your Contact Manager has been deleted.'),'flash',array('alert'=>'success'));
            }
            $this->redirect(array('action' => 'index'));
        }
        catch (Exception $e)
        {
            $this->Session->setFlash(__('Please Delete Deal first.'),'flash',array('alert'=>'danger'));
            return $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->Contact->findById($id);
        $this->set('post',$post);
    }
    public function printclient($id = null)
    {
        $this->layout = null;
        if (!$id)
        {
            $this->Session->setFlash(__('Invalid Post.'),'flash',array('alert'=>'danger'));
            $this->redirect(array('action' => 'index'));
        }
        $post = $this->Contact->findById($id);
        $this->set('post',$post);
    }
    public function changepass($id = null)
    {
        $this->layout = null;
        if (!$id)
        {
            $this->Session->setFlash(__('Invalid Post.'),'flash',array('alert'=>'danger'));
            $this->redirect(array('action' => 'index'));
        }
        $post = $this->Contact->findById($id);
        if (!$post)
        {
            $this->Session->setFlash(__('Invalid Post.'),'flash',array('alert'=>'danger'));
            $this->redirect(array('action' => 'index'));
        }
	if($this->userType=='AGT') {
	    if($post['Contact']['user_id']!=$this->luserId) {
		$this->Session->setFlash(__('Invalid Post'),'flash',array('alert'=>'danger'));
		return $this->redirect(array('action' => 'index'));
	    }
	}
	elseif($this->userType=='AGY') {
	    if($post['Contact']['project_id']!=$this->agencyId) {
		$this->Session->setFlash(__('Invalid Post'),'flash',array('alert'=>'danger'));
		return $this->redirect(array('action' => 'index'));
	    }
	}
        if ($this->request->is(array('post', 'put')))
        {
	    try
	    {
		$passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha256'));
		$this->Contact->id = $id;
		$this->request->data['Contact']['password'] = $passwordHasher->hash($this->request->data['Contact']['password']);
		if ($this->Contact->save($this->request->data,array('validate'=>false)))
		{
		    $this->Session->setFlash(__('Password Changed Successfully'),'flash',array('alert'=>'success'));
		    $this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__('Invalid Post.'),'flash',array('alert'=>'danger'));
		$this->redirect(array('action' => 'index'));
	    }
	    catch (Exception $e)
            {
                $this->Session->setFlash(__('Invalid Post.'),'flash',array('alert'=>'danger'));
                return $this->redirect(array('action' => 'index'));
            }
            $this->set('isError',true);
        }
        else
        {
            $this->layout = null;
            $this->set('isError',false);
        }
        if (!$this->request->data)
        {
            $this->request->data = $post;
        }
    }
}
