AnonSec Shell
Server IP : 162.214.74.102  /  Your IP : 216.73.216.192
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/console/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

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

use phpDocumentor\Reflection\DocBlock\Tags\Var_;
include_once __DIR__ . "/../api/WiserLeadsHelper.php";
include_once __DIR__ . "/../LeadsManagementHelper.php";
include_once __DIR__ . "/../google/GoogleYoutube.php";
include_once __DIR__ . "/../hubspot/Hubspot.php";
include_once __DIR__ . "/../CrawlerHelper.php";

class Utils {

    protected $hubspotHelper;

    public function FixAlttextDevelopmentImgs($ids = null){
        //TODO: desabilitado por segurança
        echo "desabilitado por segurança"; exit;
        $imgs = ORM::for_table("module_imobles_enterprise_imgs")
                    ->where_not_null("description")
                    ->where_not_equal("description", '')
                    ->where("type", "backend")
                    ->where("module_imobles_enterprise_id",42990)
                    ->find_many();


        $arr_imgs_insert = array();
        $insert_imgs = false;
        $count = 0;
        foreach ($imgs as $img)
        {
            $count++;
            $imgDescAux = str_replace("&nbsp;"," ",$img->description);
            $imgDescAux = strip_tags($imgDescAux);
            echo $imgDescAux."\n".$img->description."\n".$img->alt_text."\n\n";
            $img->description = $imgDescAux;
            if(empty($img->alt_text))
            {
                $img->alt_text = $img->description; 
            }
            $img->save();
        }
        echo "Total de imagens tratadas:".$count;
    }


    public function reveiwLostLeads(){   
        //TODO: desabilitado por segurança
        echo "desabilitado por segurança"; exit;
        @ini_set('memory_limit', '40095M');
        @ini_set('max_execution_time', 0);
        @set_time_limit(0);
        
        $file = 'application/storage/LostLeads.csv';
        $csv = new parseCSV();
        $csv->auto($file);
        $leads = $csv->data;
        $count = 0;
        $countTotal = 0;
        foreach ($leads as $lead) 
        {   
            if(!empty($lead['params'])){
                $request_payload = $lead['params'];
                $request_payload = json_decode($request_payload);

                var_dump($request_payload->conversion_details->context->page_uri);continue;
                if(!empty($request_payload->conversion_details->context->page_uri)){
                    $request_payload->conversion_details->context->page_uri = explode('?',$request_payload->conversion_details->context->page_uri);
                    $request_payload->conversion_details->context->page_uri = $request_payload->conversion_details->context->page_uri[0];
                }

                if(empty($request_payload->conversion_details->context->ip_address)){
                    $request_payload->conversion_details->context->ip_address = null;
                }

                if(empty($request_payload->conversion_details->context->hutk)){
                    $request_payload->conversion_details->context->hutk = null;
                }
                $request_payload = json_encode($request_payload);
                // var_dump($request_payload);exit;
            } else {
                continue;
                $phone_number = $lead['phone'];
                $phone_number_short = null;
                $country_code = 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;
                $request_payload = '{
                    "client_details": {
                        "first_name": "'.$lead['account'].'",
                        "phone": {
                            "country_code": 55,
                            "number": 4884071889
                        }
                    },
                    "conversion_details": {
                        "conversion_type": "solicitacao_de_lista",
                        "conversion_fields": [
                            {
                                "field": "city_ids",
                                "value": 3333555
                            },
                            {
                                "field": "canal_de_contato",
                                "value": "Formulario Site"
                            },
                            {
                                "field": "apto_de_interesse_atual",
                                "value": "Me ligue - Falar com especialista | Sobre a imobles"
                            }
                        ],
                        "context": {
                            "hutk": "",
                            "page_name": "imobles | Revolucionando a forma de comprar imóvel no Brasil",
                            "page_uri": "http://localhost:3000/",
                            "ip_address": "",
                            "hs_form_id": "eb72d8d2-fa25-4ef4-af88-6ad09cfa751b"
                        }
                    },
                    "crm_details": {
                        "digisac": {
                            "service_id": "6221e13e-ca1f-434d-8656-7cc0bb49425d"
                        }
                    }
                }';
            }
            $url = 'https://rocket.myside.com.br/?ng=api&key=787vrygo5tsuqvq6xn7bcjexxe63dppanmw5b3j6&method=plugin&plugin=module_imobles&pl_method=saveLead';
            $apiRequest = curl_init($url);
            curl_setopt($apiRequest, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($apiRequest, CURLOPT_POST, 1);
            curl_setopt($apiRequest, CURLOPT_POSTFIELDS, $request_payload);
            $json_response = curl_exec($apiRequest);
            $result = json_decode($json_response);
            var_dump($result->return);
        }
    }

    public function updateDevelopmentGoogle() {
        $google = new GoogleMaps();
        $developments = ORM::for_table('module_imobles_enterprise')
        ->select('id')
        ->select('google_place_id')
        ->where_not_null('google_place_id')
        ->where_null('delete_at')
        ->where('imobles_client',1)
        ->where('site_enabled',1)
        ->find_many();

        foreach($developments as $development){
            var_dump($development->id);
            $placeDetails = $google->placeDetails($development->google_place_id);
            if(isset($placeDetails->place_id)){
                $development->google_json = json_encode($placeDetails);

                if(isset($placeDetails->geometry) && !empty($placeDetails->geometry)){
                    $development->google_geometry = json_encode($placeDetails->geometry);    
                }
                
                if(isset($placeDetails->formatted_phone_number) && !empty($placeDetails->formatted_phone_number)){
                    $development->google_phone = $placeDetails->formatted_phone_number;    
                }

                if(isset($placeDetails->plus_code) && !empty($placeDetails->plus_code)){
                    $development->google_plus_code = json_encode($placeDetails->plus_code);    
                }

                if(isset($placeDetails->rating) && !empty($placeDetails->rating)){
                    $development->google_rating = $placeDetails->rating;    
                }

                if(isset($placeDetails->reference) && !empty($placeDetails->reference)){
                    $development->google_reference = $placeDetails->reference;    
                }

                if(isset($placeDetails->reviews) && !empty($placeDetails->reviews)){
                    $development->google_reviews = json_encode($placeDetails->reviews);    
                }

                if(isset($placeDetails->user_ratings_total) && !empty($placeDetails->user_ratings_total)){
                    $development->google_user_ratings_total = $placeDetails->user_ratings_total;    
                }
                $development->updated_at = date('Y-m-d H:i:s');
                $development->save();
            }
        }
    }   

