<?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.
 * ********************************************************************************** */
// Switch the working directory to base
chdir(dirname(__FILE__) . '/../..');

//header("Access-Control-Allow_origin: *");
//header("Access-Control-Allow-Methods: GET, POST, OPTIONS"):

include_once 'includes/Loader.php';
include_once 'include/Zend/Json.php';
include_once 'vtlib/Vtiger/Module.php';
include_once 'include/utils/VtlibUtils.php';
include_once 'include/Webservices/Create.php';
include_once 'modules/Webforms/model/WebformsModel.php';
include_once 'modules/Webforms/model/WebformsFieldModel.php';
include_once 'include/QueryGenerator/QueryGenerator.php';
include_once 'includes/runtime/EntryPoint.php';
include_once 'includes/main/WebUI.php';
include_once 'include/Webservices/AddRelated.php';

class Webform_Capture {
	protected $webform;

	function captureNow($request) {
		global $formularios_landing;

		$isURLEncodeEnabled = $request['urlencodeenable'];
		$currentLanguage = Vtiger_Language_Handler::getLanguage();
		$moduleLanguageStrings = Vtiger_Language_Handler::getModuleStringsFromFile($currentLanguage);
		vglobal('app_strings', $moduleLanguageStrings['languageStrings']);

		$formularios_landing = array(
			"LANDING_GENERICO_LEASING" 		=> "7cb7432e757b132b5b3a0e5ce1fadac5",
			"LANDING_GENERICO_FACTORING" 	=> "835399539458f2269f93ad3947b3ca21",
			"LANDING_DINAMICO_LEASING" 		=> "7e43bae93f5285b293024c0fe8335c60",
			"LANDING_DINAMICO_FACTORING" 	=> "c1403ff68cc2dd99557cdefa68bbc2ec",
		);

		$utm = array(
			"utmsource" => "cf_992", // UTM Sourc
			"utmmedium" => "cf_994", // UTM Medium
			"utmcampaign" => "cf_996", // UTM Campaign
		);

		$returnURL = false;
		try {
			if (!vtlib_isModuleActive('Webforms'))
				throw new Exception('webforms is not active');

			// Henry: busca el formulario por el nombre
			$webform = Webforms_Model::retrieveWithName(vtlib_purify($request['publicid']));
			if ( empty($webform) ) {
				$webform = Webforms_Model::retrieveWithPublicId(vtlib_purify($request['publicid']));
			}

			if (empty($webform))
				throw new Exception("Webform not found.");
			
			$request['publicid'] = $webform->data['publicid'];

			$this->webform = $webform;// BR: para poder usarlo cuando se resetee el roundrobin

			if(empty($request['RESPONSE_FORM'])){
				$returnURL = "https://totalserviciosfinancieros.com.pe/gracias-leasing";
			}
			else{
				$returnURL = $request['RESPONSE_FORM'];
			}

			//$returnURL = "https://leasingtotal.com.pe/gracias-leasing";
			$roundrobin = $webform->getRoundrobin();
			//--Henry 20-07-18 -- para validar si está habilitado el captcha
			if ( ( $webform->data['captcha'] == "1" ) && empty($_REQUEST["g-recaptcha-response"]) ) {
				$this->sendResponse($returnURL, 'error');
				return;
			}
			$ip = $_SERVER['REMOTE_ADDR'];

			// Retrieve user information
			$user = CRMEntity::getInstance('Users');
			$user->id = $user->getActiveAdminId();
			$user->retrieve_entity_info($user->id, 'Users');

			// Prepare the parametets
			$parameters = array();
			$webformFields = $webform->getFields();
			foreach ($webformFields as $webformField) {
				if ($webformField->getDefaultValue() != null) {
					//-- Henry 25-04-18 -- cuando se trabaja con valores por default
					if ( !empty($request[$webformField->getFieldName()]) ) {
						$parameters[$webformField->getFieldName()] = decode_html($request[$webformField->getFieldName()]);
					} else {
						$parameters[$webformField->getFieldName()] = decode_html($webformField->getDefaultValue());
					}
				} else {
					//If urlencode is enabled then skipping decoding field names
					if ($isURLEncodeEnabled == 1) {
						$webformNeutralizedField = $webformField->getNeutralizedField();
					} else {
						$webformNeutralizedField = html_entity_decode($webformField->getNeutralizedField(), ENT_COMPAT, "UTF-8");
					}

					if (isset($request[$webformField->getFieldName()])) {
						$webformNeutralizedField = $webformField->getFieldName();
					}
					if (is_array(vtlib_purify($request[$webformNeutralizedField]))) {
						$fieldData = implode(" |##| ", vtlib_purify($request[$webformNeutralizedField]));
					} else {
						$fieldData = vtlib_purify($request[$webformNeutralizedField]);
						$fieldData = decode_html($fieldData);
					}

					$parameters[$webformField->getFieldName()] = stripslashes($fieldData);
				}
				if ($webformField->getRequired()) {
					if (!isset($parameters[$webformField->getFieldName()]))
						throw new Exception("Required fields not filled");
				}
			}

			if ($roundrobin) {
				$ownerId = $webform->getRoundrobinOwnerId();
				$ownerType = vtws_getOwnerType($ownerId);
				$parameters['assigned_user_id'] = vtws_getWebserviceEntityId($ownerType, $ownerId);
			} else {
				$ownerId = $webform->getOwnerId();
				$ownerType = vtws_getOwnerType($ownerId);
				$parameters['assigned_user_id'] = vtws_getWebserviceEntityId($ownerType, $ownerId);
			}
			// Henry: aplicar round robin de la campaña  // Se comentaron para respetar la asignación por rounf robin del formulario
			$cod = trim($request['CAMPAIGN_NO']);
			if ( $cod != '' ) {
				global $adb;
				// $adb->setDebug(true);
				$rs = $adb->pquery("SELECT campaignid FROM vtiger_campaign where campaign_no = ?", array($cod));
				$campaignid = $adb->query_result($rs, 0, 'campaignid');
				if ( !empty($campaignid) ) {
					$parameters['campaignid'] = "8x".$campaignid;
				}
				$unidad = $request['opportunity_type'];
				//$parameters['assigned_user_id'] = $this->getUserIdRoundRobin($campaignid, $unidad);
			}
			
			// echo "<pre>";
			if ( in_array($request['publicid'], $formularios_landing) ) {
				// var_dump($parameters);
				$this->interceptaContactoPreSave($parameters, $request, $webform, $user, $returnURL);
				$parameters['potentialname'] = $request['opportunity_type']." - ".$request['tipobien'];
				$parameters['description'] = $request['comentario'];

				foreach ($utm as $id => $fieldname) {
					$parameters[$fieldname] = trim($request[$id]);
				}

				$fecha = new Datetime();
				$fecha->setTimezone(new DateTimeZone("America/Lima"));
				$dias = 7;
				if ( $request['opportunity_type'] == 'Leasing' ) {
					$dias = 30;
				} else if ( $request['opportunity_type'] == 'Factoring' ) {
					$dias = 7;
				}
				$fecha->modify("+$dias days");
				$fecha_estimada_cierre = $fecha->format("Y-m-d");

				$parameters['closingdate'] = $fecha_estimada_cierre;
			}

			$moduleModel = Vtiger_Module_Model::getInstance($webform->getTargetModule());
			$fieldInstances = Vtiger_Field_Model::getAllForModule($moduleModel);
			foreach ($fieldInstances as $blockInstance) {
				foreach ($blockInstance as $fieldInstance) {
					$fieldName = $fieldInstance->getName();
					if($fieldInstance->get('uitype') == 56 && $fieldInstance->getDefaultFieldValue() == '') {
						$defaultValue = $request[$fieldName];
					} else if (empty($parameters[$fieldName])) {
						$defaultValue = $fieldInstance->getDefaultFieldValue();
						if ($defaultValue) {
							$parameters[$fieldName] = decode_html($defaultValue);
						}
					} else if ($fieldInstance->get("uitype") == 71 || $fieldInstance->get("uitype") == 72) {
						//ignore comma(,) if it is currency field
						$parameters[$fieldName] = str_replace(",", "", $parameters[$fieldName]);
					}
				}
			}

			// New field added to show Record Source
			$parameters['leadsource'] = 'Página Web';
			$parameters['source'] = 'PAGINAWEB';
			// var_dump($parameters);
			// die();

			// Create the record
			$record = vtws_create($webform->getTargetModule(), $parameters, $user);
			$webform->createDocuments($record);

			$this->sendResponse($returnURL, 'ok');
			return;
		} catch (DuplicateException $e) {
			$sourceModule = $webform->getTargetModule();
			$mailBody = vtranslate('LBL_DUPLICATION_FAILURE_FROM_WEBFORMS', $sourceModule, vtranslate('SINGLE_'.$sourceModule, $sourceModule), $webform->getName(), vtranslate('SINGLE_'.$sourceModule, $sourceModule));

			$userModel = Users_Record_Model::getInstanceFromPreferenceFile($user->id);
			sendMailToUserOnDuplicationPrevention($sourceModule, $parameters, $mailBody, $userModel);

			$this->sendResponse($returnURL, false, $e->getMessage());
			return;
		} catch (Exception $e) {
			$this->sendResponse($returnURL, false, $e->getMessage());
			return;
		}
	}

