<?php
/**
 * Controller name
 *
 * @var string
 */
App::uses('AppController', 'Controller');
class CrmimportController extends AppController {

	function index(){
		$this->loadModel('CrmContact');
		$this->paginate['limit'] = 100;
		$contacts = $this->paginate('CrmContact');
		if ($contacts ){
			foreach ($contacts as $key=>$contact){
				$status = $this->_addContact($contact);
				$contacts[$key]['status'] = $status;
			}
		}
		
		$this->set('contacts', $contacts);
	}
	
	function _addContact($contact){
		$this->loadModel('VtigerContactLog');
		$this->loadModel('Customer');
		$user_id = 1;
		$lga_id = $depot_id = $region_id = $state_id = $lat = $long = 0;
		//Check customer by phone
		if (!empty($contact['CrmContact']['mobile']) && is_numeric($contact['CrmContact']['mobile'])){
			$old_customer = $this->Customer->find('first', array('conditions'=>array('Customer.phone'=>$contact['CrmContact']['mobile'])));
		}else{
			$old_customer = $this->Customer->find('first', array('conditions'=>array('Customer.first_name'=>$contact['CrmContact']['firstname'], 'Customer.last_name'=>$contact['CrmContact']['lastname'])));
		}
		
		if (!empty($old_customer)){
			$customer_id = $old_customer['Customer']['id'];
			$status = 2;
		}else{
		
		//Get LGA ID
			$this->loadModel('LgArea');
			if($contact['CrmContact']['LGA']){
				$lga = $this->LgArea->find('first', array('conditions'=>array('LOWER(name)'=>strtolower($contact['CrmContact']['LGA']))));
				if($lga){
					$lga_id = $lga['LgArea']['id'];
				}
			}
			$this->loadModel('Depot');
			if($contact['CrmContact']['depot']){
				$depot = $this->Depot->find('first', array('conditions'=>array('LOWER(Depot.title)'=>strtolower($contact['CrmContact']['depot']))));
				if($depot){
					$depot_id = $depot['Depot']['id'];
					$region_id = $depot['Depot']['id'];
				}
			}
			$this->loadModel('State');
			if($contact['CrmContact']['mailingstate']){
				$state = $this->State->find('first', array('conditions'=>array('LOWER(state)'=>strtolower($contact['CrmContact']['mailingstate']))));
				if($state){
					$state_id = $state['State']['id'];
				}
			}
			//created by
			if ($contact['CrmContact']['createby']){
				$user = $this->State->query("SELECT id FROM users WHERE LOWER(CONCAT_WS(' ', first_name, last_name)) = '".strtolower($contact['CrmContact']['createby'])."'");
				
				if ($user){
					$user_id = $user['0']['users']['id'];
				}
			}
			//Get latlong
			$address = $contact['CrmContact']['mailingstreet'].'+'.$contact['CrmContact']['mailingcity'].'+'.$contact['CrmContact']['mailingstate'].'+'.$contact['CrmContact']['mailingzip'];
			$latlong = $this->_getLatLong($address);
			$lat = $latlong['lat'];
			$long = $latlong['long'];
			$cdata = array(		
				'first_name' => $contact['CrmContact']['firstname'],
				'last_name' => $contact['CrmContact']['lastname'],
				'email' => $contact['CrmContact']['email'],
				'phone' => $contact['CrmContact']['mobile'],
				'address' => $contact['CrmContact']['mailingstreet'],
				'city' => $contact['CrmContact']['mailingcity'],
				'zipcode' => trim($contact['CrmContact']['mailingzip']),
				'state_id' => $state_id,
				'latitude' => $lat,
				'longitude' => $long,
				'lg_area_id' => $lga_id,
				'region_id' => $region_id,
				'depot_id' => $depot_id,
				'description' => $contact['CrmContact']['description'],
				'view_details' => 1,
				'user_id' => $user_id,
				'created' => $contact['CrmContact']['createdtime'],
				'modified' => $contact['CrmContact']['modifiedtime']		
			);		
			//pr($cdata);
			$this->Customer->create();
			$addeCustomer = $this->Customer->save($cdata);
			$status = 1;
			$customer_id = $addeCustomer['Customer']['id'];
			if ($contact['CrmContact']['smcreatorid'] != $contact['CrmContact']['smownerid'] ){
				//Add assign to
				$user2 = $this->State->query("SELECT id FROM users WHERE LOWER(CONCAT_WS(' ', first_name, last_name)) = '".strtolower($contact['CrmContact']['first_name']." ".$contact['CrmContact']['last_name'])."'");
				
				if ($user2){
					$assignto_id = $user2['0']['users']['id'];
					$this->loadModel('CustomerAssign');
					$this->CustomerAssign->primaryKey = null;
					$this->CustomerAssign->create();
					$assignData = array('customer_id'=>$customer_id, 'user_id'=>$assignto_id, 'assign_by'=>$user_id);					
					$this->CustomerAssign->save($assignData);
				}
			}
		}
		
		$this->loadModel('VtigerContactLog');
		$is_added = $this->VtigerContactLog->find('count', array('conditions'=>array('vtiger_id'=>$contact['CrmContact']['crmid'], 'customer_id'=>$customer_id)));
		if ($is_added == 0){
			$logData = array('vtiger_id'=>$contact['CrmContact']['crmid'], 'customer_id'=>$customer_id, 'status'=>$status);
			$this->VtigerContactLog->create();
			$this->VtigerContactLog->save($logData);
		}
		return $status;
	}
	
	function _getLatLong($address){
		
		$address = urlencode($address);
		$url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=".DEFAULT_RESION;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		$response = curl_exec($ch);
		curl_close($ch);
		$response_a = json_decode($response);
		$result['lat'] = isset($response_a->results[0]->geometry->location->lat)?$response_a->results[0]->geometry->location->lat:0;
		
		$result['long'] = isset($response_a->results[0]->geometry->location->lng)?$response_a->results[0]->geometry->location->lng:0;
		
		return $result;
	}
}