    public function fixListingsPrices(){

        //TODO: desabilitado por segurança
        echo "desabilitado por segurança"; exit;
        $csv = new parseCSV();
        $contents = file_get_contents('application/plugins/module_imobles/listingsPricesFinal.csv');
        $csvData = $csv->parse_string($contents);

        $listing = null;
        $lastUnitTypeID = 0;
        $unit_type_id = null;
        $listing_id_aux = null;
        $listing_date = null;
        foreach ($csvData as $c) {
            if($unit_type_id != $c['unit_type_id']){
                $unit_type_id = $c['unit_type_id'];
                $sql = "SELECT 
                                id
                            FROM
                                module_imobles_listings
                            WHERE
                                crawler_type_id = 4
                                    AND advertiser_id IS NULL
                                    AND unit_type_id = ".$unit_type_id."
                            ORDER BY id ASC
                            LIMIT 1;";
                $listing_aux = ORM::for_table('module_imobles_listings')->raw_query($sql)->find_one();
                if(isset($listing_aux->id)){
                    $listing_id_aux = $listing_aux->id;
                } else {
                    $listing_id_aux = null;
                }
            } else {
                $date_aux = new DateTime($c['month']);
                $listing_date_aux = $date_aux->format('Y-m-d 23:59:59');
                if($listing_date_aux == $listing_date){
                    continue;
                }
            }
            
            $price = intval($c['price']);
            if($price == 0){
                continue;
            }
            $date = new DateTime($c['month']);
            $listing_date = $date->format('Y-m-d 23:59:59');
            $sql = "SELECT lp.*
                    FROM module_imobles_listings_prices as lp
                    JOIN module_imobles_listings as l ON l.id = lp.listing_id
                    WHERE l.crawler_type_id = 4 AND l.advertiser_id IS NULL
                    AND lp.price >= ".$price." AND lp.price < ".($price + 2)."
                    AND lp.date NOT LIKE '%23:59:59%'
                    AND lp.unit_type_id = ".$unit_type_id;
            $listings = ORM::for_table('module_imobles_listings_prices')->raw_query($sql)->find_many();
            if(count($listings) > 0){
                foreach($listings as $listing){
                    // Faço o update das datas dos registros
                    $listing->date = $listing_date;
                    $listing->save();
                    echo $listing_date." | ".$price. " | ". $unit_type_id." | ATUALIZADO \n";
                }
            } else {
                // crio um novo registro com o valor e data não encontrado
                if(!empty($listing_id_aux)){
                    $sql = "SELECT lp.*
                            FROM module_imobles_listings_prices as lp
                            WHERE lp.price = ".$price."
                            AND lp.unit_type_id = ".$unit_type_id."
                            AND lp.date = '".$listing_date."'
                            AND lp.unit_type_id = ".$unit_type_id;
                    $listings = ORM::for_table('module_imobles_listings_prices')->raw_query($sql)->find_one();
                    if(!isset($listings->id)){
                        $listingPrice = ORM::for_table('module_imobles_listings_prices')->create();
                        $listingPrice->listing_id   = $listing_id_aux;
                        $listingPrice->unit_type_id = $unit_type_id;
                        $listingPrice->price        = $price;
                        $listingPrice->date         = $listing_date;
                        $listingPrice->save();
                        echo $listing_date." | ".$price. " | ". $unit_type_id." | REGISTRO INSERIDO COM SUCESSO \n";
                    } else {
                        echo $listing_date." | ".$price. " | ". $unit_type_id." | REGISTRO DUPLICADO \n";
                    }
                }
            }
        }


        // Pra cada UnitTypeID cadastrado, deletar os ListingsPrices com data igual a data do Listing
        $unitTypeIDs = ORM::for_table("module_imobles_listings_prices")
            ->distinct()
            ->select("unit_type_id")
            ->find_array();
        foreach($unitTypeIDs as $unitTypeID){
            $lps = ORM::for_table("module_imobles_listings_prices")
                ->select_expr("lp.id")
                ->table_alias("lp")
                ->left_outer_join("module_imobles_listings", "l.id = lp.listing_id AND lp.date = l.created_at", "l")
                ->where("lp.unit_type_id", $unitTypeID["unit_type_id"])
                ->where("l.crawler_type_id", 4)
                ->order_by_desc('lp.id')
                ->find_array();
            
            if($lps){
                $deleteLPs = array();
                foreach($lps as $lp) {
                    $deleteLPs[] = $lp['id'];
                    echo "REGISTRO EXCLUÍDO \n";
                }
                if(count($deleteLPs) > 0){
                    ORM::for_table('module_imobles_listings_prices')
                    ->where_id_in($deleteLPs)
                    ->delete_many();
                } else {
                    echo "NENHUM REGISTRO COM ERRO DE DATA ENCONTRADO \n";
                }
            } else {
                echo "NENHUM REGISTRO COM ERRO DE DATA ENCONTRADO \n";
            }
        }
        

        // Pra cada UnitTypeID cadastrado, localizar os ListingsPrices com data igual a data do Listings
        // $unitTypeIDs = ORM::for_table("module_imobles_listings_prices")
        //     ->distinct()
        //     ->select("unit_type_id")
        //     ->find_array();

        // foreach($unitTypeIDs as $unitTypeID){
        //     $lps = ORM::for_table("module_imobles_listings_prices")
        //         ->select_expr("lp.id, lp.listing_id")
        //         ->table_alias("lp")
        //         ->left_outer_join("module_imobles_listings", "l.id = lp.listing_id AND lp.date = l.created_at", "l")
        //         ->where("lp.unit_type_id", $unitTypeID["unit_type_id"])
        //         ->where("l.crawler_type_id", 4)
        //         ->order_by_desc('lp.id')
        //         ->find_many();

        //     $listingsIDs = array();
        //     $deleteLPs = array();
        //     foreach ($lps as $lp){
        //         if (!in_array($lp['listing_id'], $listingsIDs)){
        //             $listingsIDs[] = $lp['listing_id'];
        //         } else {
        //             $deleteLPs[] = $lp['id'];
        //         }
        //     }

        //     // Deleta os ListingsPrices com data repetida
        //     if(count($deleteLPs) > 0){
        //     // $deleteIDs = implode(', ', $deleteLPs);
        //     ORM::for_table('module_imobles_listings_prices')
        //         ->where_id_in($deleteLPs)
        //         ->delete_many();
        //     }
        // }

        // // Carrega CSV
        // $csv = new parseCSV();
        // $contents = file_get_contents('application/plugins/module_imobles/listingsPrices.csv');
        // $csvData = $csv->parse_string($contents);

        // $listing = null;
        // $lastUnitTypeID = 0;
        // foreach ($csvData as $c) {
        //     $date = date($c['month']);
        //     $unitTypeID = $c['unit_type_id'];
        //     $price = floatval(str_replace(',', '.', str_replace('.', '', $c['price'])));

        //     // Pra cada unitType distinto, buscar 1 listing para inclusão dos novos dados
        //     if ($unitTypeID <> $lastUnitTypeID){
        //         $lastUnitTypeID = $unitTypeID;

        //         // Pega um Listing do tipo de unidade para inclusão no ListingsPrices
        //         $listing = ORM::for_table("module_imobles_listings")
        //             ->where("unit_type_id", $unitTypeID)
        //             ->where("crawler_type_id", 4)
        //             ->find_one();
        //         if(!$listing){
        //             echo "\n\n!!!!!!!!! ERRO LOCALIZANDO ANÚNCIO !!!!!!!!!";
        //             echo "\nUnitTypeID: $unitTypeID\n";
        //             echo "\nNão cadastrar preços!\n\n";
        //             continue;
        //         }
        //     }

        //     // Busca um ListingPrice do tipo de Unidade pro mesmo mês e ano do novo
        //     $listingPrice = ORM::for_table("module_imobles_listings_prices")
        //         ->select_expr('lp.id, lp.price')
        //         ->table_alias("lp")
        //         ->where("lp.unit_type_id", $unitTypeID)                    
        //         ->where_raw("EXTRACT(YEAR_MONTH FROM lp.date) = EXTRACT(YEAR_MONTH FROM '$date')")
        //         ->order_by_desc('lp.id')
        //         ->find_one();

        //     // Se não existir, ou se o preço for diferente, cadastra o novo
        //    if($listing && (!$listingPrice || $listingPrice->price <> $price)){
        //         if($listingPrice && $listingPrice->price <> $price){
        //             ORM::for_table("module_imobles_listings_prices")
        //                 ->where("unit_type_id", $unitTypeID)                    
        //                 ->where_raw("EXTRACT(YEAR_MONTH FROM date) = EXTRACT(YEAR_MONTH FROM '$date')")
        //                 ->delete_many();
        //         }

        //         $listingPrice = ORM::for_table('module_imobles_listings_prices')->create();
        //         $listingPrice->listing_id   = $listing->id;
        //         $listingPrice->unit_type_id = $unitTypeID;
        //         $listingPrice->price        = $price;
        //         $listingPrice->date         = $date;
        //         $listingPrice->save();
        //     }
        // }
    }