	protected function sendResponse($url, $success = false, $failure = false) {
		if (empty($url)) {
			if ($success){
				$response = Zend_Json::encode(array('success' => true, 'result' => $success));
			}
			else{
				$response = Zend_Json::encode(array('success' => false, 'error' => array('message' => $failure)));
				$this->resetRoundrobin($this->webform); // Henry: para que no afecte el roundrobin
			}

			// Support JSONP
			if (!empty($_REQUEST['callback'])) {
				$callback = vtlib_purify($_REQUEST['callback']);
				echo sprintf("%s(%s)", $callback, $response);
			} else {
				echo $response;
			}
		} else {
			if (!$success) {
				$this->resetRoundrobin($this->webform); // Henry: para que no afecte el roundrobin
			}
			$pos = strpos($url, 'http');
			if ($pos !== false) {
				header(sprintf("Location: %s?%s=%s", $url, ($success ? 'success' : 'error'), ($success ? $success : $failure)));
			} else {
				header(sprintf("Location: http://%s?%s=%s", $url, ($success ? 'success' : 'error'), ($success ? $success : $failure)));
			}
		}
	}
	protected function resetRoundrobin($webform) {
		global $adb;
		$nextRoundrobinLogic = 0;
		$rs = $adb->pquery("SELECT roundrobin_logic,roundrobin_userid FROM vtiger_webforms where id = ?", array($webform->getId()));
		$data = array_map("decode_html", $adb->query_result_rowdata($rs));
		$roundrobin_userid = vtlib_purify($data["roundrobin_userid"]);
		$roundrobin_logic = vtlib_purify($data["roundrobin_logic"]);

		$useridList = json_decode($roundrobin_userid,true);
		$count = count($useridList);
		if ( $roundrobin_logic == 0 ) {
			$roundrobin_logic = $count-1;
		} else {
			$roundrobin_logic -= 1;
		}
		$adb->pquery("UPDATE vtiger_webforms SET roundrobin_logic = ? WHERE id = ?", array($roundrobin_logic, $webform->getId()));
		$adb->completeTransaction(); // henry: para que haga efecto el update
	}


