AnonSec Shell
Server IP : 162.214.74.102  /  Your IP : 216.73.217.103
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/hexagon/application/plugins/module_imobles/controllers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/lrsys/www/lrsys_apps/hexagon/application/plugins/module_imobles/controllers/ApiController.php
<?php

include_once "Controller.php";
include_once "CrawlerController.php";

class ApiController extends Controller {

    protected $id;
    protected $model;
    protected $crawlerController;

    public function __construct($ui, $_L, $config, $_pd) {
        @ini_set('memory_limit', '4095M');
        @ini_set('max_execution_time', 0);
        @set_time_limit(0);

        parent::__construct($ui, $_L, $config, $_pd);

        $this->crawlerController = new CrawlerController($ui, $_L, $config, $_pd = null);
        if (!isset($_SESSION['uid'])) {
            $_SESSION['uid'] = 1;
        }
    }

    public function searchDevelopments() {
        ORM::configure('caching', true); // nao vi diferença
        try {
            $jsonStr = file_get_contents("php://input");
//            $jsonStr = '{
//    "locations":[
//        {
//            "address_neighborhood": "Cacupé",
//            "address_log": "Rua Bico de Lacre",
//            "address_number": 202,
//            "address_zip": "88050-150",
//            "address_state": "SC",
//            "address_city": "Florianópolis" 
//        },
//        {
//            "address_neighborhood": "Cacupé",
//            "address_log": "Rua Bico de Lacre",
//            "address_number": 202,
//            "address_zip": "88050-150",
//            "address_state": "SC",
//            "address_city": "Florianópolis" 
//        }
//    ],
//    "price_max": 500000,
//    "price_min": 700000,
//    "area_max": 700000,
//    "area_min": 700000,
//    "bathrooms": [2,4],
//    "suites": [1,3,5],
//    "bedrooms": [2],
//    "parking_spaces": [2,4],
//    "construction_status":["Ready to move in","In Works"],
//    "amenities": [1, 2, 3],
//    "resale":true,
//    "size":10,
//    "page_token":1,
//    "count_only":false
//}';

            $filter = json_decode($jsonStr, true);

            $jsonStr = ""; //LIMPA
        } catch (Exception $e) {
            $filter = array();
        }


        extract($this->searchWhereJoinDevelopments($filter));

        $join .= ' LEFT JOIN state st ON(st.id=ent.address_state_id)';
        $join .= ' LEFT JOIN city c ON(c.id=ent.address_city_id)';
        $join .= ' LEFT JOIN module_imobles_company_construction cp ON(cp.id=ent.module_imobles_company_construction_id)';
        $orderTypeUnit = 'u.id asc';
        $order = 'ent.id ASC';
        if (isset($filter['order_by'])) {
            $order = "";
            foreach ($filter['order_by'] as $orde) {

                foreach ($orde as $key => $val) {
                    if (strtoupper($val) == 'DESC') {
                        $val = 'DESC';
                    } else {
                        $val = 'ASC';
                    }
                    switch ($key) {
                        case 'price':
                            if (!isset($filter['resale']) || $filter['resale'] != true || $filter['resale'] != 1) {
                                $areaResalep = " AND ordp.crawler_type_id = 4 ";
                            } else {
                                $areaResalep = " AND (ordp.crawler_type_id <> 4 OR  ordp.crawler_type_id is null)";
                            }

                            $join .= " JOIN (select ordp.entreprise_id, min(ordp.crawler_price) as price from  module_imobles_listings ordp WHERE (ordp.crawler_businessType <> 'RENTAL' OR ordp.crawler_businessType IS NULL) AND (ordp.unavailable IS NULL OR ordp.unavailable =0 )  AND ordp.delete_at IS NULL AND ordp.crawler_price > 0 " . $areaResalep . " GROUP BY 1) as price_min  ON (price_min.entreprise_id=ent.id)";
                            $order .= ', price_min.price ' . $val;
                            $orderTypeUnit = " min(l.crawler_price) " . $val;

                            break;
                        case 'area':
                            if (!isset($filter['resale']) || $filter['resale'] != true || $filter['resale'] != 1) {
                                $areaResale = " AND ord.crawler_type_id = 4 ";
                            } else {
                                $areaResale = " AND (ord.crawler_type_id <> 4 OR  ord.crawler_type_id is null)";
                            }
                            $join .= ' JOIN (select min(ord.area) as min_area, ord.module_imobles_enterprise_id from module_imobles_enterprise_units_type ord where  ord.delete_at is null ' . $areaResale . ' GROUP BY (ord.module_imobles_enterprise_id))as area ON (area.module_imobles_enterprise_id=ent.id)';
                            $order .= ', area.min_area ' . $val;
                            $orderTypeUnit = " u.area " . $val;
                            break;
                        case 'release_date':
                            $order .= ', tower.date_delivery ' . $val;
                            break;
                    }
                }
            }
            if (!empty($order)) {
                $order = substr($order, 1);
            } else {
                $order = 'ent.id ASC';
            }
        } else {
            $order = 'ent.id ASC';
        }
        if (!isset($filter['size']) || $filter['size'] < 0) {
            $filter['size'] = 10;
        } else {
            if ($filter['size'] > 1000) {
                $filter['size'] = 1000;
            }
        }
        if (!isset($filter['page_token']) || $filter['page_token'] < 1) {
            $filter['page_token'] = 1;
        }

        $limitMaxRegister = $filter['size'] * $filter['page_token'];
        $limit = " LIMIT " . $filter['size'] . " offset " . ( $limitMaxRegister - $filter['size']);


        $sql = ' FROM module_imobles_enterprise ent '
                . " LEFT JOIN (select sub_tow.module_imobles_enterprise_id,sub_tow.stage as stage,min(sub_tow.date_delivery) as date_delivery  from  module_imobles_enterprise_towers sub_tow GROUP BY 1) as tower"
                . " ON (tower.module_imobles_enterprise_id=ent.id )"
                . $join . '  WHERE ent.delete_at IS NULL  '
                . $where;


        if (!isset($filter['resale']) || $filter['resale'] != true || $filter['resale'] != 1) {

            if (empty(@$filter['show_not_available']) || @$filter['show_not_available'] != true || @$filter['show_not_available'] != 1) {

                $list = "";
                if (!empty(@$filterListData['unit_type_id'])) {
                    $list = " AND sub.module_imobles_enterprise_units_type_id IN (" . @$filterListData['unit_type_id'] . ")";
                }

                $sql .= " AND EXISTS (select sub.id from module_imobles_enterprise_units sub "
                        . " JOIN module_imobles_enterprise_units_type sut ON (sut.id=sub.module_imobles_enterprise_units_type_id)"
                        . "     where sut.module_imobles_enterprise_id=ent.id AND (sub.unavailable IS NULL OR sub.unavailable=0) AND sub.crawler_type_id=4 AND sub.delete_at IS NULL " . $list . ")";
            }
        }

        $dataResults = array();
        //TRATAMENTo se somenne total, não busca dados
        if (empty(@$filter['count_only']) || @$filter['count_only'] != true || @$filter['count_only'] != 1) {

            $query = "SELECT "
                    . "c.city_name, c.city_ibge,st.uf_state, st.state_name, st.code_state, "
                    . " tower.stage, DATE(tower.date_delivery) as date_delivery,"
                    . "ent.id,ent.init_sales,ent.hubspot, ent.name as development, DATE(ent.release_date) as release_date, ent.address_log, ent.address_number, ent.address_neightborhood, ent.address_zip"
                    . ", ent.google_geometry, ent.latitude, ent.longitude, cp.name as construction_company"
                    . $sql . " ORDER BY " . $order . " " . $limit;

            $dat = ORM::for_table('module_imobles_enterprise_towers')
                            ->raw_query($query)->find_array();

            if (!isset($filter['resale']) || $filter['resale'] != true || $filter['resale'] != 1) {
                $query_price = " AND l.crawler_type_id = 4 AND l.advertiser_id IS NULL AND l.crawler_price > 0 ";
                $list = "";
                if (!empty(@$filterListData['unit_type_id'])) {
                    $list = " AND sub.module_imobles_enterprise_units_type_id IN (" . @$filterListData['unit_type_id'] . ")";
                }
                $selectTotal = "NULL as total_listing, "
                        . " (select count(sub.id) from module_imobles_enterprise_units sub "
                        . "     where sub.module_imobles_enterprise_units_type_id=u.id AND (sub.unavailable IS NULL OR sub.unavailable=0) AND sub.crawler_type_id=4 AND sub.delete_at IS NULL " . $list . ") as disponible_unit";
            } else {
                $list = "";
                if (!empty(@$filterListData['listing_id'])) {
                    $list = " AND sub_l.id IN (" . @$filterListData['listing_id'] . ")";
                }


                $selectTotal = " (select count(sub_l.id) from module_imobles_listings sub_l "
                        . "     where sub_l.unit_type_id=u.id AND (sub_l.unavailable IS NULL OR sub_l.unavailable =0 )  AND sub_l.delete_at IS NULL  AND (sub_l.crawler_type_id  IS NULL OR sub_l.crawler_type_id <> 4)  AND sub_l.advertiser_id IS NOT NULL AND (sub_l.crawler_businessType <> 'RENTAL' OR sub_l.crawler_businessType IS NULL)  " . $list . " ) as total_listing, "
                        . "  NULL as disponible_unit";

                $query_price = " AND l.crawler_price > 0 AND (l.crawler_type_id  IS NULL OR l.crawler_type_id <> 4)  AND l.advertiser_id IS NOT NULL AND (l.crawler_businessType <> 'RENTAL' OR l.crawler_businessType IS NULL)  ";
            }

            if (count($dat) > 0) {
                $ent = "";
                $queryDispobibleUnit = "";

                foreach ($dat as $d) {
                    $dataResults[$d['id']]['id'] = $d['id'];
                    $dataResults[$d['id']]['name'] = $d['development'];
                    $dataResults[$d['id']]['hubspot_alias'] = $d['hubspot'];
                    $dataResults[$d['id']]['init_sales'] = $d['init_sales'];
                    $dataResults[$d['id']]['development_id'] = $d['id'];


                    //tratamento do stagio conforme regra IMB-18
                    if (empty($d['stage'])) {
                        if (strtotime(date("Y-m-d")) >= strtotime($d['release_date'])) {
                            $dataResults[$d['id']]['construction_status'] = 'Ready to move in';
                        } else {
                            $dataResults[$d['id']]['construction_status'] = 'In Works';
                        }
                        $dataResults[$d['id']]['release_date'] = $d['release_date'];
                    } else {
                        $dataResults[$d['id']]['construction_status'] = $d['stage'];
                        $dataResults[$d['id']]['release_date'] = $d['date_delivery'];
                    }

                    //IMB-19
                    if (!empty($d['google_geometry'])) {
                        $dataResults[$d['id']]['geometry'] = json_decode($d['google_geometry']);
                    } else {
                        $dataResults[$d['id']]['geometry'] = array("location" => array("lat" => $d['latitude'], "lng" => $d['longitude']));
                    }

                    $dataResults[$d['id']]['address'] = array(
                        'country' => 'BR',
                        'zip_code' => $d['address_zip'],
                        'city' => $d['city_name'],
                        'ibge_city_id' => $d['city_ibge'],
                        'state_acronym' => $d['uf_state'],
                        'state' => $d['state_name'],
                        'ibge_state_id' => $d['code_state'],
                        'street' => $d['address_log'],
                        'number' => $d['address_number'],
                        'neighborhood' => $d['address_neightborhood'],
                    );
                    $dataResults[$d['id']]['construction_company'] = $d['construction_company'];

                    $ent .= "," . $d['id'];
                }

                // Pego as imagens de backend
                $c = ORM::for_table('module_imobles_enterprise_imgs')
                                ->raw_query("SELECT s.module_imobles_enterprise_id, s.src, s.tags, s.unit_type_id, s.description FROM"
                                        . " module_imobles_enterprise_imgs as s"
                                        . " WHERE (s.duplicated IS NULL OR s.duplicated=0) AND type = 'backend' "
                                        . " AND s.module_imobles_enterprise_id IN(" . substr($ent, 1) . ") "
                                        . " AND s.delete_at IS NULL "
                                        //  . " HAVING count(module_imobles_enterprise_id)<=5"
                                )->find_array();
//                    var_dump($c);exit;
                //BUSCA UNIT_TYPE
                $types = ORM::for_table('module_imobles_enterprise_units_type')
                        ->raw_query(" SELECT "
//                                . "min(l.crawler_price) as minValue,"
                                . " max(l.crawler_price) as 'maxValue',"
                                . " avg(l.crawler_price) as averageValue ,"
                                . " u.number_rooms as bedrooms,"
                                . " u.number_bathroom as bathrooms,"
                                . " u.area as area,"
                                . " u.number_suite as suites,"
                                . " u.number_garage as parking_spaces,"
                                . " u.id,"
                                . " u.module_imobles_enterprise_id,"
                                . " group_concat(l.id) as list_listings,"
                                . $selectTotal
                                . " FROM module_imobles_enterprise_units_type u"
                                . " JOIN module_imobles_listings  l ON (u.id=l.unit_type_id)"
//                                . " LEFT JOIN (select sub_price2.unit_type_id,sub_price2.condo_fee as condo_fee from  module_imobles_listings_prices sub_price2 "
//                                . " WHERE  sub_price2.id=(select max(sub_3.id) from module_imobles_listings_prices sub_3 WHERE sub_3.unit_type_id=sub_price2.unit_type_id)) as price_condo"
//                                . " ON (price_condo.unit_type_id=u.id   )"
                                . " WHERE"
                                . " (l.unavailable IS NULL OR l.unavailable =0 )  AND l.delete_at IS NULL "
                                . " AND u.module_imobles_enterprise_id IN (" . substr($ent, 1) . ") " . $query_price . $whereunit
                                . " GROUP BY u.module_imobles_enterprise_id,u.id, u.number_rooms, u.number_suite, u.area, u.number_garage, u.number_bathroom ORDER BY " . @$orderTypeUnit)
                        ->find_array();

                // Faço a contagem das unidades disponíveis para o empreendimento
                $arr_count_available = array();
                foreach ($types as $u) {

                    if (substr($u['list_listings'], -1) == ",") {
                        $u['list_listings'] = substr($u['list_listings'], 0, strlen($u['list_listings']) - 1);
                    }
                    $min = ORM::for_table('module_imobles_enterprise_units_type')
                            ->raw_query(" SELECT "
                                    . " min(l.crawler_price) as minValue"
                                    . " FROM module_imobles_listings  l "
                                    . " WHERE "
                                    . " l.id in (" . $u['list_listings'] . ") and l.crawler_price>=" . ($u['averageValue'] * 0.6))
                            ->find_array();

                    // Pego as imagens da Tipo de Unidade
                    $arr_unit_type_imgs = array();



                    if (count($c) > 0) {
                        foreach ($c as $im) {
                            $arr_tags = array();
                            if ($im['unit_type_id'] != $u['id']) {
                                continue;
                            }
                            if (empty($arr_unit_type_imgs) || count($arr_unit_type_imgs) < 10) {
                                $arr_tags_id = json_decode($im['tags']);
                                $arr_tags_aux = ORM::for_table('module_imobles_enterprise_img_backend_tags')->select('name')->where_in('id', $arr_tags_id)->find_array();

                                foreach ($arr_tags_aux as $tags) {
                                    $arr_tags[] = $tags['name'];
                                }
                                $arr_unit_type_imgs[] = array(
                                    "type" => 'IMAGE',
                                    "url" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/" . $im['src'],
                                    "description" => $im['description'],
                                    "tags" => $arr_tags);
                            } else {
                                break;
                            }
                        }
                    }

                    if ($u['averageValue'] < $min[0]['minValue']) {
                        $u['averageValue'] = $min[0]['minValue'];
                    }

                    $dataArray = array(
                        "id" => $u['id'],
                        "total_listing" => $u['total_listing'],
                        "unit_available" => $u['disponible_unit'],
                        "min_value" => number_format($min[0]['minValue'], 2, ".", ""),
                        "average_value" => number_format($u['averageValue'], 2, ".", ""),
                        "max_value" => number_format($u['maxValue'], 2, ".", ""),
                        "bedrooms" => $u['bedrooms'],
                        "bathrooms" => $u['bathrooms'],
                        "area" => $u['area'],
                        "suites" => $u['suites'],
                        "parking_spaces" => $u['parking_spaces'],
                        "medias" => $arr_unit_type_imgs
                    );

                    if (!isset($filter['resale']) || $filter['resale'] != true || $filter['resale'] != 1) {
                        $dataArray["unit_available"] = number_format($u['disponible_unit'], 0, "", "");
                    } else {
                        $dataArray["total_listing"] = number_format($u['total_listing'], 0, "", "");
                    }
                    $dataResults[$u['module_imobles_enterprise_id']]['unit_type'] [] = $dataArray;

                    if (!isset($dataResults[$u['module_imobles_enterprise_id']]['total_units_available'])) {
                        $dataResults[$u['module_imobles_enterprise_id']]['total_units_available'] = 0;
                    }
                    $dataResults[$u['module_imobles_enterprise_id']]['total_units_available'] += $u['disponible_unit'];
                }

//                $c = ORM::for_table('module_imobles_enterprise_imgs')
//                                ->raw_query("SELECT s.module_imobles_enterprise_id,s.src, s.tags FROM"
//                                        . " module_imobles_enterprise_imgs s"
//                                        . " WHERE (s.duplicated IS NULL OR s.duplicated=0) "
//                                        . " AND s.module_imobles_enterprise_id IN(" . substr($ent, 1) . ") "
//                                        . " AND s.type = 'backend' AND s.delete_at IS NULL "
//                                        . " LIMIT 5"
//                                        //  . " HAVING count(module_imobles_enterprise_id)<=5"
//                                )->find_array();


                if (count($c) > 0) {
                    $arr_enterprise_imgs = array();
                    foreach ($c as $im) {
                        if (!empty($im['unit_type_id']) || empty($im['tags'])) {
                            continue;
                        }
                        $arr_tags = array();
                        if (!isset($dataResults[$im['module_imobles_enterprise_id']]['medias']) || count(@$dataResults[$im['module_imobles_enterprise_id']]['medias']) < 5) {
                            $arr_tags_id = json_decode($im['tags']);
                            if (!empty($arr_tags_id)) {
                                $arr_tags_aux = ORM::for_table('module_imobles_enterprise_img_backend_tags')->select('name')->where_in('id', $arr_tags_id)->find_array();

                                foreach ($arr_tags_aux as $tags) {
                                    $arr_tags[] = $tags['name'];
                                }
                            } else {
                                $arr_tags = array();
                            }
                            $arr_enterprise_imgs[$im['module_imobles_enterprise_id']][] = array(
                                "type" => 'IMAGE',
                                "url" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/" . $im['src'],
                                "description" => $im['description'],
                                "tags" => $arr_tags);
                        }
                    }

                    foreach ($arr_enterprise_imgs as $k => $v) {
                        $dataResults[$k]['medias'] = $v;
                    }
                }
            }
        }

        $tot = ORM::for_table('module_imobles_enterprise_towers')
                        ->raw_query("select count(ent.id) as total " . $sql)->find_many();

        $totalresults = count($dataResults);
        $output = array(
            "time" => (microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']),
            "total_count" => $tot[0]->total, 
            "page_token" => $totalresults == 0 ? 0 : ( ($tot[0]->total >= $limitMaxRegister ? $filter['page_token'] + 1 : "")),
            "size" => $filter['size'],
            "list_size" => $totalresults,
            "results" => array_values($dataResults),
        );
        header('Content-Type: application/json');
        echo json_encode($output);
        exit();
    }

    private function searchWhereJoinDevelopments($filter) {
        $where = '';
        $join = '';
        $whereunit = "";

        if (empty(@$filter['unit_type_ids'])) {

            $filterListData = array();
            if (isset($filter['amenities']) && $filter['amenities'] != '') {
                $a = implode("','", $filter['amenities']);
                if (!empty($a)) {
                    $where .= " AND EXISTS (select sub.module_imobles_enterprise_id from module_imobles_enterprise_entreprise_amenities sub where sub.module_imobles_enterprise_id=ent.id AND sub.module_imobles_enterprise_amenities_id IN ('" . $a . "'))";
                }
            }

            if (!empty($filter['construction_status'])) {

                $subWhere = "";
                $stages = "";
                foreach ($filter['construction_status'] as $s) {
                    if ($s == 'Ready to move in') {
                        $subWhere .= "OR ( tower.stage IS NULL AND  (tower.date_delivery<='" . date('Y-m-d') . "')) "
                                . " OR (tower.stage IS NULL AND tower.date_delivery IS NULL AND ent.release_date<='" . date('Y-m-d') . "') ";
                    }
                    if ($s == 'In Works') {
                        $subWhere .= "OR ( tower.stage IS NULL AND  (tower.date_delivery>'" . date('Y-m-d') . "')) "
                                . " OR (tower.stage IS NULL AND tower.date_delivery IS NULL AND ent.release_date>'" . date('Y-m-d') . "') ";
                    }
                    if ($s != "") {
                        $stages .= ",'" . htmlentities($s) . "'";
                    }
                }

                $where .= " AND( tower.stage IN (" . substr($stages, 1) . ") ";
                if (!empty($filter['construction_status'])) {
                    $where .= " OR (" . substr($subWhere, 2) . ")";
                }
                $where .= ")";
            }


            if (!empty($filter['release_date_start'])) {
                $where .= "AND ( (tower.date_delivery>='" . $filter['release_date_start'] . "')"
                        . " OR (tower.stage IS NULL AND tower.date_delivery IS NULL AND ent.release_date>='" . $filter['release_date_start'] . "')) ";
            }
            if (!empty($filter['release_date_end'])) {
                $where .= "AND ( (tower.date_delivery<='" . $filter['release_date_end'] . "') "
                        . " OR (tower.stage IS NULL AND tower.date_delivery IS NULL AND ent.release_date<='" . $filter['release_date_end'] . "')) ";
            }


            if (@$filter['locations']) {

                $address_neightborhood = "";
                $address_number = "";
                $state = '';
                $city = '';
                $log = '';
                $zip = '';

                foreach ($filter['locations'] as $d) {

                    if (!empty($d['address_neighborhood'])) {
                        $address_neightborhood .= "OR ent.address_neighborhood_sanitized  LIKE '%" . htmlentities(sanitizaText($d['address_neighborhood'])) . "%' ";
                    }

                    if (!empty($d['address_number'])) {
                        $address_number .= "OR ent.address_number  = '" . ($d['address_number']) . "' "
                                . "";
                    }

                    if (!empty($d['address_state'])) {
                        $state .= "OR st.uf_state  LIKE '%" . ($d['address_state']) . "%' "
                                . "";
                    }

                    if (!empty($d['address_city'])) {
                        $city .= "OR c.city_name  LIKE '%" . ($d['address_city']) . "%' ";
                    }
                    if (!empty($d['address_log'])) {

                        $log .= "OR  (ent.address_log  LIKE '%" . htmlentities($d['address_log']) . "%' "
                                . "OR ent.address_log_sanitized LIKE '%" . htmlentities(sanitizaText($d['address_log'])) . "%'  "
                                . ")";
                    }

                    if (!empty($filter['address_zip'])) {
                        $zip .= "OR ent.address_zip  LIKE '%" . $filter['address_zip'] . "%' "
                                . "";
                    }
                }

                if (!empty($address_neightborhood)) {
                    $where .= " AND (" . substr($address_neightborhood, 2) . ")";
                }
                if (!empty($address_number)) {
                    $where .= " AND (" . substr($address_number, 2) . ")";
                }

                if (!empty($state)) {
                    $where .= " AND (" . substr($state, 2) . ")";
                }



                if (!empty($city)) {
                    $where .= " AND (" . substr($city, 2) . ")";
                }
                if (!empty($log)) {
                    $where .= " AND (" . substr($log, 2) . ")";
                }
                if (!empty($zip)) {
                    $where .= " AND (" . substr($zip, 2) . ")";
                }
            }
            $subunit = '';
            $subunit2 = "";



            $filterListMediaPriceLIsting = " AND (sub_price2.delete_at IS NULL AND "
                    . "(sub_price2.crawler_status IS NULL OR sub_price2.crawler_status='ACTIVE')"
                    . " AND (sub_price2.unavailable IS NULL OR sub_price2.unavailable=0)"
                    . ")";
            $filterListMediaPriceLIsting .= " AND  (sub_price2.crawler_businessType <> 'RENTAL' OR sub_price2.crawler_businessType IS NULL)";

            if (!isset($filter['resale']) || ($filter['resale'] != 1 && $filter['resale'] != true)) {
                $filterListMediaPriceLIsting .= " AND sub_price2.crawler_type_id = 4 AND sub_price2.advertiser_id IS NULL ";

                $subunit2 .= " AND (sub_l.crawler_type_id = 4) ";
                $where .= " AND (EXISTS (select sub_w.id from module_imobles_listings  sub_w where  sub_w.entreprise_id=ent.id  AND sub_w.advertiser_id IS NULL "
                        . " AND sub_w.crawler_type_id=4 AND sub_w.crawler_price>0 AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL)))";

                $whereunit .= " AND (EXISTS (select sub_w.id from module_imobles_listings  sub_w where  sub_w.unit_type_id=u.id  AND sub_w.advertiser_id IS NULL "
                        . " AND sub_w.crawler_type_id=4 AND sub_w.crawler_price>0 AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL)))";
            } else {
                $filterListMediaPriceLIsting = "AND (sub_price2.crawler_type_id  IS NULL OR sub_price2.crawler_type_id <> 4)  AND sub_price2.advertiser_id IS NOT NULL ";

                $subunit2 = " AND (sub_l.crawler_type_id<>4 OR sub_l.crawler_type_id IS NULL ) AND  (sub_l.crawler_businessType <> 'RENTAL' OR sub_l.crawler_businessType IS NULL)";
                $where .= ' AND (ent.verified = 1 '
                        . 'OR ent.crawler_enterprise_id IS NOT NULL OR ent.google_place_id IS NOT NULL) ';

                $where .= " AND (EXISTS (select sub_w.id from module_imobles_listings  sub_w where  sub_w.entreprise_id=ent.id  AND sub_w.advertiser_id IS NOT NULL "
                        . " AND (sub_w.crawler_type_id<>4 OR sub_w.crawler_type_id IS NULL ) AND   (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL) AND sub_w.crawler_price>0))";

                $whereunit .= " AND (EXISTS (select sub_w.id from module_imobles_listings  sub_w where  sub_w.unit_type_id=u.id  AND sub_w.advertiser_id IS NOT NULL "
                        . " AND (sub_w.crawler_type_id<>4 OR sub_w.crawler_type_id IS NULL ) AND   (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL) AND sub_w.crawler_price>0))";
            }


            if (!empty($filter['area_min'])) {
                $subunit .= "AND sub_u.area>=" . htmlentities($filter['area_min']) . " ";
                $whereunit .= " AND u.area>=" . htmlentities($filter['area_min']) . " ";
            }
            if (!empty($filter['area_max'])) {
                $subunit .= "AND sub_u.area<=" . htmlentities($filter['area_max']) . " ";
                $whereunit .= " AND u.area<=" . htmlentities($filter['area_max']) . " ";
            }

            if (!empty($filter['bedrooms'])) {

                $bed = implode("','", $filter['bedrooms']);
                if (!empty($bed)) {
                    $subunit .= "AND sub_u.number_rooms IN ('" . $bed . "') ";

                    $whereunit .= " AND u.number_rooms IN ('" . $bed . "') ";
                }
            }
            if (!empty($filter['suites'])) {
                $s = implode("','", $filter['suites']);
                if (!empty($s)) {
                    $subunit .= "AND sub_u.number_suite IN ('" . $s . "') ";
                    $whereunit .= " AND u.number_suite IN ('" . $s . "') ";
                }
            }

            if (!empty($filter['bathrooms'])) {
                $s = implode("','", $filter['bathrooms']);
                if (!empty($s)) {
                    $subunit .= " AND sub_u.number_bathroom IN ('" . $s . "') ";
                    $whereunit .= " AND u.number_bathroom IN ('" . $s . "') ";
                }
            }

            if (!empty($filter['parking_spaces'])) {
                $s = implode("','", $filter['parking_spaces']);
                if (!empty($s)) {
                    $subunit .= " AND sub_u.number_garage IN ('" . $s . "') ";

                    $whereunit .= " AND u.number_garage IN ('" . $s . "') ";
                }
            }

            if (!empty($filter['price_min'])) {
                $subunit .= "  AND sub_l.crawler_price>=" . htmlentities(($filter['price_min'])) . " ";

                $whereunit .= " AND l.crawler_price>0 AND l.crawler_price>=" . htmlentities(($filter['price_min'])) . " ";
            }
            if (!empty($filter['price_max'])) {
                $subunit .= "  AND sub_l.crawler_price<=" . htmlentities(($filter['price_max'])) . " ";
                $whereunit .= " AND l.crawler_price>0 AND  l.crawler_price<=" . htmlentities(($filter['price_max'])) . " ";
            }
            if (!empty($filter['price_max']) || !empty($filter['price_min'])) {
                $subunit .= " and sub_l.crawler_price>=(select avg(sub_price2.crawler_price) from module_imobles_listings sub_price2 WHERE  sub_price2.unit_type_id=sub_u.id " . $filterListMediaPriceLIsting . ")*0.6";
                $whereunit .= " and l.crawler_price>=(select avg(sub_price2.crawler_price) from module_imobles_listings sub_price2 WHERE  sub_price2.unit_type_id=u.id " . $filterListMediaPriceLIsting . ")*0.6";
            }

            $joinSubunit = "";

            if (!empty($filter['condo_fee_min']) || !empty($filter['condo_fee_max'])) {
                $subInactivePrice = " AND (l.delete_at IS NULL AND "
                        . "(l.crawler_status IS NULL OR l.crawler_status='ACTIVE')"
                        . " AND (l.unavailable IS NULL OR l.unavailable=0)"
                        . ")";


                $wherecondo = "select sub_price2.unit_type_id "
                        . "as unit_type_id, group_concat(sub_price2.listing_id) as listing_id "
                        . "from  module_imobles_listings_prices sub_price2 "
                        . " join module_imobles_listings as l ON (l.id=sub_price2.listing_id)"
                        . " WHERE  (sub_price2.rental is null or sub_price2.rental<>1)"
                        . " AND sub_price2.id=(select max(sub_3.id)"
                        . " from module_imobles_listings_prices sub_3 "
                        . "where sub_3.listing_id=sub_price2.listing_id "
                        . " and (sub_3.rental is null or sub_3.rental<>1))"
                        . " AND sub_price2.condo_fee>0 " . $subInactivePrice
                        . " GROUP BY (sub_price2.unit_type_id) "
                        . "HAVING 1=1 "
                ;

                if (!empty($filter['condo_fee_min'])) {

                    $wherecondo .= " AND AVG(sub_price2.condo_fee)>=" . htmlentities(Finance::amount_fix($filter['condo_fee_min'])) . ""
                            . "";
                }

                if (!empty($filter['condo_fee_max'])) {
                    $wherecondo .= " AND AVG(sub_price2.condo_fee)<=" . htmlentities(Finance::amount_fix($filter['condo_fee_max'])) . ""
                            . "";
                }
                //trata aquio os tipos e listings selecionados com base no valor do condominio
                $totUnit = ORM::for_table('module_imobles_enterprise_units')
                        ->raw_query($wherecondo)
                        ->find_many();
                if (count($totUnit) > 0) {
                    $unit_type_id = '';
                    $listing_id = '';
                    foreach ($totUnit as $t) {
                        $unit_type_id .= ',' . $t->unit_type_id;
                        $listing_id .= ',' . $t->listing_id;
                    }
                    if (!empty($listing_id)) {
                        $unit_type_id = substr($unit_type_id, 1);
                        $listing_id = substr($listing_id, 1);
                    }

                    $subunit .= " AND sub_u.id IN (" . $unit_type_id . ")";
                    $whereunit .= " AND u.id IN (" . $unit_type_id . ")";
                    $filterListData['listing_id'] = $listing_id;
                    $filterListData['unit_type_id'] = $unit_type_id;
                } else {
                    $subunit .= " AND '1'<>'1'";
                }
                if (count($totUnit) > 0) {
                    
                } else {
                    $subunit .= " AND '1'<>'1'";
                }
            }




            $where .= " AND EXISTS (Select sub_u.id from module_imobles_enterprise_units_type"
                    . " sub_u LEFT JOIN module_imobles_listings  "
                    . "sub_l ON (sub_u.id=sub_l.unit_type_id) " . $joinSubunit . " "
                    . "WHERE sub_l.crawler_price>0 "
                    . "AND sub_u.module_imobles_enterprise_id=ent.id "
                    . "AND sub_u.delete_at IS NULL " . @$subunit2 . " " . @$subunit . "" . " limit 1"
                    . ")";
        } else {

            if (!isset($filter['resale']) || ($filter['resale'] != 1 && $filter['resale'] != true)) {
                $where .= " AND (EXISTS (select sub_w.id from module_imobles_listings  sub_w where  sub_w.entreprise_id=ent.id  AND sub_w.advertiser_id IS NULL "
                        . " AND sub_w.crawler_type_id=4 AND sub_w.crawler_price>0 AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL)))";

                $whereunit .= " AND (EXISTS (select sub_w.id from module_imobles_listings  sub_w where  sub_w.unit_type_id=u.id  AND sub_w.advertiser_id IS NULL "
                        . " AND sub_w.crawler_type_id=4 AND sub_w.crawler_price>0 AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL)))";
            } else {
                $where .= ' AND (ent.verified = 1 '
                        . 'OR ent.crawler_enterprise_id IS NOT NULL OR ent.google_place_id IS NOT NULL) ';

                $where .= " AND (EXISTS (select sub_w.id from module_imobles_listings  sub_w where  sub_w.entreprise_id=ent.id  AND sub_w.advertiser_id IS NOT NULL "
                        . " AND (sub_w.crawler_type_id<>4 OR sub_w.crawler_type_id IS NULL ) AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL) AND crawler_price>0))";

                $whereunit .= " AND (EXISTS (select sub_w.id from module_imobles_listings  sub_w where  sub_w.unit_type_id=u.id  AND sub_w.advertiser_id IS NOT NULL "
                        . " AND (sub_w.crawler_type_id<>4 OR sub_w.crawler_type_id IS NULL ) AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL) AND crawler_price>0))";
            }
            $where .= " AND EXISTS (Select sub_u.id from module_imobles_enterprise_units_type sub_u"
                    . " WHERE sub_u.module_imobles_enterprise_id=ent.id "
                    . " AND sub_u.delete_at IS NULL  and sub_u.id IN ('" . implode("','", $filter['unit_type_ids']) . "')"
                    . ")";
            $whereunit .= " AND u.id IN ('" . implode("','", $filter['unit_type_ids']) . "')";
            $filterListData = implode(",", $filter['unit_type_ids']);
        }

        return array('whereunit' => $whereunit, 'where' => $where, 'join' => $join, 'filterListData' => $filterListData);
    }

    /////////////////////development details
    public function developmentDetails() {
        try {
            $jsonStr = file_get_contents("php://input");
            $filter = json_decode($jsonStr, true);
            $jsonStr = ""; //LIMPA
        } catch (Exception $e) {
            $filter = array();
        }
        $dataResults = array();
        $id = intval($filter['development_id']);
        $resale = intval(@$filter['resale']);

        if ($id > 0) {
            $select = "SELECT s.name as property_standard, "
                    . "c.city_name, c.city_ibge,st.uf_state, st.state_name, st.code_state, "
                    . " tower.stage, DATE(tower.date_delivery) as date_delivery,"
                    . " co.name as construction_company, ent.id, ent.name as development, ent.desc, DATE(ent.release_date) as release_date, ent.address_log, ent.address_number, ent.address_neightborhood, ent.address_zip"
                    . ", ent.google_geometry, ent.latitude, ent.longitude"
                    . ", ent.google_place_id, ent.google_rating, ent.link_google"
                    . ", ent.link_presentation, ent.value_input_porcentage as financing_input, ent.value_installment_porcentage financing_installment
                        , ent.value_founding_porcentage as financing_founding, ent.hubspot, ent.init_sales";

            $from = ' FROM module_imobles_enterprise ent '
                    . " LEFT JOIN (select sub_tow.module_imobles_enterprise_id,sub_tow.stage as stage,min(sub_tow.date_delivery) as date_delivery  from  module_imobles_enterprise_towers sub_tow GROUP BY 1) as tower"
                    . " ON (tower.module_imobles_enterprise_id=ent.id )"
                    . ' LEFT JOIN state st ON(st.id=ent.address_state_id)'
                    . ' LEFT JOIN city c ON(c.id=ent.address_city_id)'
                    . ' LEFT  JOIN module_imobles_company_construction co ON(co.id=ent.module_imobles_company_construction_id)'
                    . ' LEFT  JOIN module_imobles_enterprise_standard s ON(s.id=ent.module_imobles_enterprise_standard_id)'
            ;

            $where = '  WHERE  ent.delete_at IS NULL AND ent.id= ' . $id;



            $dat = ORM::for_table('module_imobles_enterprise')
                            ->raw_query($select . $from . $where)->find_array();


            if (count($dat) > 0) {
                $d = $dat[0];
                $dataResults['name'] = $d['development'];
                $dataResults['description'] = $d['desc'];
                $dataResults['construction_company'] = $d['construction_company'];
                $dataResults['hubspot_alias'] = $d['hubspot'];
                $dataResults['init_sales'] = $d['init_sales'];
                $dataResults['development_id'] = $d['id'];

                //tratamento do stagio conforme regra IMB-18
                if (empty($d['stage'])) {
                    if (strtotime(date("Y-m-d")) >= strtotime($d['release_date'])) {
                        $dataResults['construction_status'] = 'Ready to move in';
                    } else {
                        $dataResults['construction_status'] = 'In Works';
                    }
                    $dataResults['release_date'] = $d['release_date'];
                } else {
                    $dataResults['construction_status'] = $d['stage'];
                    $dataResults['release_date'] = $d['date_delivery'];
                }
                $dataResults['property_standard'] = $d['property_standard'];
                $dataResults['financing']['entry'] = $d['financing_input'];
                $dataResults['financing']['installment'] = $d['financing_installment'];
                $dataResults['financing']['founding'] = $d['financing_founding'];

                //IMB-19
                if (!empty($d['google_geometry'])) {
                    $dataResults['geometry'] = json_decode($d['google_geometry']);
                } else {
                    $dataResults['geometry'] = array("location" => array("lat" => $d['latitude'], "lng" => $d['longitude']));
                }
                $dataResults['google']['place_id'] = $d['google_place_id'];
                $dataResults['google']['rating'] = $d['google_rating'];
                $dataResults['google']['link'] = $d['link_google'];

                $dataResults['link_presentation'] = $d['link_presentation'];

                $dataResults['address'] = array(
                    'country' => 'BR',
                    'zip_code' => $d['address_zip'],
                    'city' => $d['city_name'],
                    'ibge_city_id' => $d['city_ibge'],
                    'state_acronym' => $d['uf_state'],
                    'state' => $d['state_name'],
                    'ibge_state_id' => $d['code_state'],
                    'street' => $d['address_log'],
                    'number' => $d['address_number'],
                    'neighborhood' => $d['address_neightborhood'],
                );


                $tags = ORM::for_table('module_imobles_enterprise_img_backend_tags')
                        ->table_alias('s');
                $tags = $tags->find_many();
                $arrayTag = array();
                foreach ($tags as $t) {
                    $arrayTag[$t->id] = $t->name;
                }

                // Pego as imagens de backend
                $imagB = ORM::for_table('module_imobles_enterprise_imgs')
                                ->raw_query("SELECT s.module_imobles_enterprise_id, s.src, s.tags, s.unit_type_id, s.description FROM"
                                        . " module_imobles_enterprise_imgs as s"
                                        . " WHERE (s.duplicated IS NULL OR s.duplicated=0) AND type = 'backend' "
                                        . " AND s.module_imobles_enterprise_id IN(" . $d['id'] . ") "
                                        . " AND s.delete_at IS NULL "
                                        //  . " HAVING count(module_imobles_enterprise_id)<=5"
                                )->find_array();

//                $imagB = ORM::for_table('module_imobles_enterprise_imgs')
//                                ->raw_query("SELECT s.module_imobles_enterprise_id,s.src, s.tags FROM"
//                                        . " module_imobles_enterprise_imgs s"
//                                        . " WHERE (s.duplicated IS NULL OR s.duplicated=0)  AND s.delete_at IS NULL AND s.type='backend' AND s.module_imobles_enterprise_id IN(" . $d['id'] . ")"
//                                        //  . " HAVING count(module_imobles_enterprise_id)<=5"
//                                )->find_array();


                if (count($imagB) > 0) {
                    foreach ($imagB as $im) {
                        if (!empty($im['unit_type_id']) || empty($im['tags'])) {
                            continue;
                        }
                        $desc_tags = array();
                        try {
                            $tagsIm = json_decode($im['tags']);
                            if ($tagsIm) {
                                foreach ($tagsIm as $t) {
                                    $desc_tags[] = $arrayTag[$t];
                                }
                            }
                        } catch (Exception $e) {
                            $desc_tags = "";
                        }

                        // Monto o array com os tamanhos alternativos das imagens
                        $alternatives_sizes = null;
                        if (in_array("DEVELOPMENT_GALLERY_IMGS", $desc_tags)) {
                            $alternatives_sizes = array("1152x768" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/xxl/" . $im['src'],
                                "840x560" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/xlg/" . $im['src'],
                                "600x400" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/lrg/" . $im['src'],
                                "450x300" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/med/" . $im['src'],
                                "300x200" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/sml/" . $im['src'],
                                "120x80" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/xsm/" . $im['src'],
                                "104x80" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/thumb/" . $im['src']);
                        }
                        $dataResults['medias'][] = array(
                            "type" => 'IMAGE',
                            "url" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/" . $im['src'],
                            "description" => $im['description'],
                            "tags" => $desc_tags,
                            "alternatives_sizes" => $alternatives_sizes);
                    }
                }


                $filterListMediaPriceLIsting = " AND (sub_price2.delete_at IS NULL AND "
                        . "(sub_price2.crawler_status IS NULL OR sub_price2.crawler_status='ACTIVE')"
                        . " AND (sub_price2.unavailable IS NULL OR sub_price2.unavailable=0)"
                        . ")";

                if (!$resale || $resale != 1 || $resale != true) {
                    $query_resale_listing = " AND sub_l.crawler_type_id = 4 AND  sub_l.advertiser_id IS NULL  ";
                    $query_resale_unit = " AND  sub.crawler_type_id = 4  ";
                    $query_resale = " AND  u.crawler_type_id = 4  ";
                    $filterListMediaPriceLIsting .= " AND sub_price2.crawler_type_id = 4 AND sub_price2.advertiser_id IS NULL ";

                    $selectCount = "NULL as total_listing, "
                            . " (select count(sub.id) from module_imobles_enterprise_units sub "
                            . "     where sub.module_imobles_enterprise_units_type_id=u.id AND (sub.unavailable IS NULL OR sub.unavailable=0) " . $query_resale_unit . " AND  sub.delete_at IS NULL) as disponible_unit";
                } else {
                    $query_resale_listing = " AND ( sub_l.crawler_type_id <> 4 OR  sub_l.crawler_type_id  IS NULL)  AND  sub_l.advertiser_id IS NOT NULL AND  (sub_l.crawler_businessType <> 'RENTAL' OR sub_l.crawler_businessType IS NULL)";
                    $query_resale_unit = " AND ( sub.crawler_type_id <> 4 OR  sub.crawler_type_id  IS NULL)";
                    $query_resale = " AND ( u.crawler_type_id <> 4 OR  u.crawler_type_id  IS NULL)";

                    $selectCount = " (select count(sub_l.id) from module_imobles_listings sub_l "
                            . "     where sub_l.unit_type_id=u.id AND (sub_l.unavailable IS NULL OR sub_l.unavailable =0 )  AND sub_l.delete_at IS NULL " . $query_resale_listing . " ) as total_listing, "
                            . "NULL as disponible_unit";
                    $filterListMediaPriceLIsting = "AND (sub_price2.crawler_type_id  IS NULL OR sub_price2.crawler_type_id <> 4)  AND sub_price2.advertiser_id IS NOT NULL AND (sub_price2.crawler_businessType <> 'RENTAL' OR sub_price2.crawler_businessType IS NULL) ";
                }
                $arr_unit_type_imgs = array();
                //BUSCA UNIT_TYPE
                $types = ORM::for_table('module_imobles_enterprise_units_type')
                        ->raw_query(" SELECT "
//                                . "min(l.crawler_price) as minValue,"
                                . " max(l.crawler_price) as 'maxValue',"
                                . " avg(l.crawler_price) as averageValue ,"
                                . " u.number_rooms as bedrooms,"
                                . " u.number_bathroom as bathrooms,"
                                . " u.area as area,"
                                . " u.number_suite as suites,"
                                . " u.number_garage as parking_spaces,"
                                . " u.id,"
                                . " u.module_imobles_enterprise_id,"
                                . " group_concat(l.id) as list_listings,"
                                . $selectCount
                                . " FROM module_imobles_enterprise_units_type u"
                                . " JOIN module_imobles_listings  l ON (u.id=l.unit_type_id)"
                                . " WHERE"
                                . " (l.unavailable IS NULL OR l.unavailable =0)"
                                . " AND l.delete_at IS NULL "
                                . $query_resale
                                . " and l.crawler_price>=(select avg(sub_price2.crawler_price) from module_imobles_listings sub_price2 WHERE  sub_price2.unit_type_id=u.id " . $filterListMediaPriceLIsting . ")*0.6"
                                . "   AND  u.module_imobles_enterprise_id IN (" . $d['id'] . ")"
                                . " GROUP BY u.module_imobles_enterprise_id, u.id, u.number_rooms, u.number_suite, u.area, u.number_garage, u.number_bathroom")
                        ->find_array();
                if (count($types) > 0) {
                    foreach ($types as $u) {

                        if (count($imagB) > 0) {
                            foreach ($imagB as $im) {
                                $arr_tags = array();
                                if ($im['unit_type_id'] != $u['id']) {
                                    continue;
                                }
                                if (empty($arr_unit_type_imgs[$u['id']]) || count($arr_unit_type_imgs[$u['id']]) < 10) {
                                    $arr_tags_id = json_decode($im['tags']);
                                    $arr_tags_aux = ORM::for_table('module_imobles_enterprise_img_backend_tags')->select('name')->where_in('id', $arr_tags_id)->find_array();

                                    foreach ($arr_tags_aux as $tags) {
                                        $arr_tags[] = $tags['name'];
                                    }
                                    $arr_unit_type_imgs[$u['id']][] = array(
                                        "type" => 'IMAGE',
                                        "url" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/" . $im['src'],
                                        "description" => $im['description'],
                                        "tags" => $arr_tags);
                                } else {
                                    break;
                                }
                            }
                        }

                        $min = ORM::for_table('module_imobles_enterprise_units_type')
                                ->raw_query(" SELECT "
                                        . " min(l.crawler_price) as minValue"
                                        . " FROM module_imobles_listings  l "
                                        . " WHERE "
                                        . " l.id in (" . $u['list_listings'] . ") and l.crawler_price>=" . ($u['averageValue'] * 0.6))
                                ->find_array();

                        //bbusca os tipos de unidade
                        $am = ORM::for_table('module_imobles_enterprise_units_type_amenities')
                                ->table_alias('s')
                                ->select("sub.name")
                                ->select_expr("sub.type")
                                ->join('module_imobles_type_units_amenities', 's.module_imobles_type_units_amenities_id = sub.id', 'sub')
                                ->where('s.module_imobles_enterprise_units_type_id', $u['id'])
                                ->find_array();

                        if ($u['averageValue'] < $min[0]['minValue']) {
                            $u['averageValue'] = $min[0]['minValue'];
                        }

                        $dataResults['unit_type'] [] = array(
                            "id" => $u['id'],
                            "total_listing" => $u['total_listing'],
                            "unit_available" => $u['disponible_unit'],
                            "min_value" => number_format($min[0]['minValue'], 2, ".", ""),
                            "average_value" => number_format($u['averageValue'], 2, ".", ""),
                            "max_value" => number_format($u['maxValue'], 2, ".", ""),
                            "bedrooms" => $u['bedrooms'],
                            "bathrooms" => $u['bathrooms'],
                            "area" => $u['area'],
                            "suites" => $u['suites'],
                            "parking_spaces" => $u['parking_spaces'],
                            "amenities" => $am,
                            "medias" => @$arr_unit_type_imgs[$u['id']]
                        );
                    }
                }


                $amenities = ORM::for_table('module_imobles_enterprise_entreprise_amenities')
                        ->table_alias('s')
                        ->select("sub.name")
                        ->select_expr(" sub.type")
                        ->join('module_imobles_enterprise_amenities', 's.module_imobles_enterprise_amenities_id = sub.id', 'sub')
                        ->where('s.module_imobles_enterprise_id', $d['id'])
                        ->find_array();
                $dataResults['amenities'] = $amenities;

                // Pego os amenities obrigatórios
                $required_amenities = ORM::for_table("module_imobles_enterprise_amenities")->select_many('name', 'type')->where("required", 1)->find_array();
                $dataResults['required_amenities'] = $required_amenities;
            }
        }


        $output = array(
            "time" => (microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']),
            "results" => ($dataResults),
        );
        header('Content-Type: application/json');
        echo json_encode($output);
        exit();
    }

    /**
     * Send Message
     * Função que faz o cadastro do novo Lead e o envio da primeira mensagem por whats
     *
     * @param  
     * @return JSON 
     */
    public function mandeUmZapHubspot() {
        $jsonStr = file_get_contents("php://input");
        $data = json_decode($jsonStr, true);
        foreach ($data as $event) {
            if (isset($event['objectId'])) {
                // Pego os dados do Cliente no HubSpot
                $url = "https://api.hubapi.com/crm/v3/objects/contacts/"
                        . $event['objectId']
                        . "?hapikey=2149faed-582c-48fa-950e-01d9cd403b06"
                        . "&properties=phone,email,firstname,lastname,apto_de_interesse_atual,"
                        . "n_mero_de_quartos,lancamentos_interesse,horario_de_preferencia_de_contato,canal_de_contato,"
                        . "data_de_entrega___cta_lista,lista_detalhes_da_solicitacao,quartos___cta_lista,"
                        . "faixa_de_preco___cta_lista,data_de_entrega___cta_lista,bairro";
                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                $json_response = curl_exec($ch);
                $result = json_decode($json_response);
                if (isset($result->properties->phone)) {
                    // Trato o Telefone cadastrado no Hubspot
                    $phone = preg_replace('/\D/', '', $result->properties->phone);
                    if (!preg_match('/^\+/', trim($result->properties->phone))) {
                        if (!preg_match('/^55/', $phone)) {
                            $phone = "55" . $phone;
                        }
                    }
                    $name = mb_strtoupper($result->properties->firstname . " " . $result->properties->lastname);

                    // Verifico se o usuário já está cadastrado
                    $client = ORM::for_table("crm_accounts")->where('code', $result->id)->find_one();

                    if (!isset($client->id)) {
                        $client = ORM::for_table("crm_accounts")->create();
                        $client->account = $name;
                        $client->phone = $phone;
                        $client->email = $result->properties->email;
                        $client->kind_of_person = 'PF';
                        $client->code = $result->id;
                        $client->created_at = date('Y-m-d H:i:s');
                        $client_id = $client->save();

                        // Verifico o horário para saber se deve ser enviada a mensagem automática
                        $dataAux = new DateTime('now', new DateTimeZone('America/Sao_Paulo'));
                        $hora_aux = intval($dataAux->format('H'));
                        $send_msg = false;
                        if ($dataAux->format('D') != 'Sun' && $dataAux->format('D') != 'Sat') {
                            if ($hora_aux <= 7 || $hora_aux >= 19) {
                                $send_msg = true;
                            }
                        } elseif ($dataAux->format('D') == 'Sat') {
                            if ($hora_aux <= 7 || $hora_aux >= 19) {
                                $send_msg = true;
                            }
                        } else {
                            $send_msg = true;
                        }

                        $firstname = trim(strtolower($result->properties->firstname));
                        if (preg_match('/testezap/i', $firstname)) {
                            $send_msg = true;
                        }



                        // Envio a mensagaem automática
                        $msg = null;
                        if ($send_msg === true) {
                            // Pego os empreendimentos de interesse
                            $enterprises_selecteds = array();
                            if (!empty($result->properties->apto_de_interesse_atual)) {
                                if (preg_match('/Solicitacao de Lista/i', $result->properties->apto_de_interesse_atual)) {
                                    if (preg_match('/CTA/i', $result->properties->apto_de_interesse_atual)) {
                                        $arr_msg_lista = explode("-", $result->properties->lista_detalhes_da_solicitacao);
                                    } else {
                                        $arr_msg_lista = explode("|", $result->properties->lista_detalhes_da_solicitacao);
                                    }

                                    unset($arr_msg_lista[count($arr_msg_lista) - 1]);
                                    //                                var_dump($arr_msg_lista);exit;
                                    $msg_lista = null;
                                    foreach ($arr_msg_lista as $item_msg) {
                                        if (!empty(trim($item_msg))) {
                                            $msg_lista .= trim($item_msg) . ", ";
                                        }
                                    }

                                    // Monto a mensagem para solicitação de lista
                                    $msg = "Olá " . $name . ", tudo bem? 😃\n\n"
                                            . "Entro em contato porque você solicitou a lista de empreendimentos no " . $msg_lista . " em nosso site.\n\n"
                                            . "Estamos offline agora 🌙, e não gostamos de enviar qualquer informação para desperdiçar seu "
                                            . "tempo com bobagens. Fazemos um trabalho CUSTOMIZADO e trabalhamos com TODOS apartamentos de Goiânia: na planta, prontos, novos e revenda! 😉\n\n"
                                            . "Amanhã entraremos em contato já com uma lista inicial para customizar às suas necessidades. Qual o melhor horário?\n\n"
                                            . "🔍 Enquanto isso, se quiser ir deixando mais detalhes aqui que me ajudem a acertar na mosca o que você busca, fique à vontade!\n\n"
                                            . "Uma ótima noite da equipe imobles.com!🌃";
                                } else {
                                    //                                $arr_enterprises = explode(';', $result->properties->apto_de_interesse_atual);
                                    //                                $enterprise_selected = trim($arr_enterprises[0]);
                                    //                                $enterprise_aux = ORM::for_table('module_imobles_enterprise')->select("id")->where("hubspot", $enterprise_selected)->find_one();
                                    //                                if (isset($enterprise_aux->id)) 
                                    //                                {
                                    //                                    // Pego os dados do empreendimento via API
                                    //                                    $url = "https://imobles.lrsys.com.br/?ng=api&key=gg7m8b7ruqaptg4a0jc9f4604qrsm1et7b66c3nx&method=plugin&plugin=module_imobles&pl_method=developmentDetails";
                                    //                                    $postdata = '{"development_id" : ' . $enterprise_aux->id . '}';
                                    //                                    $ch = curl_init($url);
                                    //                                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                    //                                    curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
                                    //                                    $json_response = curl_exec($ch);
                                    //                                    $result_ent = json_decode($json_response);
                                    //                                    $enterprises_selecteds[] = $result;
                                    //
    //                                    $arr_unit_types = $result_ent->results->unit_type;
                                    //                                    $price = 0;
                                    //                                    $unit_type = null;
                                    //                                    foreach ($arr_unit_types as $unit_type_aux) 
                                    //                                    {
                                    //                                        if ($price == 0 || $price > $unit_type_aux->min_value) 
                                    //                                        {
                                    //                                            $price = $unit_type_aux->min_value;
                                    //                                            $unit_type = $unit_type_aux;
                                    //                                        }
                                    //                                    }
                                    //                                    
                                    //                                    // Pego a data de lançamento
                                    //                                    $release_date = $result_ent->results->release_date;
                                    //                                    if($dataAux->format('Y-m-d') > $release_date)
                                    //                                    {
                                    //                                        $msg_unit = "Quanto ao plano de pagamento 💰, o valor total da unidade mais em conta de " . $unit_type->area . "m2 com " . $unit_type->bedrooms
                                    //                                                . " quartos" . ($unit_type->suites > 0 ? ", sendo " . $unit_type->suites . " suite" . ($unit_type->suites > 1 ? "s" : "") . "," : ",")
                                    //                                                . " fica em torno de R$" . number_format($unit_type->min_value, 0, ",", ".") . ", e como esse é um imóvel já pronto para morar, "
                                    //                                                . "a entrada é normalmente 20% (R$" . number_format(($unit_type->min_value*0.2), 0, ",", ".") . ") e o restante é financiado com o banco.\n\n";
                                    //
    //
    //                                        $msg = "*" . $result_ent->results->name . " - Plano de Pagamento*\n\n"
                                    //                                                . "Olá, " . $name . " Tudo bem? 😃\n\n"
                                    //                                                . "Conforme sua solicitação em nosso site, seguem as informações sobre o plano de pagamento do *" . $result_ent->results->name . "* 👇\n\n"
                                    //                                                . "Primeiro, uma apresentação para sua referência: \n\n"
                                    //                                                . $result_ent->results->link_presentation . " \n\n"
                                    //                                                . $msg_unit
                                    //                                                . "Trabalhamos com todos os imóveis de Goiânia: na planta, prontos, novos e revenda 😉. \n\n"
                                    //                                                . "Então gostaríamos de preparar uma lista com opções, assim você pode reunir informações, comparar os apartamentos e fazer o melhor negócio! \n\n"
                                    //                                                . "O que você acha?  \n\n"
                                    //                                                . "Aah e antes que eu esqueça, se você quiser já pode ir deixando suas dúvidas aqui. Agora estamos descansando 🌙, mas amanhã, assim que chegarmos, "
                                    //                                                . "entraremos em contato para explicar TODOS os detalhes! \n\n"
                                    //                                                . "Uma ótima noite da equipe imobles.com!🌃";
                                    //                                    }
                                    //                                    else
                                    //                                    {
                                    //                                        $msg_unit = "💰 O preço da unidade mais em conta de " . $unit_type->area . "m2 com " . $unit_type->bedrooms
                                    //                                                . " quartos" . ($unit_type->suites > 0 ? ", sendo " . $unit_type->suites . " suite" . ($unit_type->suites > 1 ? "s" : "") . "," : ",")
                                    //                                                . " fica em torno de R$" . number_format($unit_type->min_value, 0, ",", ".") . ".\n\n"
                                    //                                                . "O plano de pagamento funciona assim:\n\n"
                                    //                                                . "R$" . (number_format(($unit_type->min_value * $result_ent->results->financing->founding), 0, ",", ".")) . " devem ser pagos até a entrega das chaves, em 35 meses;\n\n"
                                    //                                                . "A entrada padrão é de R$" . (number_format(($unit_type->min_value * $result_ent->results->financing->entry), 0, ",", ".")) . ";\n\n"
                                    //                                                . "As parcelas mensais são de R$" . (number_format(($unit_type->min_value * $result_ent->results->financing->installment), 0, ",", ".")) . ";\n\n"
                                    //                                                . "Além disso, tem um valor de parcelas intermediárias, que pode ser ajustado conforme for melhor para você.\n\n";
                                    //
    //
    //                                        $msg = "*" . $result_ent->results->name . " - Plano de Pagamento*\n\n"
                                    //                                                . "Olá, " . $name . " Tudo bem? 😃\n\n"
                                    //                                                . "Conforme você solicitou, seguem as informações do *" . $result_ent->results->name . "* 👇\n\n"
                                    //                                                . "Antes dos valores, separei uma apresentação do empreendimento para sua referência: \n\n"
                                    //                                                . $result_ent->results->link_presentation . " \n\n"
                                    //                                                . $msg_unit
                                    //                                                . "Trabalhamos com todos os imóveis de Goiânia: na planta, prontos, novos e revenda 😉. \n\n"
                                    //                                                . "Então gostaríamos de preparar uma lista com opções, assim você pode reunir informações, comparar os apartamentos e fazer o melhor negócio! \n\n"
                                    //                                                . "O que você acha?  \n\n"
                                    //                                                . "Aah e antes que eu esqueça, se você quiser já pode ir deixando suas dúvidas aqui. Agora estamos descansando 🌙, mas amanhã, assim que chegarmos, "
                                    //                                                . "entraremos em contato para explicar TODOS os detalhes! \n\n"
                                    //                                                . "Uma ótima noite da equipe imobles.com!🌃";
                                    //                                    }
                                    //                                }
                                }
                            }

                            // Faço o envio da mensagem pelo MandeUmZap
                            if (!empty($msg)) {
                                $send_msg = $this->crawlerController->mandeUmZapSendMessage($phone, $name, $msg);
                                if ($send_msg["success"] == true) {
                                    echo "OK";
                                } else {
                                    echo "ERROR";
                                }
                            }
                        }
                    } else {
                        $client_id = $client->id;
                        $client->account = $name;
                        $client->email = $result->properties->email;
                        $client->phone = $phone;
                        $client->updated_at = date('Y-m-d H:i:s');
                        $client->save();
                    }
                }
            }
        }
    }

}

Anon7 - 2022
AnonSec Team