    /*
     * reviewEnterpriseUrl
     * Função para alterar o padrão das URLs dos empreendimentos
     * 
     */
    public function reviewEnterpriseUrlsMySide(){
        //TODO: desabilitado por segurança
        echo "desabilitado por segurança"; exit;
        $enterprises = ORM::for_table("module_imobles_enterprise")
                ->select_many_expr('id,slug,site_url')
                ->where('sanitized', 1)
                ->where_not_null("slug")
                ->find_many();
        foreach ($enterprises as $enterprise)
        {
            $development_slug = $enterprise->slug;
            $check_slug = ORM::for_table("module_imobles_enterprise")
                        ->where_not_in('id',[$enterprise->id])
                        ->where("slug", $enterprise->slug)
                        ->find_one();
            if(isset($check_slug->id) && $check_slug->id > 0)
            {
                echo "Slug Duplicada.".$enterprise->id." | ".$enterprise->slug."\n";
            }
            else
            {
                $site_url = "https://myside.com.br/".$development_slug;
                if($enterprise->site_url != $site_url)
                {
                    echo $enterprise->site_url."\n";
                    echo $site_url."\n\n";
                    $enterprise->site_url = $site_url;
                    $enterprise->save();
                }
            }
        }
    }


    /*
     * reviewEnterpriseUrl
     * Função para alterar o padrão das URLs dos empreendimentos
     * 
     */
    public function reviewConstructionMySide(){
        //TODO: desabilitado por segurança
        echo "desabilitado por segurança"; exit;
        $enterprises = ORM::for_table("module_imobles_company_construction")
                ->select_many_expr('id,slug,site_url')
                ->where_not_null("slug")
                ->find_many();
        foreach ($enterprises as $enterprise)
        {
            $development_slug = $enterprise->slug;
            $check_slug = ORM::for_table("module_imobles_company_construction")
                        ->where_not_in('id',[$enterprise->id])
                        ->where("slug", $enterprise->slug)
                        ->find_one();
            if(isset($check_slug->id) && $check_slug->id > 0)
            {
                echo "Slug Duplicada.".$enterprise->id." | ".$enterprise->slug."\n";
            }
            else
            {
                $site_url = "https://myside.com.br/".$development_slug;
                if($enterprise->site_url != $site_url)
                {
                    echo $enterprise->site_url."\n";
                    echo $site_url."\n\n";
                    $enterprise->site_url = $site_url;
                    $enterprise->save();
                }
            }
        }
    }