	// Henry: para validar el duplicado de contactos, aumenta contador y actualiza fecha de registro
	protected function interceptaContactoPreSave(&$parameters, $request, $webform, $user, $returnURL) {
		global $adb, $formularios_landing;
		// $adb->setDebug(true);
		// error_reporting(-1);
		if ( in_array($request['publicid'], $formularios_landing) ) {
			$accountid = $this->interceptaCuentaPreSave($parameters, $request, $webform, $user, $returnURL);
		}
		$ruc = trim($request['siccode']);
		$tipo_persona = "Natural";
		
		$cuenta_id = explode("x", $accountid)[1];
		// Busca el contacto relacionado 
		$rs = $adb->pquery("SELECT * FROM vtiger_contactdetails c 
			inner join vtiger_crmentity e on c.contactid = e.crmid and e.deleted = 0
			where c.accountid = ? and c.email = ? order by c.contactid desc limit 1", array($cuenta_id, trim($request['email']) ));
		$contactid = '';
		if ( $adb->num_rows($rs) == 1 ) {
			$contactid = "12x".$adb->query_result($rs, 0, 'contactid');
		}

		if ( empty($contactid) ) {
			if ( substr($ruc, 0, 2) == "20" ) {
				// Cuando es persona juridica hay que crear el contacto con los datos del formulario
				$nombre = trim($request['firstname']);
				$apellido = trim($request['lastname']);
				$arr = explode(" ", $apellido);
				if ( empty($nombre) && count($arr) > 1 ) {
					$nombre = $arr[0];
					unset($arr[0]);
					$apellido = implode(" ", $arr);
				}
				$cont_parameters = array(
					'firstname' => $nombre, // Nombre
					'lastname' => $apellido, // Apellido
					'mobile' => trim($request['mobile']), // Movil / WhatsApp
					'account_id' => $accountid,
					'email' => trim($request['email']),
					'assigned_user_id' => $parameters['assigned_user_id'],
					'source' => 'PAGINAWEB',
				);


				$contact = vtws_create('Contacts', $cont_parameters, $user);
				$contactid = $contact['id']; // aqui retorna el id concatenado con 12x
			} else {
				// cuando es persona natural hay un workflow que crea el contacto, entonces hay que recuperarlo y actualizar el email y el movil
				$rs = $adb->pquery("SELECT * FROM vtiger_contactdetails c 
					inner join vtiger_crmentity e on c.contactid = e.crmid and e.deleted = 0
					where c.accountid = ? and c.email = 'POR COMPLETAR' and c.mobile = 'POR COMPLETAR' order by c.contactid desc limit 1", array($cuenta_id ));
				$contactid = $adb->query_result($rs, 0, 'contactid');
				if ( !empty($contactid) ) {
					$adb->pquery("UPDATE vtiger_contactdetails set email = ?, mobile = ? where contactid = ?", array( trim($request['email']), trim($request['mobile']), $contactid ));
					$contactid = "12x".$contactid;
				} else {
					// En caso no se haya creado el contacto con el workflow, pues aquí lo creamos ya que es necesario guardar su información
					$nombre = trim($request['firstname']);
					$apellido = trim($request['lastname']);
					$arr = explode(" ", $apellido);
					if ( empty($nombre) && count($arr) > 1 ) {
						$nombre = $arr[0];
						unset($arr[0]);
						$apellido = implode(" ", $arr);
					}
					$cont_parameters = array(
						'firstname' => $nombre, // Nombre
						'lastname' => $apellido, // Apellido
						'mobile' => trim($request['mobile']), // Movil / WhatsApp
						'account_id' => $accountid,
						'email' => trim($request['email']),
						'assigned_user_id' => $parameters['assigned_user_id'],
						'source' => 'WEBFORM',
					);
					$contact = vtws_create('Contacts', $cont_parameters, $user);
					$contactid = $contact['id']; // aqui retorna el id concatenado con 12x
				}
			}
		}
		$parameters['contact_id'] = $contactid;
		return $contactid;
	}
	protected function interceptaCuentaPreSave(&$parameters, $request, $webform, $user, $returnURL) {
		global $adb;
		$ruc = trim($request['siccode']);
		$tipo_persona = "Natural";
		$nombre_cuenta = "POR COMPLETAR";
		$nombre = trim($request['firstname']);
		$apellido = trim($request['lastname']);
		if ( !empty($request['accountname']) ) {
			$nombre_cuenta = trim($request['accountname']);
		}
		if ( substr($ruc, 0, 2) == "20" ) {
			$tipo_persona = "Juridica";
			$nombre = "";
			$apellido = "";
		} else {
			$nombre_cuenta = trim($request['firstname']) ." ".trim($request['lastname']);
			$arr = explode(" ", $nombre_cuenta);
			if ( empty($nombre) && count($arr) > 1 ) {
				$nombre = $arr[0];
				unset($arr[0]);
				$apellido = implode(" ", $arr);
			}
		}
		$leadsource = "Landing Page";
		if ( !empty($request['leadsource']) ) {
			$leadsource = trim($request['leadsource']);
		}
		$rs = $adb->pquery("SELECT * FROM vtiger_account a 
				inner join vtiger_crmentity e on a.accountid = e.crmid and e.deleted = 0 
				where a.siccode = ?",array(trim($request['siccode'])));
		$accountid = trim($adb->query_result($rs, 0, 'accountid'));
		if ( empty($accountid) || $accountid == 0 ) {
			$acc_parameters = array(
				'cf_852' => $tipo_persona, // Tipo de persona
				'siccode' => $request['siccode'],
				'cf_908' => $nombre, // Nombre
				'cf_910' => $apellido, // Apellido
				'accountname' => $nombre_cuenta,
				'leadsource' => "Página Web",
				'assigned_user_id' => $parameters['assigned_user_id'],
				'accounttype' => 'Nuevo',
				// 'cf_884' => "POR COMPLETAR", // Aceptantes 1
				// 'cf_894' => "POR COMPLETAR", // Sector de Frente de Trabajo 1
				'bill_country' => "36x2168", // Ubigeo = POR COMPLETAR
				'source' => 'PAGINAWEB',
			);

			$account = vtws_create('Accounts', $acc_parameters, $user);
			
			$accountid = $account['id']; // aqui retorna el id concatenado con 11x
		} else {
			#Evita que se creen oportunidades duplicadas, si ya la cuenta tiene una oportunidad creada hace 2 minutos ya no crea otra.
			$fecha = date('Y-m-d H:i:s');
			$adbR = $adb->pquery('SELECT p.potentialid FROM vtiger_potential p JOIN vtiger_crmentity c ON c.crmid = p.potentialid WHERE p.related_to = ? AND c.createdtime > date("'.date('Y-m-d H:i:s',strtotime($fecha.' -2 minutes')).'") AND c.source="PAGINAWEB"',[$accountid]);
			if($adb->num_rows($adbR) > 1)
			{
				throw new Exception('duplicado');
			}
			$accountid = '11x'.$accountid;
		}
		$parameters['related_to'] = $accountid; // parameters le pertenece a Oportundiad, el campo cuenta en oportunidad es related_to
		return $accountid;
	}

	/*
	Henry Creantis: roundrobin
	*/
	public function getUserIdRoundRobin($campaignid, $unidad) {
	    global $adb;
	    $field_asignar_a = "cf_1001";

	    $rs = $adb->pquery("SELECT $field_asignar_a, roundrobin_userid, roundrobin_logic, smownerid 
	    	FROM vtiger_campaignscf cf 
	    	inner join vtiger_crmentity e on cf.campaignid = e.crmid and e.deleted = 0
	    	where cf.campaignid = ?", array($campaignid));
	    $data = array_map("decode_html", $adb->query_result_rowdata($rs));

	    $smownerid = "19x".$data['smownerid'];

	    if ( !empty($data["roundrobin_userid"]) ) {
		    $roundrobin_logic = json_decode($data["roundrobin_logic"],true);
		    $useridList = json_decode($data["roundrobin_userid"],true);

		    if ( isset($roundrobin_logic[$unidad]) ) {
			    $roundrobin_logic_unidad = $roundrobin_logic[$unidad];
			    
			    if($roundrobin_logic_unidad >= count($useridList))
			        $roundrobin_logic_unidad=0;

			    $roundrobinOwnerId = $useridList[$unidad][$roundrobin_logic_unidad];
			    $nextRoundrobinLogic = ($roundrobin_logic_unidad+1)%count($useridList[$unidad]);
			    $roundrobin_logic[$unidad] = $nextRoundrobinLogic;
			    
			    $roundrobin_logic = (object) $roundrobin_logic;
				$roundrobin_logic = json_encode($roundrobin_logic);

			    $adb->pquery("UPDATE vtiger_campaignscf SET roundrobin_logic = ? WHERE campaignid = ?", array($roundrobin_logic, $campaignid));
			    return "19x".vtlib_purify($roundrobinOwnerId);
		    } else {
	    		// En caso no tenga configurados los usuarios para la unidad de round robin, retorna el usuario asignado a la campaña
		    	return "19x".$smownerid;
		    }
	    } else {
	    	// En caso no tenga configurados los usuarios de round robin, retorna el usuario asignado a la campaña
	    	return "19x".$smownerid;
	    }
	}
}

// NOTE: Take care of stripping slashes...
$webformCapture = new Webform_Capture();
$request = vtlib_purify($_REQUEST);
$isURLEncodeEnabled = $request['urlencodeenable'];
//Do urldecode conversion only if urlencode is enabled in a form. 
if ($isURLEncodeEnabled == 1) {
	$requestParameters = array();
	// Decoding the form element name attributes.
	foreach ($request as $key => $value) {
		$requestParameters[urldecode($key)] = $value;
	}
	//Replacing space with underscore to make request parameters equal to webform fields
	$neutralizedParameters = array();
	foreach ($requestParameters as $key => $value) {
		$modifiedKey = str_replace(" ", "_", $key);
		$neutralizedParameters[$modifiedKey] = $value;
	}
	$webformCapture->captureNow($neutralizedParameters);
} else {
	$webformCapture->captureNow($request);
}
