<?php
/*+********************************************************************************
 * The contents of this file are subject to the vtiger CRM Public License Version 1.0
 * ("License"); You may not use this file except in compliance with the License
 * The Original Code is:  vtiger CRM Open Source
 * The Initial Developer of the Original Code is vtiger.
 * Portions created by vtiger are Copyright (C) vtiger.
 * All Rights Reserved.
 *********************************************************************************/
header('Access-Control-Allow-Origin: *');
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);

//Opensource fix for tracking email access count
chdir(dirname(__FILE__). '/../');

require_once 'includes/Loader.php';
require_once 'include/utils/utils.php';

vimport('includes.http.Request');
vimport('includes.runtime.Globals');
vimport('includes.runtime.BaseModel');
vimport('includes.runtime.Controller');
vimport('includes.runtime.LanguageHandler');

require_once 'modules/Contacts/Contacts.php';
require_once 'modules/Potentials/Potentials.php';

// require_once "libraries/google-api-php-client/autoload.php";

class Ajax_Action extends Vtiger_Action_Controller {

	public function process(Vtiger_Request $request) {
		global $adb;
		global $current_user;
		$current_user = Users::getActiveAdminUser();
		$option = $request->get("option");
		switch ($option) {
			case 'getPrecontactoByNro':
				$cf_993 = trim($request->get('lead_no'));
				$json = $this->getPrecontactoByNro($cf_993 );
				break;
			case 'getPrecontactoByEmail':
				$email = trim($request->get('email'));
				$json = $this->getPrecontactoByEmail($email );
				break;
			case 'updateLead': 
				$json = $this->updateLead( $request );
				break;
			case 'getUbigeo': 
				$value = trim($request->get('value'));
				$json = $this->getUbigeo( $value );
				break;
		}
		echo $json;
		exit();
	}

	public function getPrecontactoByEmail($email) {
		global $adb;
		$query = "SELECT crm.crmid FROM vtiger_leaddetails l INNER JOIN vtiger_crmentity crm on l.leadid = crm.crmid AND deleted = 0 
			WHERE lower(trim(l.email)) = ? ";
		$rs = $adb->pquery($query, array( strtolower(trim($email)) ) );
		$n = $adb->num_rows($rs);

		if ( $n > 0 ) {
			$leadid = $adb->query_result($rs, 0, 'crmid');
			$pre = Vtiger_Record_Model::getInstanceById($leadid, 'Leads');
			return json_encode( array( "status" => true, "result" => $pre->getData() ) );
		} else {
			return json_encode( array("status" => false) );
		}
	}

	public function getPrecontactoByNro($cf_993) {
		global $adb;
		$query = "SELECT crm.crmid FROM vtiger_leadscf l INNER JOIN vtiger_crmentity crm on l.leadid = crm.crmid AND deleted = 0 
			WHERE trim(l.cf_993) = ? ";
		$rs = $adb->pquery($query, array( trim($cf_993) ) );
		$n = $adb->num_rows($rs);

		if ( $n > 0 ) {
			$leadid = $adb->query_result($rs, 0, 'crmid');
			$pre = Vtiger_Record_Model::getInstanceById($leadid, 'Leads')->getData();
			if ( $pre['leadstatus'] == 'Registrado' ) {
				return json_encode( array( "status" => true, "result" => $pre ) );
			} else {
				return json_encode( array( "status" => false, "result" => $pre ) );
			}
		} else {
			return json_encode( array("status" => false, "result" => null ) );
		}
	}
	
	public function updateLead($request) {
		$leadid = $request->get('leadid');
		$formulario = $request->get('formulario');
		$redirect = "Proyectosluminaria";
		$email = $request->get('email');
		$codigo_ubigeo = $request->get('cf_995');
		// if ( $formulario == 'Proyectos' ) {
			$tipo_requerimiento = $request->get('cf_981');
			$metros_cuadrados = $request->get('cf_971');
			$nro_trabajadores = $request->get('noofemployees');
			$ubigeo = explode('-', $request->get('ubigeo'))[1];
			$lugar_implementacion = $request->get('cf_977');
			$productos = $request->get('productos_string');
			$departamento = $request->get('pobox');
			$provincia = $request->get('state');
			$distrito = $request->get('city');
			$ubigeocrm = $request->get('ubigeocrm');
			// var_dump($request);
			// var_dump($nro_trabajadores);
			// die();
			

			$pre = Vtiger_Record_Model::getInstanceById($leadid, 'Leads');
			$datos = $pre->getData();
			$pre->set("mode", "edit");
			$pre->set("leadstatus", 'Pre Qualified'); // pre calificado
			$pre->set("cf_981", $tipo_requerimiento);
			$pre->set("cf_971", $metros_cuadrados);
			$pre->set("noofemployees", $nro_trabajadores);
			$pre->set("cf_975", $ubigeo);
			$pre->set("cf_977", $lugar_implementacion);
			$pre->set("cf_979", $productos);
			$pre->set("cf_995", $codigo_ubigeo);
			
			// $pre->set("leadstatus", 'Pre Qualified'); // pre calificado

			// if(!empty($direccion)) $pre->set("lane", $direccion);
			if(!empty($departamento)) $pre->set("city", $departamento);
			if(!empty($provincia)) $pre->set("state", $provincia);
			if(!empty($distrito)) $pre->set("pobox", $distrito);
			if(!empty($ubigeocrm)) $pre->set("cf_999", $ubigeocrm);

			
		// } 

		$pre->save();

		$nombre = $datos['firstname']." ".$datos['lastname'];
		$email = $datos['email'];
		
		$url_return = "http://fursysperu.com.pe/proyectos/gracia?email=$email&nombre=$nombre&form=form2";
		header("Location: $url_return");
	}

	public function getUbigeo($value) {
		global $adb;
		// $adb->setDebug(true);
		$query = "SELECT * FROM vtiger_ubigeo INNER JOIN vtiger_crmentity ON ubigeoid = crmid AND deleted = 0  WHERE ubigeo_tks_distrito like concat('%',?,'%')";
		$rs = $adb->pquery($query, array( strtolower(trim($value)) ) );
		$n = $adb->num_rows($rs);
		$arr = $arr_ = array();

		while ($row = $adb->fetch_row($rs)) {
			$row = array_map(function($val){
				return html_entity_decode($val);
			}, $row);
			$arr_[trim($row['ubigeo_tks_combinado'])] = $row;
		}
		foreach($arr_ as $row) { 
			$arr[] = $row;
		}
		
		if ( $n > 0 ) {
			return json_encode( array( "status" => true, "result" => $arr ) );
		} else {
			return json_encode( array("status" => false) );
		}
	}
}
$track = new Ajax_Action();
$track->process(new Vtiger_Request($_REQUEST));