    public function reveiwLeadsWithoutProduct() {   
        @ini_set('memory_limit', '40095M');
        @ini_set('max_execution_time', 0);
        @set_time_limit(0);

        //TODO: desabilitado por segurança
        echo "desabilitado por segurança"; exit;


        
        $file = 'application/plugins/module_imobles/reenvio_conversoes_wiserads.csv';
        $csv = new parseCSV();
        $csv->auto($file);
        $leads = $csv->data;
        $count = 0;
        $countTotal = 0;
        $leadsManagementHelper = new LeadsManagementHelper();
        $arr_wl_ids = array();
        foreach ($leads as $lead) 
        {   
            if(!empty($lead['params'])){
                $request_payload = $lead['params'];
                $request_payload = json_decode($request_payload);

                if(!empty($request_payload->conversion_details->context->page_uri)){
                    $request_payload->conversion_details->context->page_uri = explode('?',$request_payload->conversion_details->context->page_uri);
                    $request_payload->conversion_details->context->page_uri = $request_payload->conversion_details->context->page_uri[0];
                }

                if(empty($request_payload->conversion_details->context->ip_address)){
                    $request_payload->conversion_details->context->ip_address = null;
                }

                if(empty($request_payload->conversion_details->context->hutk)){
                    $request_payload->conversion_details->context->hutk = null;
                }
                $request_payload = json_encode($request_payload);
                $data = json_decode($request_payload, true);


                $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;
                $account = ORM::for_table('crm_accounts')
                                ->where_raw('trim(replace(replace(replace(replace(phone, " ", ""), "-", ""), "(", ""), ")", "")) ="' . $phone . '"')->find_many();
                if (count($account) == 0) {
                    echo "LEAD NÃO CADASTRADO \n";
                    continue;
                } else {
                    $crmA = $account[0];
                    $arr_wl_ids_aux = array();
                    $arr_createat = null;
                    $conversion = ORM::for_table('module_imobles_leads_conversion')
                                    ->where('crm_accounts_id', $crmA->id)
                                    ->where_null('leads_product_id')->find_one();
                    if(isset($conversion->created_at)){
                        $arr_createat = $conversion->created_at;
                    }
                    $wiserLeadsAux = ORM::for_table('module_imobles_leads_wiserleads_contacts')
                                    ->where('crm_account_id', $crmA->id)->find_many();
                    if(count($wiserLeadsAux) > 0){
                        foreach($wiserLeadsAux as $wl){
                            $arr_wl_ids_aux[] = $wl->wiserlead_id;
                        }
                        $arr_wl_ids[] = array("name" => $crmA->account,
                                            "phone" => $crmA->phone,
                                            "wiserlead_ids" => $arr_wl_ids_aux,
                                            "created_at" => $arr_createat);
                    }
                    
                }
                // continue;
                $conversion_type_id = null;
                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) {
                            $conversion_type_id = $c->id;
                        }
                    }
                }

                if(empty($conversion_type_id)){

                    echo "TIPO DE CONVERSÃO NÃO ENCONTRADO \n";
                    continue;
                }

                $product_type = null;
                if(isset($conversion_type_id) && $conversion_type_id > 0){
                    $product_aux = $leadsManagementHelper->getProductDetails($data,$conversion_type_id);
                    if(isset($product_aux->id)){
                        $product_type = $product_aux->name;
                    } else {
                        var_dump($lead['params']);exit;
                        echo $data['conversion_details']['conversion_type']."\n";
                        echo "PRODUTO NÃO ENCONTRADO | ".$crmA->id. " | ".trim($data['client_details']['first_name'])." \n";
                        continue;
                    }
                } 
                continue;

                if($data['client_details']['first_name'] == 'Karina Takassaki ' || $data['client_details']['first_name'] == 'Wilma Leandro Rodrigues ' || $data['client_details']['first_name'] == 'Marcelo ramos do amaral '){
                    continue;
                }

                // Faço o envio dos dados para o WiserLeads
                if(isset($data['conversion_details']['context']['ppc_source']) && $data['conversion_details']['context']['ppc_source'] == 'google' && !empty($product_type)){
                    $data_aux = '{
                            "campaign": "imobles-google-ads",
                            "token": "e5e2ea4fd4c8c416219ec48487a96dc5a4bd09d2",
                            "url": "'.$data['conversion_details']['context']['page_uri'].'",
                            "referer": "'.@$data['conversion_details']['context']['referer'].'",
                            "user_agent": "",
                            "ip_address": "'.$data['conversion_details']['context']['ip_address'].'",
                            "firstname": "'.trim($data['client_details']['first_name']).'",
                            "lastname": "",
                            "phone": "'.$phone.'",
                            "email": "",
                            "metadata":{"product": "'.$product_type.'"}
                        }';
                    
                    $wiserLeads = new WiserLeadsHelper();
                    $results = $wiserLeads->postLead($data_aux);
                    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();
                        echo "ENVIO REALIZADO COM SUCESSO | ".$product_type. " | ".$crmA->id. " | ".trim($data['client_details']['first_name'])." \n";
                    } else {
                        echo "ERRO AO ENVIAR PARA WISERLEADS | ".$product_type. " | ".$crmA->id." | ".trim($data['client_details']['first_name'])." \n";
                        $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();
                    }
                }
            }
        }
        // var_dump(json_encode($arr_wl_ids));
    }


    public function resendWiserLeads() {   
        //TODO: desabilitado por segurança
        echo "desabilitado por segurança"; exit;


        
        // $file = 'application/plugins/module_imobles/reenvio_conversoes_wiserads.csv';
        // $csv = new parseCSV();
        // $csv->auto($file);


        // $sql = "SELECT c.*, p.name 
        //         FROM module_imobles_leads_conversion as c
        //         JOIN module_imobles_leads_products as p ON p.id = c.leads_product_id
        //         where c.created_at > '2022-10-25 19:44:45' AND c.leads_product_id IS NOT NULL";
        $sql = "SELECT 
                    *
                FROM
                    module_imobles_leads_conversion
                WHERE
                    LOWER(JSON_EXTRACT(params,
                                    '$.conversion_details.context.page_uri')) REGEXP '(geo=)'
                        AND LOWER(JSON_EXTRACT(params,
                                    '$.conversion_details.context.ppc_source')) NOT REGEXP '(google)'
                        AND created_at > '2023-06-18'
                        AND created_at < '2023-06-20'
                ORDER BY id DESC";
        $leads = ORM::for_table('module_imobles_listings')->raw_query($sql)->find_array();
        $count = 0;
        $countTotal = 0;
        $leadsManagementHelper = new LeadsManagementHelper();
        $arr_wl_ids = array();
        foreach ($leads as $lead) 
        {   
            if(!empty($lead['params'])){
                $request_payload = $lead['params'];
                $request_payload = json_decode($request_payload);

                // if(!empty($request_payload->conversion_details->context->page_uri)){
                //     $request_payload->conversion_details->context->page_uri = explode('?',$request_payload->conversion_details->context->page_uri);
                //     $request_payload->conversion_details->context->page_uri = $request_payload->conversion_details->context->page_uri[0];
                // }

                if(empty($request_payload->conversion_details->context->ip_address)){
                    $request_payload->conversion_details->context->ip_address = null;
                }

                if(empty($request_payload->conversion_details->context->hutk)){
                    $request_payload->conversion_details->context->hutk = null;
                }
                $request_payload = json_encode($request_payload);
                $data = json_decode($request_payload, true);

                $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;
                        }
                    }
                }

                $conversion_type_id = null;
                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) {
                            $conversion_type_id = $c->id;
                        }
                    }
                }
                
                if(empty($conversion_type_id)){

                    echo "TIPO DE CONVERSÃO NÃO ENCONTRADO \n";
                    continue;
                }

                $product_type = null;
                if(isset($conversion_type_id) && $conversion_type_id > 0){
                    $product_aux = $leadsManagementHelper->getProductDetails($data,$conversion_type_id);
                    if(isset($product_aux['product']->id)){
                        $product_type = $product_aux['product']->name;
                    } else {
                        echo "PRODUTO NÃO ENCONTRADO | ".trim($data['client_details']['first_name'])." \n";
                        continue;
                    }
                }
                
                // if($data['client_details']['first_name'] == 'frederico parreira' || $data['client_details']['first_name'] == 'Brunna Yasmin da Silva Carvalho'){
                //     continue;
                // }

                // Faço o envio dos dados para o WiserLeads
                // var_dump($product_type);
                // if(isset($data['conversion_details']['context']['ppc_source']) 
                //     && $data['conversion_details']['context']['ppc_source'] == null
                //     && !empty($product_type)){
                        $data_aux = '{
                                "campaign": "imobles-google-ads",
                                "token": "e5e2ea4fd4c8c416219ec48487a96dc5a4bd09d2",
                                "url": "'.$data['conversion_details']['context']['page_uri'].'",
                                "referer": "'.@$data['conversion_details']['context']['referer'].'",
                                "user_agent": "",
                                "ip_address": "'.$data['conversion_details']['context']['ip_address'].'",
                                "firstname": "'.trim($data['client_details']['first_name']).'",
                                "lastname": "",
                                "phone": "'.$phone_number.'",
                                "email": "",
                                "metadata":{"product": "'.$product_type.'"}
                            }';
                    
                    
                    $wiserLeads = new WiserLeadsHelper();
                    $results = $wiserLeads->postLead($data_aux);
                    $arr_wl_ids_aux = array();
                    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 = $lead['crm_accounts_id'];
                        $lesdConParams->save();
                        echo "ENVIO REALIZADO COM SUCESSO | ".$product_type. " | ".$lead['crm_accounts_id']. " | ".trim($data['client_details']['first_name'])." \n";

                        $arr_wl_ids_aux[] = $results->lead_id;
                        $phone = $country_code . $phone_number;
                        $account = ORM::for_table('crm_accounts')->find_one($lead['crm_accounts_id']);
                        if (!isset($account->id)) {
                            echo "LEAD NÃO CADASTRADO \n";
                            continue;
                        } else {
                            $crmA = $account;
                            $wiserLeadsAux = ORM::for_table('module_imobles_leads_wiserleads_contacts')
                                            ->where('crm_account_id', $crmA->id)->find_many();
                            if(count($wiserLeadsAux) > 0){
                                foreach($wiserLeadsAux as $wl){
                                    $arr_wl_ids_aux[] = $wl->wiserlead_id;
                                }
                            }
                            $arr_wl_ids[] = array("name" => $crmA->account,
                                                    "phone" => $crmA->phone,
                                                    "wiserlead_ids" => $arr_wl_ids_aux,
                                                    "created_at" => $lead['created_at']);
                            
                        }
                    } else {
                        echo "ERRO AO ENVIAR PARA WISERLEADS | ".$product_type. " | ".$crmA->id." | ".trim($data['client_details']['first_name'])." \n";
                        $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();
                    }
                // }
            }
        }
        var_dump(json_encode($arr_wl_ids));
    }


    public function updateCompanyConstructionGoogle() {
        $developments = ORM::for_table('module_imobles_company_construction')
        ->select('id')
        ->select('google_place_id')
        ->where_not_null('google_place_id')
        ->where_null('delete_at')
        ->find_many();
        foreach($developments as $development){
            $url = 'https://maps.googleapis.com/maps/api/place/details/json?'
                                . 'key=AIzaSyDV8EiKB-3-jeqoB9qGR7oeQb-y9kLHoCU'
                                . '&place_id='.$development->google_place_id.'&language=pt-BR&reviews_no_translations=true';
            $json_google = curl_init($url);
            curl_setopt($json_google, CURLOPT_RETURNTRANSFER, true);
            $json_response = curl_exec($json_google);
            $result_details = json_decode($json_response);
            var_dump($result_details);exit;
            if(isset($result_details->status) && $result_details->status == 'NOT_FOUND'){
                echo "PLACE_ID NÂO ENCONTRADO: ".$development->id." | ".$development->google_place_id."\n";
                continue;
            }
            
            if(isset($result_details->result->place_id)){
                echo $development->id."\n";
                $development->google_place_json = json_encode($result_details);
                $development->updated_at = date('Y-m-d H:i:s');
                $development->save();
            }
        }
    }

    public function updateListingsTable() {
        echo "Desabilitado por segurança.";exit;
        $sql = "SELECT l.id as listing_id, t.id as tipology_id, t.module_imobles_enterprise_id as development_id
                FROM module_imobles_listings as l 
                JOIN module_imobles_enterprise_units_type as t ON t.id = l.unit_type_id
                where l.entreprise_id is null order by l.id DESC";
        $listings = ORM::for_table('module_imobles_listings_prices')->raw_query($sql)->find_many();
        $count = 0;
        foreach($listings as $listing){
            echo $listing->listing_id."\n";
            $listing_aux = ORM::for_table('module_imobles_listings')->find_one($listing->listing_id);
            $listing_aux->entreprise_id = $listing->development_id;
            $listing_aux->save();
            $count++;
        }
        echo $count;
    }

    public function updateEnterpriseYoutubeVideoInfo(){
        echo "\n\n=========== Atualização das Informações do vídeo do youtube dos Empreendimentos ===========";
        $google = new GoogleYoutube();        
        $enterprises = ORM::for_table('module_imobles_enterprise')
            ->where_null('delete_at')
            ->where_not_equal('youtube_video', "")
            ->find_many();
        foreach($enterprises as $e){
            $link = $e->youtube_video;
            echo "\n\nEmpreendimento: $e->name";
            echo "\nYoutube Link: $e->youtube_video";
            $youtube_json = $google->getVideoInfo($link);
            if ($youtube_json === false){
                echo "\nVídeo não localizado!";
            } else {
                $e->youtube_json = json_encode($youtube_json);
                $e->save();
                echo "\nInformações do vídeo Atualizadas!";
            }
        }
        echo "\n\n============ FIM ============\n\n";
    }

    public function syncLeadHistory(){
        echo "\n\n=========== Sincronização de Histórico de Leads ===========";
        $sql = "SELECT DISTINCT(hs_utk) as hs_utk FROM module_imobles_leads_history WHERE crm_account_id IS NULL ";
        $leads = ORM::for_table('module_imobles_listings_prices')->raw_query($sql)->find_many();
        $leadHelper = new LeadsManagementHelper();
        $count = 0;
        foreach($leads as $e){
            $verified = false;
            if(!empty($e->hs_utk)){
                $leadDetails = $leadHelper->hubspotGetContactDetailsByUtk($e->hs_utk);
                if(isset($leadDetails->{'canonical-vid'})){
                    $hs_lead = ORM::for_table('module_imobles_hubspot_contacts')
                        ->where('hs_object_id', $leadDetails->{'canonical-vid'})
                        ->find_one();
                    if(isset($hs_lead->crm_account_id)){
                        $sql = "UPDATE module_imobles_leads_history SET crm_account_id = ".$hs_lead->crm_account_id." WHERE hs_utk = '".$e->hs_utk."'";
                        ORM::for_table('module_imobles_listings_prices')->execute($sql);
                        $verified = true;
                    }
                }
            }

            if($verified == false){
                $sql = "UPDATE module_imobles_leads_history SET crm_account_id = 0 WHERE hs_utk = '".$e->hs_utk."'";
                        ORM::for_table('module_imobles_listings_prices')->execute($sql);
                $count ++;        
                echo "\n\n".$count." ============ LEAD NOT FOUND ============\n\n";
            } else {
                echo "\n\n============ SUCESSO ============\n\n";   
            }
        }
        echo "\n\n============ FIM ============\n\n";
    }

    public function syncLeadRocket($crawlerController){
        $this->hubspotHelper = new hubspotHelper();
        echo "\n\n=========== Sincronização dos leads no Rockt, Hubspot e Digisac ===========";
        $leads = ORM::for_table('crm_accounts')->where('status','Active')->find_many();
        foreach($leads as $e){
            echo $e->id.' | '.$e->account." | ".$e->phone." | ";
            if (preg_match_all("/(\s)+((test)e?)$|^((test)e?)(\s)+|(\s)+((test)e?)(\s)+|^((test)e?)$/i", $e->account, $matches)) {
                echo "TESTE - DESCONSIDERAR \n";
                $e->status = 'Inactive';
                $e->save();
            }
            if(!empty($e->phone)){
                $data = array('input_data' => ['client_details' => array('first_name' => $e->account)]);
                $data = json_decode(json_encode($data));
                $sinc = $this->hubspotHelper->hubspotSyncLead($e->id, $data, $crawlerController);
                if(isset($sinc['success']) && $sinc['success'] === false){
                    $e->phone = preg_replace('/\D/', '', $e->phone);
                    $data = array('input_data' => ['client_details' => array('first_name' => $e->account,'phone' => array('country_code' => 55, 'number' => $e->phone))]);
                    $data = json_decode(json_encode($data));
                    $sinc = $this->hubspotHelper->hubspotSyncLead($e->id, $data, $crawlerController);
                    if(isset($sinc['success']) && $sinc['success'] === false){
                        echo "CONTATO NÃO ENCONTRADO NO HS\n";
                    } else {
                        $e->phone = '55'.$e->phone;
                        $e->save();
                        echo "CONTATO SINCRONIZADO COM SUCESSO\n";
                    }
                } else {
                    echo "CONTATO SINCRONIZADO COM SUCESSO\n";
                }
            } else {
                $e->status = 'Inactive';
                $e->save();
                echo "CONTATO DELETADO | SEM PHONE\n";
            }
        }
        echo "\n\n============ FIM ============\n\n";
    }

    public function resendWiserLeadsPpcNull(){   
        $sql = 'SELECT * FROM module_imobles_leads_conversion
                WHERE LOWER(JSON_EXTRACT(params, "$.conversion_details.context.ppc_source" )) REGEXP "(null)"
                AND LOWER(JSON_EXTRACT(params, "$.client_details.first_name" )) NOT REGEXP "(teste)"
                AND  LOWER(JSON_EXTRACT(params, "$.conversion_details.context.referer" )) REGEXP "(utm_source=wiserads)"
                AND created_at > "2023-02-22"
                ORDER BY created_at desc;';
        $leads = ORM::for_table('module_imobles_listings')->raw_query($sql)->find_array();
        $count = 0;
        $countTotal = 0;
        $leadsManagementHelper = new LeadsManagementHelper();
        $arr_wl_ids = array();
        foreach ($leads as $lead) 
        {   
            if(!empty($lead['params'])){
                $request_payload = $lead['params'];
                $request_payload = json_decode($request_payload);

                if(!empty($request_payload->conversion_details->context->page_uri)){
                    // $request_payload->conversion_details->context->page_uri = explode('?',$request_payload->conversion_details->context->page_uri);
                    // $request_payload->conversion_details->context->page_uri = $request_payload->conversion_details->context->page_uri[0];
                }

                if(empty($request_payload->conversion_details->context->ip_address)){
                    $request_payload->conversion_details->context->ip_address = null;
                }

                if(empty($request_payload->conversion_details->context->hutk)){
                    $request_payload->conversion_details->context->hutk = null;
                }
                $request_payload = json_encode($request_payload);
                $data = json_decode($request_payload, true);
                $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;
                        }
                    }
                }

                

                // Faço o envio dos dados para o WiserLeads
                $hs_contact = ORM::for_table('module_imobles_hubspot_contacts')
                                        ->where('crm_account_id', $lead['crm_accounts_id'])
                                        ->find_one();
                if(isset($hs_contact->hs_object_id)){
                    $hs_contact_id = $hs_contact->hs_object_id;
                } else {
                    echo "ERRO - LEAD NÃO VINCULADO AO HUBSPOT | ".$lead['crm_accounts_id']."\n";
                    continue;
                }
                
                $leadsHelper = new LeadsManagementHelper;
                $send_wiserads = true;
                $hs_contacts_deals = $leadsHelper->hubspotGetDeals($hs_contact_id);
                $hs_deal_id = null;
                if(!empty($hs_contacts_deals))
                {
                    foreach($hs_contacts_deals as $hs_deal)
                    {
                        if($hs_deal->properties->status_do_deal == 'Aberto - Conversando')
                        {
                            $deal_aux = ORM::for_table('module_imobles_leads_wiserleads_contacts')
                                        ->where('hs_deal_id', $hs_deal->id)
                                        ->find_one();
                            if(isset($deal_aux->id)){
                                $send_wiserads = false;
                                echo "ERRO - CONVERSÃO JÁ ENVIADA PARA WISERLEADS | ".$lead['crm_accounts_id']."\n";
                            } else {
                                $hs_deal_id = intval($hs_deal->id);
                            }
                        }
                    }
                }

                if($send_wiserads === true){
                    $product_type_aux = ORM::for_table('module_imobles_leads_products')
                                        ->find_one($lead['leads_product_id']);
                    if(isset($product_type_aux->name)){
                        $product_type = $product_type_aux->name;
                    } else {
                        echo "ERRO - PRODUTO NÃO ENCONTRADO | ".$lead['crm_accounts_id']."\n";
                        continue;
                    }
                    $data_aux = '{
                        "campaign": "imobles-google-ads",
                        "token": "e5e2ea4fd4c8c416219ec48487a96dc5a4bd09d2",
                        "url": "'.$data['conversion_details']['context']['page_uri'].'",
                        "referer": "'.@$data['conversion_details']['context']['referer'].'",
                        "user_agent": "",
                        "ip_address": "'.$data['conversion_details']['context']['ip_address'].'",
                        "firstname": "'.trim($data['client_details']['first_name']).'",
                        "lastname": "",
                        "phone": "'.$phone_number.'",
                        "email": "",
                        "metadata":{"product": "'.$product_type.'"}
                    }';
                
                    $wiserLeads = new WiserLeadsHelper();
                    $results = $wiserLeads->postLead($data_aux);
                    $arr_wl_ids_aux = array();
                    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 = $lead['crm_accounts_id'];
                        $lesdConParams->hs_deal_id = $hs_deal_id;
                        $lesdConParams->save();
                        echo "ENVIO REALIZADO COM SUCESSO | ".$product_type. " | ".$lead['crm_accounts_id']. " | ".trim($data['client_details']['first_name'])." \n";

                        $arr_wl_ids_aux[] = $results->lead_id;
                        $phone = $country_code . $phone_number;
                        $account = ORM::for_table('crm_accounts')->find_one($lead['crm_accounts_id']);
                        if (!isset($account->id)) {
                            echo "LEAD NÃO CADASTRADO \n";
                            continue;
                        } else {
                            $crmA = $account;
                            $wiserLeadsAux = ORM::for_table('module_imobles_leads_wiserleads_contacts')
                                            ->where('crm_account_id', $crmA->id)->find_many();
                            if(count($wiserLeadsAux) > 0){
                                foreach($wiserLeadsAux as $wl){
                                    $arr_wl_ids_aux[] = $wl->wiserlead_id;
                                }
                            }
                            $arr_wl_ids[] = array("name" => $crmA->account,
                                                    "phone" => $crmA->phone,
                                                    "wiserlead_ids" => $arr_wl_ids_aux,
                                                    "created_at" => $lead['created_at']);
                            
                        }
                    } else {
                        echo "ERRO AO ENVIAR PARA WISERLEADS | ".$product_type. " | ".$lead['crm_accounts_id']." | ".trim($data['client_details']['first_name'])." \n";
                        // $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();
                    }
                }
            } 
        }
        var_dump(json_encode($arr_wl_ids));
    }

    public function reziseImageFilesByTag(){

        // $tags50kb = array (2, 7,  8, 10, 16, 23, 25, 28, 31);
        // $tags100kb = array (4, 15, 24, 27);

        $tags = array (2, 4, 7, 8, 10, 15, 16, 23, 24, 25, 27, 28, 31);
        $crawlerHelper = new CrawlerHelper();

        $like = "";
        foreach($tags as $t){
            if ($like != ''){
                $like .= "OR ";
            }
            $like .= "tags like '%\"" . $t . "\"%'";
        }

        $images = ORM::for_table('module_imobles_enterprise_imgs')
            ->where_null('delete_at')
            ->where_raw($like)
            ->find_many();

        echo "\n\nREDIMENSIONAMENTO DE IMAGENS POR TAG";
        echo "\nTotal de imagens cadastradas: " . count($images);

        foreach ($images as $img){
            echo "\n======================================================";
            echo "\nID: $img->id";
            if(!empty($img->module_imobles_enterprise_id)){
                $dir = "application/plugins/module_imobles/uploads/enterprise/$img->module_imobles_enterprise_id/images/";
            } else if(!empty($img->construction_company_id)){
                $dir = "application/plugins/module_imobles/uploads/companyconstruction/$img->construction_company_id/images/";
            } else if(!empty($img->unit_type_id)){
                $dir = "application/plugins/module_imobles/uploads/enterprise/$img->module_imobles_enterprise_id/images/";
            } else {
                echo "Tipo de imagem não identificado";
                continue;
            }
            $file = $dir . $img->src;
            
            echo "\nArquivo: $file";

            if(file_exists($file)){

                $inicialFileSize = filesize($file);

                $tags = json_decode($img->tags);
                $crawlerHelper->resizeImgFileSizeByTag($file, $tags);

                $finalFileSize = filesize($file);
                
                echo "\nTags: " . $img->tags;
                echo "\nTamanho Inicial: " . $inicialFileSize / 1000 . " kB";
                echo "\nTamanho Inicial: " . $finalFileSize / 1000 . " kB";
            } else {
                echo "\nNÃO LOCALIZADO";
            }
        }

        echo "\n\n FIM DO REDIMENSIONAMENTO\n\n";
    }

    public function setDealIdWhereNull(){
        $deals_client = array();

        $data = ORM::for_table('sys_activity')
            ->find_many();

        foreach($data as $d){
            $n = ORM::for_table('module_imobles_deals_notes')->where('sys_activity_id', $d->id)->find_one();
            if(isset($n->id)){
                continue;
            }

            if(preg_match('(Proposta gerada para apresentação)',$d->msg)){
                // echo "\nNOTES | PROPOSTA | ".$d->crm_accounts_id;
                continue;
            }

                $show_error = false;
                if(!in_array($d->cid, $deals_client)){
                    $deals_client[] = $d->cid;
                    $show_error = true;
                }

            $hs_note_id = null;
            if(intval($d->icon) > 0){
                $hs_note_id = $d->icon;
            }

            $deals = ORM::for_table('module_imobles_deals')
                ->where('crm_account_id', $d->cid)
                ->where_null('deleted_at')
                ->order_by_desc('id')
                ->find_many();
            if(count($deals) > 0){
                if(count($deals) == 1){
                    $n = ORM::for_table('module_imobles_deals_notes')->create();
                    $n->crm_account_id = $d->cid;
                    $n->msg = $d->msg;
                    $n->deal_id = $deals[0]->id;
                    $date_aux = date('Y-m-d H:i:s',$d->stime);
                    $n->created_at = $date_aux;
                    $n->created_by = $d->o;
                    $n->hs_note_id = $hs_note_id;
                    $n->sys_activity_id = $d->id;
                    $n->save();
                } else {
                    $open_deals = array();
                    foreach($deals as $ds){ 
                        if($ds->status_id == 1){
                            $open_deals[] = $ds;
                        } 
                    }

                    if(count($open_deals) == 0){
                        if($show_error === true){
                            $n = ORM::for_table('module_imobles_deals_notes')->create();
                            $n->crm_account_id = $d->cid;
                            $n->msg = $d->msg;
                            $n->deal_id = $deals[0]->id;
                            $date_aux = date('Y-m-d H:i:s',$d->stime);
                            $n->created_at = $date_aux;
                            $n->created_by = $d->o;
                            $n->hs_note_id = $hs_note_id;
                            $n->sys_activity_id = $d->id;
                            $n->save();
                            // echo "\nDEAL | ERROR | NENHUM DEAL EM ABERTO | ".$d->cid;
                        }
                    } else if(count($open_deals) == 1){
                        $n = ORM::for_table('module_imobles_deals_notes')->create();
                        $n->crm_account_id = $d->cid;
                        $n->msg = $d->msg;
                        $n->deal_id = $open_deals[0]->id;

                        $date_aux = date('Y-m-d H:i:s',$d->stime);
                        $n->created_at = $date_aux;

                        $n->created_by = $d->o;
                        $n->hs_note_id = $hs_note_id;
                        $n->sys_activity_id = $d->id;
                        $n->save();
                    } else {
                        if($show_error === true){
                            echo "\nDEAL | ERROR | MULTIPLOS DEALS EM ABERTOS | ".$d->cid;
                        }
                    }
                }
            } else {
                if($show_error === true){
                    // echo "\nGOLS | ERROR | NO DEAL SET | ".$d->cid;
                }
            }
        }
        exit;


        $data = ORM::for_table('module_imobles_crm_goals')
            ->where_null('deleted_at')
            ->where_null('deal_id')
            ->find_many();

        foreach($data as $d){
            $show_error = false;
            if(!in_array($d->crm_accounts_id, $deals_client)){
                $deals_client[] = $d->crm_accounts_id;
                $show_error = true;
            }
            $deals = ORM::for_table('module_imobles_deals')
                ->where('crm_account_id', $d->crm_accounts_id)
                ->where_null('deleted_at')
                ->order_by_desc('id')
                ->find_many();
            if(count($deals) > 0){
                if(count($deals) == 1){
                    $d->deal_id = $deals[0]->id;
                    $d->save();
                } else {
                    if($show_error === true){
                        echo "\nGOLS | ERROR | MULTIPLOS DEALS | ".$d->crm_accounts_id;
                    }
                }
            } else {
                if($show_error === true){
                    echo "\nGOLS | ERROR | NO DEAL SET | ".$d->crm_accounts_id;
                }
            }
        }

        $data = ORM::for_table('module_imobles_proposal')
            ->where_null('deleted_at')
            ->where_null('deal_id')
            ->where_not_null('scenario_title')
            ->find_many();

        foreach($data as $d){
            if(empty($d->scenario_title)){
                // var_dump($d);exit;
                if(!empty($d->deal_id)){
                    $d->deal_id = null;
                    $d->save();
                    echo "\nSCENARIOS | ERROR | NO TITLE | ".$d->client_id;
                }
                continue;
            }
            $show_error = false;
            if(!in_array($d->client_id, $deals_client)){
                $deals_client[] = $d->client_id;
                $show_error = true;
            }
            $deals = ORM::for_table('module_imobles_deals')
                ->where('crm_account_id', $d->client_id)
                ->where_null('deleted_at')
                ->order_by_desc('id')
                ->find_many();
            if(count($deals) > 0){
                if(count($deals) == 1){
                    $d->deal_id = $deals[0]->id;
                    $d->save();
                } else {
                    if($show_error === true){
                        echo "\nSCENARIOS | ERROR | MULTIPLOS DEALS | ".$d->client_id;
                    }
                }
            } else {
                if($show_error === true){
                    echo "\nSCENARIOS | ERROR | NO DEAL SET | ".$d->client_id;
                }
            }
        }

        $data = ORM::for_table('module_imobles_crm_journey_tasks')
                ->where_null('deleted_at')
                ->where_null('deal_id')
                ->find_many();

        foreach($data as $d){
            $show_error = false;
            if(!in_array($d->crm_accounts_id, $deals_client)){
                $deals_client[] = $d->crm_accounts_id;
                $show_error = true;
            }
            $deals = ORM::for_table('module_imobles_deals')
                ->where('crm_account_id', $d->crm_accounts_id)
                ->where_null('deleted_at')
                ->order_by_desc('id')
                ->find_many();
            if(count($deals) > 0){
                if(count($deals) == 1){
                    $d->deal_id = $deals[0]->id;
                    $d->save();
                } else {
                    if($show_error === true){
                        echo "\nSCENARIOS | ERROR | MULTIPLOS DEALS | ".$d->crm_accounts_id;
                    }
                }
            } else {
                if($show_error === true){
                    echo "\nSCENARIOS | ERROR | NO DEAL SET | ".$d->crm_accounts_id;
                }
            }
        }
        echo "\n\n FIM DO AJUSTE DE DEALS\n\n";
    }
}

Anon7 - 2022
AnonSec Team