AnonSec Shell
Server IP : 162.214.74.102  /  Your IP : 216.73.217.111
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/.trash/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/lrsys/.trash/TypeunityController.php_
<?php
@ini_set('memory_limit', -1);
@ini_set('max_execution_time', 0);
@set_time_limit(0);
ini_set('mysql.connect_timeout', 14400);
ini_set('default_socket_timeout', 14400);

include_once "Controller.php";
include_once __DIR__ . "/../controllers/CrawlerController.php";
include_once __DIR__ . "/../models/TypeunityModel.php";
include_once __DIR__ . "/../models/Typeunits_amenitiesModel.php";
include_once __DIR__ . "/../assets/libs/Helper.php";

class TypeunityController extends Controller {

    protected $id;
    protected $model;

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

        $this->ui->assign('_title', $this->_L['module imobles typeunity'] . ' - ' . $this->config['CompanyName']);
        $this->ui->assign('_st', $_L['module imobles']);

        $this->model = new TypeunityModel();

        $this->id = $this->routes[3];
    }

    public function listAll() {
        $where = '';
        $filter['items_per_page'] = 10;
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $filter['search'] = filter_var(_post('search'), FILTER_SANITIZE_STRING);
            $filter['module_imobles_enterprise_id'] = filter_var(_post('module_imobles_enterprise_id'), FILTER_SANITIZE_STRING);
            $amenities = empty($_POST['amenities']) ? "" : implode(",", $_POST['module_imobles_type_units_amenities']);
            $filter['amenities'] = filter_var($amenities, FILTER_SANITIZE_STRING);
            $filter['items_per_page'] = filter_var(_post('items_per_page'), FILTER_SANITIZE_STRING);
        } else {
            if ($i = array_search('search', $this->routes))
                $filter['search'] = filter_var($this->routes[$i + 1], FILTER_SANITIZE_STRING);
            if ($i = array_search('module_imobles_enterprise_id', $this->routes))
                $filter['module_imobles_enterprise_id'] = filter_var($this->routes[$i + 1], FILTER_SANITIZE_STRING);
            if ($i = array_search('module_imobles_type_units_amenities', $this->routes))
                $filter['module_imobles_type_units_amenities'] = filter_var($this->routes[$i + 1], FILTER_SANITIZE_STRING);
            if ($i = array_search('items_per_page', $this->routes))
                $filter['items_per_page'] = filter_var($this->routes[$i + 1], FILTER_SANITIZE_STRING);
        }

        if (!empty($filter['search'])) {
            $where .= " AND (e.title  LIKE '%" . ($filter['search']) . "%' or "
                    . " e.alias  LIKE '%" . ($filter['search']) . "%' )";
        }

        if (!empty($filter['module_imobles_enterprise_id'])) {
            $where .= " AND     e.module_imobles_enterprise_id ='" . htmlentities($filter['module_imobles_enterprise_id']) . "'";
            $module_imobles_enterprise = ORM::for_table('module_imobles_enterprise')
                            ->table_alias('s')
                            ->where('s.id', $filter['module_imobles_enterprise_id'])
                            ->find_many()->limit(1);
            $this->ui->assign('module_imobles_enterprise', $module_imobles_enterprise[0]);
        }
        $module_imobles_type_units_amenities = '';
        if (isset($filter['amenities']) && $filter['amenities'] != '') {

            $where .= " AND e.id in (select sub.module_imobles_enterprise_units_type_id from module_imobles_enterprise_units_type_amenities sub where sub.module_imobles_type_units_amenities_id IN (" . $filter['module_imobles_type_units_amenities'] . "))";
            $amen = ORM::for_table('module_imobles_type_units_amenities')->where_raw("id IN (" . $filter['module_imobles_type_units_amenities'] . ")")->find_many();
            if (count($amen) > 0) {
                foreach ($amen as $c) {
                    $module_imobles_type_units_amenities .= '<option value="' . $c->id . '" selected >' . $c->name . '</option>';
                }
            }
        }
        $this->ui->assign('amenities', $module_imobles_type_units_amenities);


        $sql = ' FROM module_imobles_enterprise_units_type e'
                . ' LEFT JOIN module_imobles_enterprise ent ON(ent.id=e.module_imobles_enterprise_id)'
                . '  WHERE e.delete_at IS NULL and  ent.delete_at IS NULL' . $where;

        $order = ' order by e.id desc';
        if ($filter['items_per_page'] != 'all')
            $filter['items_per_page'] = ($filter['items_per_page'] > 0) ? $filter['items_per_page'] : 10;

        $page = isset($this->routes['3']) ? $this->routes['3'] : 1;

        $paginator = new ModulePaginator('module_imobles_enterprise_units_type', "Select e.*,ent.name as enterprise_name " . $sql . $order, $filter);
        $records = $paginator->setItemsPerPage($filter['items_per_page'])
                ->setCurrentPageNumber($page)
                ->run();

        $css_arr = array('/../../../application/plugins/module_imobles/assets/css/default', 's2/css/select2.min');

        $js_arr = array(
            '/../../../application/plugins/module_imobles/assets/js/typeunity-list', 's2/js/select2.min'
        );

        $assets_css = Asset::css($css_arr, date("Y-m-d"));
        $assets_js = Asset::js($js_arr, "v12");

        $this->ui->assign('xheader', $assets_css);
        $this->ui->assign('xfooter', $assets_js);

        $this->ui->assign('typeunit', $records);
        $this->ui->assign('paginator', $paginator);
        $this->ui->assign('filter', $filter);
        $this->ui->assign('tanks', $records);

        $d = ORM::for_table('module_imobles_enterprise_units_type')->raw_query("select count(e.id)  as total  " . $sql . "")->find_many();


        $bottomBar = array(
            array('type' => 'int', 'info' => $this->_L['module imobles typeunitys_Qty'], 'value' => $d[0]['total']),
        );
        $this->ui->assign('bottomBar', $bottomBar);

        $this->ui->assign('_st', $this->_L['module imobles typeunity']);
        $this->ui->assign('_include', 'typeunitys/list');
        $this->ui->display('wrapper.tpl');
    }

    public function search_order() {
        $campo = _post('campo');
        $_SESSION['order']['module_imobles/typeunity/search'][$campo] = next_order_table(filter_var(_post('value'), FILTER_SANITIZE_STRING));
        echo $_SESSION['order']['module_imobles/typeunity/search'][$campo];
    }

    public function desactive_listing() {
        $status = ORM::for_table('module_imobles_listings')->find_one(_post('id'));
        if ($status) {
            $status->unavailable = 1;
            if ($status->save()) {
                echo json_encode(array("status" => "OK", 'msg' => $this->_L['module imobles desctived Successfull']));
                exit();
            }
        }
        echo json_encode(array("status" => "OK", 'msg' => $this->_L['module imobles error desctived']));
    }

    public function search() {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            unset($_SESSION['order']['module_imobles/typeunity/search']);

            if (filter_var(_post('clear_filter'), FILTER_SANITIZE_STRING) == 1) {
                unset($_SESSION['filter']['module_imobles/typeunity/search']);
            } else {
                $_SESSION['filter']['module_imobles/typeunity/search']['date_delivery_period'] = _post('date_delivery_period');
                if ($_SESSION['filter']['module_imobles/typeunity/search']['date_delivery_period'] == 'interval') {
                    $_SESSION['filter']['module_imobles/typeunity/search']['date_delivery_period_ini'] = _postDate('date_delivery_period_ini');
                    $_SESSION['filter']['module_imobles/typeunity/search']['date_delivery_period_end'] = _postDate('date_delivery_period_end');
                } else {
                    $_SESSION['filter']['module_imobles/typeunity/search']['date_delivery_period_ini'] = '';
                    $_SESSION['filter']['module_imobles/typeunity/search']['date_delivery_period_end'] = '';
                }
                $_SESSION['filter']['module_imobles/typeunity/search']['search'] = filter_var(_post('search'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['address'] = array();
                if (isset($_POST['address_desc'])) {
                    for ($i = 0; $i < count($_POST['address_desc']); $i++) {
                        if (!empty($_POST['address_desc'][$i])) {
                            $_SESSION['filter']['module_imobles/typeunity/search']['address'][$i]['address_desc'] = $_POST['address_desc'][$i];
                            $_SESSION['filter']['module_imobles/typeunity/search']['address'][$i]['address_log'] = $_POST['address_log'][$i];
                            $_SESSION['filter']['module_imobles/typeunity/search']['address'][$i]['address_neighborhood'] = $_POST['address_neighborhood'][$i];
                            $_SESSION['filter']['module_imobles/typeunity/search']['address'][$i]['address_number'] = $_POST['address_number'][$i];
                            $_SESSION['filter']['module_imobles/typeunity/search']['address'][$i]['address_zip'] = $_POST['address_zip'][$i];
                            $_SESSION['filter']['module_imobles/typeunity/search']['address'][$i]['address_state'] = $_POST['address_state'][$i];
                            $_SESSION['filter']['module_imobles/typeunity/search']['address'][$i]['address_city'] = $_POST['address_city'][$i];
                        }
                    }
                }


                $_SESSION['filter']['module_imobles/typeunity/search']['area_min'] = filter_var(_post('area_min'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['area'] = filter_var(_post('area'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['varanda_sacada'] = filter_var(_post('varanda_sacada'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['number_rooms'] = filter_var(_post('number_rooms'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['number_suite'] = filter_var(_post('number_suite'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['number_bathroom'] = filter_var(_post('number_bathroom'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['number_toilet'] = filter_var(_post('number_toilet'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['number_garage'] = filter_var(_post('number_garage'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['comparator_status'] = filter_var(_post('comparator_status'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['roof'] = filter_var(_post('roof'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['showimages'] = filter_var(_post('showimages'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['resale'] = filter_var(_post('resale'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['promotion'] = filter_var(_post('promotion'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['duplex'] = filter_var(_post('duplex'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['hobbox'] = filter_var(_post('hobbox'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['garage_drawer'] = filter_var(_post('garage_drawer'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['amount_max'] = filter_var(_post('amount_max'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['amount_min'] = filter_var(_post('amount_min'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['enterprise_towers_stage'] = filter_var(_post('enterprise_towers_stage'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['module_imobles_company_construction_id'] = filter_var(_post('module_imobles_company_construction_id'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['dummys'] = filter_var(_post('dummys'), FILTER_SANITIZE_STRING);
                $_SESSION['filter']['module_imobles/typeunity/search']['unity_disponible'] = filter_var(_post('unity_disponible'), FILTER_SANITIZE_STRING);
                $entreprises = empty($_POST['module_imobles_enterprise_id']) ? "" : implode(",", $_POST['module_imobles_enterprise_id']);
                $_SESSION['filter']['module_imobles/typeunity/search']['module_imobles_enterprise_id'] = filter_var($entreprises, FILTER_SANITIZE_STRING);

                $amenities = empty($_POST['amenities']) ? "" : implode(",", $_POST['amenities']);
                $_SESSION['filter']['module_imobles/typeunity/search']['amenities'] = filter_var($amenities, FILTER_SANITIZE_STRING);

                $neighborhood = empty($_POST['neighborhood']) ? "" : $_POST['neighborhood'];
                $_SESSION['filter']['module_imobles/typeunity/search']['neighborhood'] = $neighborhood;
            }
        } elseif (isset($this->routes[3])) {
            $arr_type_unit_ids = explode('=', $this->routes[3]);
            if ($arr_type_unit_ids[0] === "unit_type_ids") {
                $_SESSION['filter']['module_imobles/typeunity/unit_type_ids'] = $arr_type_unit_ids[1];
            }
        }


        if (isset($_SESSION['order']['module_imobles/typeunity/search'])) {
            $order = $_SESSION['order']['module_imobles/typeunity/search'];
        } else {
            $order = array();
            $order[9] = 'asc';
//            $order[3] = 'asc';
            $_SESSION['order']['module_imobles/typeunity/search'][9] = 'asc';
//            $_SESSION['order']['module_imobles/typeunity/search'][3] = 'asc';
        }

        for ($i = 1; $i <= 9; $i++) {
            if (!isset($order[$i])) {
                $order[$i] = "";
            }
        }

        if (isset($_SESSION['filter']['module_imobles/typeunity/search'])) {
            $filter = $_SESSION['filter']['module_imobles/typeunity/search'];
            $this->ui->assign('showData', true);
        } else {
            $this->ui->assign('showData', false);
            $filter = array();

            $filter['area_min'] = '';
            $filter['area'] = '';
            $filter['varanda_sacada'] = '';
            $filter['number_rooms'] = '';
            $filter['number_suite'] = '';
            $filter['number_bathroom'] = '';
            $filter['number_toilet'] = '';
            $filter['number_garage'] = '';
            $filter['comparator_status'] = '';
            $filter['roof'] = '';
            $filter['showimages'] = '';
            $filter['resale'] = '';
            $filter['promotion'] = '';
            $filter['duplex'] = '';
            $filter['hobbox'] = '';
            $filter['garage_drawer'] = '';
            $filter['amount_max'] = '';
            $filter['amount_min'] = '';
            $filter['enterprise_towers_stage'] = '';
            $filter['date_delivery_period'] = '';
            $filter['date_delivery_period_ini'] = '';
            $filter['date_delivery_period_end'] = '';
            $filter['search'] = "";
            $filter['dummys'] = "";
            $filter['unity_disponible'] = "";
            $filter['neighborhood'] = "";
        }
//carrega dados dos selects tmbm
        extract($this->searchWhereJoin($filter));  // retira as variaveis wheer e join
        $css_arr = array('slider/jquery.bxslider', 'dp/dist/datepicker.min', 'modal', '/../../../application/plugins/module_imobles/assets/css/default', 's2/css/select2.min');

        $js_arr = array('slider/jquery.bxslider', 'dp/dist/datepicker.min', 'modal', 'dataTables/jquery.dataTables', 'dataTables/paginate',
            '/../../../application/plugins/module_imobles/assets/js/typeunity-search', 's2/js/select2.min'
        );


        $assets_css = Asset::css($css_arr, "v11");
        $assets_js = Asset::js($js_arr, "v11");

        $this->ui->assign('order', $order);

        $this->ui->assign('xheader', $assets_css);
        $this->ui->assign('xfooter', $assets_js);
        $this->ui->assign('filter', $filter);

        $bottomBar = array(
            ((isset($filter['resale']) && $filter['resale'] == 1) ?
            array('type' => 'ajax', 'info' => $this->_L['module imobles tot listing'], 'value' => '<span class="bar_bottom_2 bar_bottom_view">--</span>') : array('type' => 'int', 'info' => '', 'value' => '')),
            array('type' => 'ajax', 'info' => $this->_L['module imobles tot unity'], 'value' => '<span class="bar_bottom_3 bar_bottom_view">--</span>'),
            array('type' => 'ajax', 'info' => $this->_L['module imobles tot type_unity'], 'value' => '<span class="bar_bottom_4 bar_bottom_view">--</span>'),
            array('type' => 'ajax', 'info' => $this->_L['module imobles tot enterprise'], 'value' => '<span class="bar_bottom_1 bar_bottom_view">--</span>'),
        );

        $this->ui->assign('bottomBar', $bottomBar);

        $this->ui->assign('jsvar', '
        _L[\'Yes\'] = \'' . $this->_L['Yes'] . '\';
        _L[\'No\'] = \'' . $this->_L['No'] . '\';
        _L[\'module_imobles desactive listing?\'] = \'' . $this->_L['module_imobles desactive listing?'] . '\';
        _L[\'send success\'] = \'' . $this->_L['module imobles send success'] . '\';
        _L[\'fail send\'] = \'' . $this->_L['module imobles fail send'] . '\';
        _L[\'select one listing\'] = \'' . $this->_L['module imobles select one listing'] . '\';
        _L[\'module imobles select one enterprise\'] = \'' . $this->_L['module imobles select one enterprise'] . '\';
        _L[\'module imobles select one typeunit\'] = \'' . $this->_L['module imobles select one typenity'] . '\';
        _L[\'module imobles typenity enteprise distinct not group\'] = \'' . $this->_L['module imobles typenity enteprise distinct not group'] . '\';
        _L[\'module imobles group successfull\'] = \'' . $this->_L['module imobles group successfull'] . '\';
        _L[\'module imobles review listings\'] = \'' . $this->_L['module imobles review listings'] . '\';
        _L[\'module imobles text title msg whats\'] = \'' . $this->_L['module imobles text title msg whats'] . '\';
        _L[\'module imobles text msg whats\'] = \'' . $this->_L['module imobles text msg whats'] . '\';
        ');


        $this->ui->assign('_st', $this->_L['module imobles search type unity']);
        $this->ui->assign('_include', 'typeunitys/search');
        $this->ui->display('wrapper.tpl');
    }

    public function search_barBottom() {
        if (isset($_SESSION['filter']['module_imobles/typeunity/search'])) {
            $filter = $_SESSION['filter']['module_imobles/typeunity/search'];
        } else {
            $filter = array();
        }

        extract($this->searchWhereJoin($filter));  // retira as variaveis wheer e join
        if (!isset($filter['resale']) || $filter['resale'] != 1) {
            $total_listings = 0;
        } else {
            $totListing = ORM::for_table('module_imobles_listings')->raw_query(
                            "select count(l.id)  as total" . ' '
                            . ' FROM module_imobles_listings l  '
                            . '  JOIN module_imobles_enterprise_units_type e ON(l.unit_type_id=e.id )'
                            . '  JOIN module_imobles_enterprise ent ON(ent.id=e.module_imobles_enterprise_id)'
                            . " 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 and e.delete_at IS NULL '
                            . '  AND  l.advertiser_id IS NOT NULL ' . $where . "")->find_many();
            $total_listings = $totListing[0]['total'];
        }


        $where_resale = null;
        if (!isset($filter['resale']) || $filter['resale'] != 1) {
            $where_resale = " AND ent.crawler_type_id = 4";
        }
        $totListing2 = ORM::for_table('module_imobles_listings')->raw_query(
                        'select count(distinct(ent.id))  as total_enterprise'
                        . ", count(distinct(u.id))  as total_unit"
                        . ", count(distinct(e.id))  as total_unit_type"
                        . ' FROM module_imobles_enterprise ent '
                        . '  JOIN module_imobles_enterprise_units_type e ON(ent.id=e.module_imobles_enterprise_id)'
                        . '  JOIN module_imobles_enterprise_units u ON(u.module_imobles_enterprise_units_type_id=e.id)'
                        . $join . '  WHERE  ent.delete_at IS NULL AND e.delete_at IS NULL '
                        . $where . $where_resale . ""
                )->find_many();

        echo json_encode(array(
            'bar_bottom_1' => $totListing2[0]['total_enterprise'],
            'bar_bottom_2' => $total_listings,
            'bar_bottom_3' => $totListing2[0]['total_unit'],
            'bar_bottom_4' => $totListing2[0]['total_unit_type']
        ));
    }

    private function searchWhereJoin($filter) {
        $where = '';
        $join = '';
        $module_imobles_company_construction = '';
        if (!empty($filter['module_imobles_company_construction_id'])) {
            $where .= " AND     ent.module_imobles_company_construction_id=  (" . ($filter['module_imobles_company_construction_id']) . ")";
            $moEnter = ORM::for_table('module_imobles_company_construction')
                    ->table_alias('s')
                    ->where('s.id', $filter['module_imobles_company_construction_id'])
                    ->find_many();

            if (count($moEnter) > 0) {
                foreach ($moEnter as $c) {
                    $module_imobles_company_construction .= '<option value="' . $c->id . '" selected >' . $c->name . '</option>';
                }
            }
        }
        $this->ui->assign('module_imobles_company_construction', $module_imobles_company_construction);

        $module_imobles_enterprises = '';
        if (!empty($filter['module_imobles_enterprise_id'])) {
            $where .= " AND     e.module_imobles_enterprise_id IN (" . ($filter['module_imobles_enterprise_id']) . ")";
            $moEnter = ORM::for_table('module_imobles_enterprise')
                    ->table_alias('s')
                    ->where_raw("s.id IN (" . ($filter['module_imobles_enterprise_id']) . ")")
                    ->find_many();

            if (count($moEnter) > 0) {
                foreach ($moEnter as $c) {
                    $module_imobles_enterprises .= '<option value="' . $c->id . '" selected >' . $c->name . (!empty($c->alias) ? " - " . $c->alias : "") . '</option>';
                }
            }
        }
        $this->ui->assign('module_imobles_enterprises', $module_imobles_enterprises);


        $neighborhood = '';

        if (!empty($filter['neighborhood'])) {
            $neig = "";
            foreach ($filter['neighborhood'] as $c) {
                $op = htmlentities($c);
                $neig .= ", '" . $op . "' ";
                $neighborhood .= '<option value="' . $op . '" selected >' . $op . '</option>';
            }
            $where .= " AND     ent.address_neightborhood  IN (" . (substr($neig, 1)) . ")";
        }
        $this->ui->assign('neighborhood', $neighborhood);



        $module_imobles_type_units_amenities = '';
        if (isset($filter['amenities']) && $filter['amenities'] != '') {
            $amenit = explode(",", $filter['amenities']);
            $a = array();
            foreach ($amenit as $am) {
                $e = explode("_", $am);
                $a[$e[0]][] = $e[1];
            }
            if (isset($a['ENTERPRISE'])) {

                $where .= " AND ent.id in (select sub.module_imobles_enterprise_id from module_imobles_enterprise_entreprise_amenities sub where sub.module_imobles_enterprise_amenities_id IN ('" . implode("','", $a['ENTERPRISE']) . "'))";
                $amen = ORM::for_table('module_imobles_enterprise_amenities')->where_raw("id IN ('" . implode("','", $a['ENTERPRISE']) . "')")->find_many();
                if (count($amen) > 0) {
                    foreach ($amen as $c) {
                        $module_imobles_type_units_amenities .= '<option value="ENTERPRISE_' . $c->id . '" selected >' . $c->name . '</option>';
                    }
                }
            }
            if (isset($a['TYPE_UNITY'])) {
                $where .= " AND e.id in (select sub.module_imobles_enterprise_units_type_id from module_imobles_enterprise_units_type_amenities sub where sub.module_imobles_type_units_amenities_id IN ('" . implode("','", $a['TYPE_UNITY']) . "'))";
                $amen = ORM::for_table('module_imobles_type_units_amenities')->where_raw("id IN ('" . implode("','", $a['TYPE_UNITY']) . "')")->find_many();
                if (count($amen) > 0) {
                    foreach ($amen as $c) {
                        $module_imobles_type_units_amenities .= '<option value="TYPE_UNITY_' . $c->id . '" selected >' . $c->name . '</option>';
                    }
                }
            }

            if (isset($a['UNITY'])) {
                $where .= " AND e.id in (select sub2.module_imobles_enterprise_units_type_id  from module_imobles_enterprise_units_amenities sub join module_imobles_enterprise_units sub2 on(sub2.id=sub.module_imobles_units_amenities_id) where sub.module_imobles_units_amenities_id IN ('" . implode("','", $a['UNITY']) . "'))";
                $amen = ORM::for_table('module_imobles_type_units_amenities')->where_raw("id IN ('" . implode("','", $a['UNITY']) . "')")->find_many();
                if (count($amen) > 0) {
                    foreach ($amen as $c) {
                        $module_imobles_type_units_amenities .= '<option value="UNITY_' . $c->id . '" selected >' . $c->name . '</option>';
                    }
                }
            }
        }
        $this->ui->assign('amenities', $module_imobles_type_units_amenities);



        if (!empty($filter['enterprise_towers_stage'])) {
            $subWhere = "";
            if ($filter['enterprise_towers_stage'] == 'Ready to move in') {
                $subWhere .= "OR (ent.release_date<='" . date('Y-m-d') . "') ";
            }
            if ($filter['enterprise_towers_stage'] == 'In Works') {
                $subWhere .= "OR (ent.release_date>'" . date('Y-m-d') . "') ";
            }

            $subWhere .= "OR tower.stage IN ('" . $filter['enterprise_towers_stage'] . "') ";
            $where .= " AND (" . substr($subWhere, 2) . ")";
        }


        if (isset($filter['date_delivery_period']) && $filter['date_delivery_period'] != '') {
            if ($filter['date_delivery_period'] != 'all') {
                if ($filter['date_delivery_period'] == 'day')
                    $where .= " AND tower.date_delivery = '" . date('Y-m-d') . "' "
                            . "OR (tower.date_delivery is null and ent.release_date= '" . date('Y-m-d') . "')";
                if ($filter['date_delivery_period'] == 'week')
                    $where .= " AND WEEK(tower.date_delivery) = WEEK('" . date('Y-m-d') . "') "
                            . "OR (tower.date_delivery is null and WEEK(ent.release_date)= WEEK('" . date('Y-m-d') . "'))";
                if ($filter['date_delivery_period'] == 'month')
                    $where .= " AND MONTH(tower.date_delivery) = MONTH('" . date('Y-m-d') . "')"
                            . "OR (tower.date_delivery is null and MONTH(ent.release_date)= MONTH('" . date('Y-m-d') . "'))";
                if ($filter['date_delivery_period'] == 'interval') {
                    if ($filter['date_delivery_period_ini'] != '') {
                        $where .= " AND tower.date_delivery >= '" . $filter['date_delivery_period_ini'] . "' "
                                . " OR (tower.date_delivery is null AND ent.release_date>='" . $filter['date_delivery_period_ini'] . "')";
                    }
                    if ($filter['date_delivery_period_end'] != '') {
                        $where .= " AND tower.date_delivery <= '" . $filter['date_delivery_period_end'] . "'"
                                . " OR (tower.date_delivery is null and  ent.release_date<='" . $filter['date_delivery_period_end'] . "')";
                    }
                }
            }
        }
        if (@$filter['address']) {

            $address_neightborhood = "";
            $address_number = "";
            $state = '';
            $city = '';
            $log = '';
            foreach ($filter['address'] as $d) {


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

                if (!empty($d['address_number'])) {
                    $address_number .= "OR ent.address_number  LIKE '%" . ($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 '%" . $this->sanitizaLogradouro(htmlentities($d['address_log'])) . "%'  "
                            . ")";
                }
            }

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

            if (!empty($state)) {
                $join .= ' LEFT JOIN state st ON(st.id=ent.address_state_id)';
                $where .= " AND (" . substr($state, 2) . ")";
            }



            if (!empty($city)) {
                $where .= " AND (" . substr($city, 2) . ")";
            }
            if (!empty($log)) {
                $where .= " AND (" . substr($log, 2) . ")";
            }
        }
        $join .= ' LEFT JOIN city c ON(c.id=ent.address_city_id)';

        if (!isset($filter['resale']) || $filter['resale'] != 1) {
            $where .= " AND (ent.crawler_type_id = 4)";
        }

//        if (!empty($filter['address_zip'])) {
//            $where .= " AND (ent.address_zip  LIKE '%" . preg_replace('/\D/', '', ($filter['address_zip'])) . "%' "
//                    . ")";
//        }



        if (!empty($filter['area_min'])) {
            $where .= " AND (e.area>=" . htmlentities(Finance::amount_fix($filter['area_min'])) . ""
                    . ")";
        }
        if (!empty($filter['area'])) {
            $where .= " AND (e.area<=" . htmlentities(Finance::amount_fix($filter['area'])) . ""
                    . ")";
        }


        if (!empty($filter['amount_min'])) {
            $where .= " AND   price.price>=" . htmlentities(Finance::amount_fix($filter['amount_min'])) . ""
                    . "";
        }
        if (!empty($filter['amount_max'])) {
            $where .= " AND price.price<=" . htmlentities(Finance::amount_fix($filter['amount_max'])) . ""
                    . "";
        }


        if (!empty($filter['varanda_sacada'])) {
            $where .= " AND (e.varanda_sacada='" . htmlentities(($filter['varanda_sacada'])) . "'"
                    . ")";
        }


        if (!empty($filter['number_rooms'])) {
            $where .= " AND (e.number_rooms IN (" . htmlentities($filter['number_rooms']) . ")"
                    . ")";
        }
        if (!empty($filter['number_suite'])) {
            $where .= " AND (e.number_suite IN (" . htmlentities($filter['number_suite']) . ")"
                    . ")";
        }
        if (!empty($filter['number_bathroom'])) {
            $where .= " AND (e.number_bathroom IN (" . htmlentities($filter['number_bathroom']) . ")"
                    . ")";
        }

        if (!empty($filter['number_toilet'])) {
            $where .= " AND (e.number_toilet IN (" . htmlentities($filter['number_toilet']) . ")"
                    . ")";
        }
        if (!empty($filter['number_garage'])) {
            $where .= " AND (e.number_garage IN (" . htmlentities($filter['number_garage']) . ")"
                    . ")";
        }

        if (!empty($filter['comparator_status'])) {
            $where .= " AND (e.comparator_status=" . htmlentities($filter['comparator_status']) . ""
                    . ")";
        }

        if (!empty($filter['promotion'])) {
            $where .= " AND (e.promotion=1)";
        }

        if (!empty($filter['duplex'])) {
            $where .= " AND (e.duplex=1)";
        }

        if (!empty($filter['roof'])) {
            $where .= " AND (e.roof=1)";
        }

        if (!empty($filter['hobbox'])) {
            $where .= " AND (e.hobbox=1)";
        }

        if (!empty($filter['garage_drawer'])) {
            $where .= " AND (e.garage_drawer=1)";
        }

        if (!empty($filter['search'])) {
            $arrstring = explode(";", $filter['search']);
            $string = implode("\"'  '\"", $arrstring);
            $string = "'\"" . $string . "\"'";
            $resa = '';
            if (!isset($filter['resale']) || $filter['resale'] != 1) {
                $resa = " AND crawler_type_id = 4 ";
            }
            $where .= " AND (e.id IN ("
                    . "SELECT distinct(unit_type_id)
                        FROM module_imobles_listings
                        WHERE MATCH(title, description, crawler_externalId)
                        AGAINST(" . $string . " IN BOOLEAN MODE) AND advertiser_id IS NOT NULL  " . $resa
                    . " AND unavailable IS NULL) )";
        }


        if (!empty($filter['resale']) && $filter['resale'] == 1) {
            if (empty($filter['dummys'])) {
                $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.unavailable IS NULL AND sub_w.unit_type_id=e.id  AND sub_w.advertiser_id IS NOT NULL "
                    . " AND sub_w.crawler_businessType = 'SALE' ))";
        } else {
            if (!empty($filter['unity_disponible'])) {
                $where .= " AND (EXISTS (select sub_w.id from module_imobles_listings  sub_w where sub_w.unit_id IS NOT NULL AND"
                        . "  (crawler_businessType <> 'RENTAL' OR crawler_businessType IS NULL) AND  sub_w.unavailable IS NULL AND sub_w.unit_type_id=e.id AND crawler_type_id = 4 "
                        . "))";
            }
        }
        return array("where" => $where, "join" => $join);
    }

    /**
     * cleanString
     * Remove todos dos caracteres especiais do texto e os acentos
     *
     * @param  string $texto
     * @return string Texto sem caractere especiais
     */
    public function cleanString($texto = '') {
        $texto = trim($texto);
        $aFind = array('&', 'á', 'à', 'ã', 'â', 'é', 'ê', 'í', 'ó', 'ô', 'õ', 'ú', 'ü',
            'ç', 'Á', 'À', 'Ã', 'Â', 'É', 'Ê', 'Í', 'Ó', 'Ô', 'Õ', 'Ú', 'Ü', 'Ç');
        $aSubs = array('e', 'a', 'a', 'a', 'a', 'e', 'e', 'i', 'o', 'o', 'o', 'u', 'u',
            'c', 'A', 'A', 'A', 'A', 'E', 'E', 'I', 'O', 'O', 'O', 'U', 'U', 'C');
        $novoTexto = str_replace($aFind, $aSubs, $texto);
        $novoTexto = preg_replace("/[^a-zA-Z0-9 @,-.;:\/]/", "", $novoTexto);
        return $novoTexto;
    }

    public function sanitizaLogradouro($string) {
        $sanit = $this->cleanString(strtolower(trim($string)));
        $sanit = preg_replace('/[^a-zA-Z0-9\']/', '', $sanit);
        return $sanit;
    }

    public function search_data() {
        $where = '';
        if (isset($_SESSION['filter']['module_imobles/typeunity/search'])) {
            $filter = $_SESSION['filter']['module_imobles/typeunity/search'];
        } else {
            $filter = array();
        }
        extract($this->searchWhereJoin($filter));

        $filterDatatable = getFiltrosDatatable(array("ignorar",
            'ent.name', 'ent.address_neightborhood', 'ent.address_log', 'e.area', 'e.number_rooms', 'e.number_suite', 'e.number_bathroom', 'e.number_garage', 'ignorar', 'ignorar', 'ignorar', 'ignorar'));

        $query_unit_type_ids = null;
        if (isset($_SESSION['filter']['module_imobles/typeunity/unit_type_ids'])) {
            $unit_type_ids = $_SESSION['filter']['module_imobles/typeunity/unit_type_ids'];
            $query_unit_type_ids = " AND e.id IN (" . $unit_type_ids . ") ";
            unset($_SESSION['filter']['module_imobles/typeunity/unit_type_ids']);
        }

        $sql = ' FROM module_imobles_enterprise_units_type e'
                . ' JOIN module_imobles_enterprise ent ON(ent.id=e.module_imobles_enterprise_id)'
                . ' LEFT  JOIN module_imobles_company_construction co ON(co.id=ent.module_imobles_company_construction_id)'
                . " 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 (select sub_price.unit_type_id, min(sub_price.crawler_price) as price from  module_imobles_listings sub_price GROUP BY 1) as price"
                . " ON (price.unit_type_id=e.id )"
                . $join . '  WHERE e.delete_at IS NULL and ent.delete_at IS NULL ' . $query_unit_type_ids
                . $where;

        if (isset($_SESSION['order']['module_imobles/typeunity/search'])) {
            $orderSession = $_SESSION['order']['module_imobles/typeunity/search'];
            $order = '';
            foreach ($orderSession as $key => $value) {
                if (!empty($value)) {
                    switch ($key) {
                        case 1:
                            $order .= ", ent.name " . $value;
                            break;
                        case 2:
                            $order .= ", ent.address_neightborhood " . $value;
                            break;
                        case 3:
                            $order .= ", ent.address_log " . $value;
                            $order .= ", ent.address_number " . $value;
                            break;
                        case 4:
                            $order .= ", e.area " . $value;
                            break;
                        case 5:
                            $order .= ", e.number_rooms " . $value;
                            break;
                        case 6:
                            $order .= ", e.number_suite " . $value;
                            break;
                        case 7:
                            $order .= ", e.number_bathroom " . $value;
                            break;
                        case 8:
                            $order .= ", e.number_garage " . $value;
                            break;
                        case 9:

                            $order .= ", (select min(sub_l.crawler_price) from module_imobles_listings sub_l "
                                    . " where  sub_l.entreprise_id=e.module_imobles_enterprise_id"
                                    . " and sub_l.unit_type_id=e.id ";
//                            if (!isset($filter['resale']) || $filter['resale'] != 1) {
                            //     $order .= " AND sub_l.crawler_type_id = 4 ";
//                            }

                            $order .= ") " . $value;

                            break;
                        case 10 :
                            $order .= ", co.name " . $value;
                            break;

                        case 0 :
                            $order = ',ent.address_neightborhood ASC,ent.address_log ASC, ent.address_number ASC,ent.id ASC';
                            break;
                    }
                }
            }
            if (!empty($order)) {
                $order = " order by " . substr($order, 1) . "";
            }
        } else {
            $order = ' order by  c.city_name ASC,ent.address_neightborhood ASC,ent.address_log ASC, ent.address_number ASC,ent.id ASC';
        }

        if ($filterDatatable['limit'] == '-1' || empty($filterDatatable['limit'])) {
            $filterDatatable['limit'] = 'all';
            $page = 1;
        } else {
            $page = $filterDatatable['start'] == 0 ? 1 : ($filterDatatable['start'] / $filterDatatable['limit']) + 1;
        }
//echo "Select "
//                . " co.name as company_construction ,e.number_rooms,e.number_bathroom, e.area, e.number_suite, e.number_garage, e.id, e.module_imobles_enterprise_id, "
//                . "ent.name as enterprise_name,ent.release_date,ent.address_log,ent.address_number,ent.address_neightborhood"
//                . ", ent.google_phone, ent.google_rating, ent.value_installment_porcentage, ent.value_founding_porcentage, ent.value_input_porcentage, ent.discount "
//                . ",DATE(tower.date_delivery) as date_delivery"
//                . $sql . $order; die();


        $paginator = new ModulePaginator('module_imobles_enterprise_units_type', "Select "
                . " co.name as company_construction ,e.number_rooms,e.number_bathroom, e.area, e.number_suite, e.number_garage, e.id, e.module_imobles_enterprise_id, "
                . "ent.name as enterprise_name,ent.release_date,ent.address_log,ent.address_number,ent.address_neightborhood"
                . ", ent.google_phone, ent.google_rating, ent.value_installment_porcentage, ent.value_founding_porcentage, ent.value_input_porcentage, ent.discount "
                . ",DATE(tower.date_delivery) as date_delivery"
                . $sql . $order, array());

        $records = $paginator->setItemsPerPage($filterDatatable['limit'])
                ->setCurrentPageNumber($page)
                ->run();
        $output = array(
            "sEcho" => intval($_GET['sEcho']),
            "iTotalRecords" => $paginator->total_items, //$iTotal,
            "iTotalDisplayRecords" => $paginator->total_items, // $iFilteredTotal,
            "aaData" => array()
        );
        if (count($records) > 0) {
            foreach ($records as $key => $value) {

                if (!empty($value['date_delivery'])) {
                    $records[$key]['release_date'] = $value['date_delivery'];
                }

                $query_resale_listing = '';
                $query_resale_unit = '';
                if (!isset($filter['resale']) || $filter['resale'] != 1) {
                    $query_resale_unit = " AND crawler_type_id = 4 ";
                    $query_resale_unit = " AND sub.crawler_type_id = 4 ";
                } else {
//                    $query_resale_listing = " AND crawler_type_id <> 4 ";
//                    $query_resale_unit = " AND sub.crawler_type_id <> 4 ";
                }

                $where_subSearch = '';
//                if (!empty($filter['search'])) {
//                    $arrstring = explode(",", $filter['search']);
//                    $string = implode("\"'  '\"", $arrstring);
//                    $string = "'\"" . $string . "\"'";
//
//
//                    $where_subSearch = " AND MATCH(title, description, crawler_externalId)
//                        AGAINST(" . $string . " IN BOOLEAN MODE) AND advertiser_id IS NOT NULL ";
//                }

                $d = ORM::for_table('module_imobles_enterprise_units_type')
                        ->raw_query(" select min(crawler_price) as min,"
                                . " max(crawler_price) as max,"
                                . " avg(crawler_price) as avg , "
                                . " count(crawler_price) as listing,"
                                . " group_concat(crawler_price) as  crawler_price_str"
                                . " from module_imobles_listings "
                                . " where entreprise_id=" . $value['module_imobles_enterprise_id'] . ""
                                . " AND  unit_type_id=" . $value['id'] . $query_resale_listing)
                        ->find_many();

                $totUnit = ORM::for_table('module_imobles_enterprise_units_type')
                        ->raw_query(" select  count(distinct(unit_id)) as total_unit"
                                . " from module_imobles_listings "
                                . " where entreprise_id=" . $value['module_imobles_enterprise_id'] . ""
                                . " AND  unit_type_id=" . $value['id'] . $query_resale_listing)//. $where_subSearch)
                        ->find_many();


                if (count($totUnit)) {
                    $records[$key]['total_unit'] = $totUnit[0]->total_unit;
                } else {
                    $records[$key]['total_unit'] = 0;
                }
                if (count($d) > 0) {
                    $records[$key]['min'] = $d[0]->min;
                    $records[$key]['max'] = $d[0]->max;
                    $records[$key]['avg'] = $d[0]->avg;
//                    $records[$key]['listing'] = $d[0]->listing;

                    $listPrice = explode(",", "," . $d[0]->crawler_price_str);
                    unset($listPrice[0]);
                    sort($listPrice);
                    if (count($listPrice) > 0) {
                        if (count($listPrice) % 2 == 1) {
                            $records[$key]['mediana'] = $listPrice[(count($listPrice) / 2) - 0.5];
                        } else {
                            $records[$key]['mediana'] = ($listPrice[(count($listPrice) / 2)] + $listPrice[(count($listPrice) / 2) - 1]) / 2;
                        }
                    } else {
                        $records[$key]['mediana'] = 0;
                    }
                } else {
                    $records[$key]['min'] = 0;
                    $records[$key]['max'] = 0;
                    $records[$key]['avg'] = 0;
//                    $records[$key]['listing'] = 0;
                    $records[$key]['total_unit'] = 0;
                    $records[$key]['mediana'] = 0;
                }


                if (!isset($filter['resale']) || $filter['resale'] != 1) {
                    $d1 = null;
                } else {
                    $d1 = ORM::for_table('module_imobles_listings')
                            ->raw_query("select count(id) as listing"
                                    . " from module_imobles_listings "
                                    . " where entreprise_id=" . $value['module_imobles_enterprise_id'] . "  AND advertiser_id IS NOT NULL "
                                    . " AND crawler_businessType = 'SALE' AND unit_type_id=" . $value['id'] . $where_subSearch)
                            ->find_many();
                }


                if ($d1 && count($d1) > 0) {
                    $records[$key]['listing'] = $d1[0]->listing;
                } else {
                    $records[$key]['listing'] = 0;
                }

                $iptu = ORM::for_table('module_imobles_enterprise_units_type')
                        ->raw_query(" select crawler_pricingInfos"
                                . " from module_imobles_listings "
                                . " where entreprise_id=" . $value['module_imobles_enterprise_id'] . "  "
                                . " AND unit_type_id=" . $value['id'] . " AND  crawler_pricingInfos LIKE '%yearlyIptu%'")
                        ->find_many();

                if (count($iptu) > 0) {
                    $num = 0;
                    $total = 0;
                    foreach ($iptu as $p) {
                        try {
                            $data = json_decode($p->crawler_pricingInfos, true);
                            if (isset($data[0]['yearlyIptu']) && $data[0]['yearlyIptu'] > 0) {
                                $total += $data[0]['yearlyIptu'];
                                $num++;
                            }
                        } catch (Exception $e) {
                            
                        }
                    }
                    if ($num > 0) {
                        $records[$key]['iptu'] = $total / $num;
                    } else {
                        $records[$key]['iptu'] = 0;
                    }
                } else {
                    $records[$key]['iptu'] = 0;
                }

                $row = array();
                if ($records[$key]['release_date']) {
                    if (strtotime($records[$key]['release_date']) >= strtotime(date("Y-m-d"))) {
                        $row['DT_RowClass'] = '';
                    } else {
                        $row['DT_RowClass'] = '';
                    }
                }

                //aqui busca as imagens
                $valueImages = '';
                if ($filter['showimages']) {
                    $images = ORM::for_table('module_imobles_enterprise_imgs')
                            ->table_alias("i")
                            ->select_expr('i.src,i.module_imobles_enterprise_id')
                            ->select_expr('i.listing_id')
                            ->where("i.duplicated", 0)->where('i.unit_type_id', $value['id'])
                            ->limit(10)
                            ->find_many();
                    if (count($images) == 0) {
                        $images = ORM::for_table('module_imobles_enterprise_imgs')
                                ->table_alias("i")
                                ->select_expr('i.src,i.module_imobles_enterprise_id')
                                ->select_expr('i.listing_id')
                                ->where("i.duplicated", 0)->where('i.module_imobles_enterprise_id', $value['module_imobles_enterprise_id'])
                                ->limit(10)
                                ->find_many();
                    }

                    if (count($images) > 0) {
                        $valueImages .= '<ul class="bxslider">';
                        foreach ($images as $im) {

                            $valueImages .= '   <li>
                                            <center>  <img   style="max-width:205px; max-height:150px"  src="' . APP_URL . '/application/plugins/module_imobles/uploads/enterprise/' . $im->module_imobles_enterprise_id . '/images/' . $im->src . '" /></center></li>';
                        }
                        $valueImages .= '</ul>';
                    }
                }



//              $row['DT_RowClass'] = class linha
                $row[] = "<input class='select_listing select_td' data-enterprise-id='" . $records[$key]['module_imobles_enterprise_id'] . "' value='" . $records[$key]['id'] . "' type='checkbox'>";

                if ($filter['showimages']) {
                    $row[] = $valueImages;
                }

                $row[] = '<div class="btn-group dropdown">
                                            <button class="btn btn-primary btn-xs dropdown-toggle"
                                                    data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                                                <i class="fa fa-cog"></i> <span class="caret"></span>
                                            </button>
                                            <ul class="dropdown-menu" aria-labelledby="dropdown-list">
                                                <li><a class="income-edit" data-id="" href="' . U . 'module_imobles/typeunity/view/' . $records[$key]['id'] . '"><i class="fa fa-eye"></i> ' . $this->_L['View'] . '</a></li>
                                                <li><a class="income-edit" data-id="' . $records[$key]['id'] . '" href="' . U . 'module_imobles/typeunity/edit/' . $records[$key]['id'] . '"><i class="fa fa-edit"></i> ' . $this->_L['Edit'] . " " . $this->_L['module imobles typeunity'] . '</a></li>
                                                <li><a class="income-edit" data-id="' . $records[$key]['id'] . '" href="' . U . 'module_imobles/docs/listAll/unit_type/' . $records[$key]['id'] . '"><i class="fa fa-file-archive-o"></i> ' . $this->_L['module imobles docs'] . " " . $this->_L['module imobles typeunity'] . '</a></li>
                                                <li><a class="income-edit" data-id="' . $records[$key]['id'] . '" href="' . U . 'module_imobles/enterprises/edit/' . $records[$key]['module_imobles_enterprise_id'] . '"><i class="fa fa-edit"></i> ' . $this->_L['Edit'] . " " . $this->_L['module imobles enterprise'] . '</a></li>
                                                <li><a class="income-edit" data-id="' . $records[$key]['module_imobles_enterprise_id'] . '" href="' . U . 'module_imobles/enterprises/images/backend/' . $records[$key]['module_imobles_enterprise_id'] . '"><i class="fa fa-file-archive-o"></i> ' . $this->_L['module imobles images Backend'] . " " . $this->_L['module imobles enterprise'] . '</a></li>
                                                <li><a class="income-edit" data-id="' . $records[$key]['module_imobles_enterprise_id'] . '" href="' . U . 'module_imobles/enterprises/images/listing/' . $records[$key]['module_imobles_enterprise_id'] . '"><i class="fa fa-file-archive-o"></i> ' . $this->_L['module imobles images Listing'] . " " . $this->_L['module imobles enterprise'] . '</a></li>
                                                <li><a class="income-edit" data-id="' . $records[$key]['module_imobles_enterprise_id'] . '" href="' . U . 'module_imobles/docs/listAll/enterprise/' . $records[$key]['module_imobles_enterprise_id'] . '"><i class="fa fa-file-archive-o"></i> ' . $this->_L['module imobles docs'] . " " . $this->_L['module imobles enterprise'] . '</a></li>
                                                <li><a class="delete_record" onclick="ConfirmDelete(' . $records[$key]['id'] . ')" href="#"><i class="fa fa-trash-o"></i>' . $this->_L['Delete'] . '</a></li>
                                            </ul>
                                        </div>';
                $row[] = $records[$key]['company_construction'];
                $row[] = "<a data-content='" . $records[$key]['enterprise_name'] . "<br/>"
                        . " " . $records[$key]['address_neightborhood'] . ", " . $records[$key]['address_log'] . ", " . $records[$key]['address_number']
                        . " " . ($records[$key]['google_phone'] != 'NULL' ? $records[$key]['google_phone'] . "<br/>" : "")
                        . " " . ($records[$key]['google_rating'] != 'NULL' ? $records[$key]['google_rating'] . "<br/>" : "")
                        . "'"
                        . " class='popoverDetail' href='" . U . "module_imobles/enterprises/view/" . $records[$key]['module_imobles_enterprise_id'] . "' target='_blank'>" . $records[$key]['enterprise_name'] . "</a>";

                $row[] = "" . $records[$key]['address_neightborhood'];
//                $row[] = "" . $records[$key]['address_log'] . ", " . $records[$key]['address_number'];
                //aqui consulta de amenities

                $amenities = ORM::for_table('module_imobles_enterprise_units_type')
                        ->raw_query("select sub.name from module_imobles_enterprise_units_type_amenities s
JOIN module_imobles_type_units_amenities sub on (s.module_imobles_type_units_amenities_id = sub.id)
Where s.module_imobles_enterprise_units_type_id=" . $records[$key]['id'] . "
union
select sub.name from module_imobles_enterprise_entreprise_amenities s
JOIN module_imobles_enterprise_amenities sub on (s.module_imobles_enterprise_amenities_id = sub.id)
Where s.module_imobles_enterprise_id=" . $records[$key]['module_imobles_enterprise_id'])
                        ->find_array();


                if (count($amenities) > 0) {
                    $text = "";
                    foreach ($amenities as $a) {
                        $text .= $a['name'] . "<br/>";
                    }
                    $row[] = "" . "<div class='popoverDetail' data-content='" . $text . "'>" . number_format($records[$key]['area'], 0, $this->config['dec_point'], $this->config['thousands_sep']) . "</div>";
                } else {
                    $row[] = "" . number_format($records[$key]['area'], 0, $this->config['dec_point'], $this->config['thousands_sep']);
                }



                $row[] = "" . $records[$key]['number_rooms'];
                $row[] = "" . $records[$key]['number_suite'];
                $row[] = "" . $records[$key]['number_bathroom'];
                $row[] = "" . $records[$key]['number_garage'];
                $row[] = "" . "<div class='popoverDetail' data-content='" . $this->_L['module imobles value (IPTU)'] .
                        ": R$ " . number_format($records[$key]['iptu'], 0, $this->config['dec_point'], $this->config['thousands_sep']) . '<br/>' .
                        'Valor Mínimo: R$ ' . number_format($records[$key]['min'], 0, $this->config['dec_point'], $this->config['thousands_sep']) . '<br/>' .
                        'Valor Médio: R$ ' . number_format($records[$key]['avg'], 0, $this->config['dec_point'], $this->config['thousands_sep']) . '<br/>' .
                        "Valor Máximo: R$ " . number_format($records[$key]['max'], 0, $this->config['dec_point'], $this->config['thousands_sep']) . "' >" .
                        "" . number_format($records[$key]['min'], 0, $this->config['dec_point'], $this->config['thousands_sep']) . "</div>";

                // M²
                $row[] = $records[$key]['area'] > 0 ? number_format($records[$key]['mediana'] / $records[$key]['area'], 0, $this->config['dec_point'], $this->config['thousands_sep']) : "--";

                if (empty($filter['resale']) || $filter['resale'] != 1) {
                    // Entrada
                    $row[] = number_format($records[$key]['min'] * ($records[$key]['value_input_porcentage']), 0, $this->config['dec_point'], $this->config['thousands_sep']);

                    // Parcela
                    $row[] = number_format($records[$key]['min'] * ($records[$key]['value_installment_porcentage']), 0, $this->config['dec_point'], $this->config['thousands_sep']);

                    // Captação
                    $row[] = number_format($records[$key]['min'] * ($records[$key]['value_founding_porcentage']), 0, $this->config['dec_point'], $this->config['thousands_sep']);

                    // Desconto Conhecido
                    $row[] = number_format($records[$key]['min'] * ($records[$key]['discount']), 0, $this->config['dec_point'], $this->config['thousands_sep']);
                }
                $showListing = true;
                if (isset($filter['resale']) && $filter['resale'] == 1) {
                    if (strtotime("+3 months", strtotime(date("Y-m-d"))) < strtotime($records[$key]['release_date'])) {
//                        $showListing = false;
                    }
                }
                if (isset($filter['resale']) && $filter['resale'] == 1) {
                    if ($showListing && $records[$key]['listing'] > 0) {
                        $row[] = "" . '<a href="#" data-id="' . $records[$key]['id'] . '" class="open_listing btn btn-warning"> ' . $records[$key]['listing'] . '</a>';
                    } else {
                        $row[] = '-';
                    }
                }

                // Se for RESALE não mostro a quantidade de UNIDADES
                if (isset($filter['resale']) && $filter['resale'] == 1) {
                    
                } else {
//                $row[] = "" . '<a href="' . U . 'module_imobles/unity/listAll/1/module_imobles_enterprise_id/' . $records[$key]['module_imobles_enterprise_id'] . '" target="_blank" class="btn btn-warning">' . $records[$key]['total_unit'] . '</a>';
                    $row[] = "" . '<span class="btn btn-warning">' . $records[$key]['total_unit'] . '</span>';
                }


                if ($records[$key]['release_date']) {
                    if (strtotime($records[$key]['release_date']) >= strtotime(date("Y-m-d"))) {
                        $class_releaseData = 'btn btn-danger';
                    } else {
                        $class_releaseData = 'btn btn-green';
                    }
                }

                $row[] = $records[$key]['release_date'] ? "<span class='" . $class_releaseData . "'>" . date($this->config['df'], strtotime($records[$key]['release_date'])) . "</span>" : "";

//                if (isset($filter['resale']) && $filter['resale'] == 1) {
//                    if ($records[$key]['listing'] > 0) {
//                        $output['aaData'][] = $row;
//                    }
//                } else {
                $output['aaData'][] = $row;
//                }
            }
        }

        echo json_encode($output);
    }

    public function search_map() {
        $where = '';
        if (isset($_SESSION['filter']['module_imobles/typeunity/search'])) {
            $filter = $_SESSION['filter']['module_imobles/typeunity/search'];
        } else {
            $filter = array();
        }
        extract($this->searchWhereJoin($filter));

        $sql = ' FROM module_imobles_enterprise_units_type e'
                . ' LEFT JOIN module_imobles_enterprise ent ON(ent.id=e.module_imobles_enterprise_id)'
                . " 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   e.delete_at  IS NULL  and ent.delete_at  IS NULL ' . $where;

        $paginator = new ModulePaginator('module_imobles_enterprise_units_type', "Select "
                . "distinct(ent.id) as id, ent.latitude, ent.longitude, DATE(tower.date_delivery) as date_delivery,"
                . "ent.name as enterprise_name,ent.address_log,ent.address_number,ent.address_neightborhood, ent.release_date"
                . $sql, array());

        $records = $paginator->setItemsPerPage('all')
                ->run();
        $marker = '';
        if (count($records) > 0) {
            $center = '';
            $data[0] = strtotime(date('Y-m-d'));
            $data[1] = strtotime("+ 12 months", $data[0]);
            $data[2] = strtotime("+ 24 months", $data[0]);

            foreach ($records as $r) {
                if (!empty($r['longitude']) && !empty($r['latitude'])) {
                    if (empty($center)) {
                        $center = '{lat: ' . $r['latitude'] . ', lng: ' . $r['longitude'] . '}';
                    }

                    //define a cor do mapa conforme a regra IMB-16
                    if (empty($r['date_delivery'])) {
                        $r['date_delivery_towers'] = $r['release_date'];
                    }
                    if (empty($r['date_delivery'])) {
                        $colormap = APP_URL . "/ui/theme/lrsys/img/map_blue.png";
                    } else {
                        if ($data[0] >= strtotime($r['date_delivery'])) {
                            $colormap = APP_URL . "/ui/theme/lrsys/img/map_green.png";
                        } else if ($data[1] >= strtotime($r['date_delivery'])) {
                            $colormap = APP_URL . "/ui/theme/lrsys/img/map_blue.png";
                        } else if ($data[2] >= strtotime($r['date_delivery'])) {
                            $colormap = APP_URL . "/ui/theme/lrsys/img/map_yellow.png";
                        } else {
                            $colormap = APP_URL . "/ui/theme/lrsys/img/map_red.png";
                        }
                    }

                    $marker .= "
            mark" . $r['id'] . " = new google.maps.Marker({
                position: {lat: " . $r['latitude'] . ", lng: " . $r['longitude'] . "},
                map,
             icon:'" . $colormap . "',
                title:'" . str_replace("'", "\'", ($r['enterprise_name'])) . "',
            });
            mark" . $r['id'] . ".addListener('click', () => {
                new google.maps.InfoWindow({
                    content: '<div id=\"content\">' +
          '<div id=\"siteNotice\">' +
          '</div>' +
          '<div id=\"bodyContent\">' +
          '<p>" . str_replace("'", "\'", ($r['enterprise_name'])) . "</p>' +
          '</div>' +
          '</div>'
                }).open(map, mark" . $r['id'] . ");
            });
            ";
                }
            }
        }

        if (empty($center)) {
            $center = '{lat: -16.69254875183105, lng: -49.26187896728516}';
        }
        $this->ui->assign('centerMarker', $center);
        $this->ui->assign('marker', $marker);
        $this->ui->assign('_include', 'typeunitys/search_map');
        $this->ui->display('wrapper_clean.tpl');
    }

    public function postGroupByEnterprise() {

        if (empty(_post('id_father')) || !is_numeric(_post('id_father'))) {
            die($this->_L['Id_Required']);
        }
        $idPai = _post('id_father');
        $id = $_POST['id'];

        if ($idPai == -1) {
            $idPai = _post('other_id');
        }
        $cr = new CrawlerController($this->ui, $this->_L, $this->_pd, $this->config);
        foreach ($id as $i) {
            if ($i != $idPai) {
                $cr->mergeEnterprises($idPai, $i, 'manual');
            }
        }
        if ($this->routes[3] == 1) {
            _notify($this->_L['module imobles group successfull'], 's');
        }
    }

    public function viewReviewListing() {
        $enterprise = ORM::for_table('module_imobles_enterprise')
                ->table_alias("e")
                ->select_expr("e.address_number,e.address_log,e.address_neightborhood,e.name,e.id,c.city_name")
                ->left_outer_join('city', 'address_city_id = c.id', 'c')
                ->where_in('e.id', $_POST['id'])
                ->where_null('e.delete_at')
                ->order_by_asc('e.name')
                ->find_many();
        $this->ui->assign('enterprises', $enterprise);

        $othersEnterprise = ORM::for_table('module_imobles_enterprise')
                ->table_alias("e")
                ->select_expr("e.address_number,e.address_log,e.address_neightborhood,e.name,e.id")
                ->where_not_in('e.id', $_POST['id'])
                ->where_null('delete_at')
                ->where_raw('(e.verified=1 OR e.google_place_id IS NOT NULL OR e.crawler_enterprise_id IS NOT NULL)')
                ->order_by_asc('e.name')
                ->find_many();

        $this->ui->assign('othersEnterprise', $othersEnterprise);
        $this->ui->assign('_include', 'typeunitys/group/review_listing');
        $this->ui->display('wrapper_clean.tpl');
    }

    public function viewGroupByEnterprise() {
        $enterprise = ORM::for_table('module_imobles_enterprise')
                ->table_alias("e")
                ->select_expr("e.address_number,e.address_log,e.address_neightborhood,e.name,e.id,c.city_name")
                ->left_outer_join('city', 'address_city_id = c.id', 'c')
                ->where_in('e.id', $_POST['id'])
                ->where_null('e.delete_at')
                ->order_by_asc('e.name')
                ->find_many();
        $this->ui->assign('enterprises', $enterprise);

        $othersEnterprise = ORM::for_table('module_imobles_enterprise')
                ->table_alias("e")
                ->select_expr("e.address_number,e.address_log,e.address_neightborhood,e.name,e.id")
                ->where_not_in('e.id', $_POST['id'])
                ->where_null('delete_at')
                ->where_raw('(e.verified=1 OR e.google_place_id IS NOT NULL OR e.crawler_enterprise_id IS NOT NULL)')
                ->order_by_asc('e.name')
                ->find_many();

        $this->ui->assign('othersEnterprise', $othersEnterprise);
        $this->ui->assign('_include', 'typeunitys/group/enterprise');
        $this->ui->display('wrapper_clean.tpl');
    }

    public function postGroupByTypeUnity() {
        if (empty(_post('id_father')) || !is_numeric(_post('id_father'))) {
            die($this->_L['Id_Required']);
        }
        $idPai = _post('id_father');
        $id = $_POST['id'];

        if ($idPai == -1) {
            $idPai = _post('other_id');
        }

        $typeunitPai = $this->model->getOne($idPai);

        if (!$typeunitPai) {
            die($this->_L['Not_Found']);
        }
        foreach ($id as $i) {
            if ($i != $idPai) {
                $typeunit = $this->model->getOne($i);
                if ($typeunit->module_imobles_enterprise_id == $typeunitPai->module_imobles_enterprise_id) {

                    //GARANTE QUE É MESMO EMPREENDIMENTO
                    ORM::execute("UPDATE module_imobles_enterprise_units set module_imobles_enterprise_units_type_id=" . $typeunitPai->id . " where id>=1 and module_imobles_enterprise_units_type_id=" . $i);
                    ORM::execute("UPDATE module_imobles_docs set module_imobles_enterprise_units_type_id=" . $typeunitPai->id . " where id>=1 and module_imobles_enterprise_units_type_id=" . $i);
                    ORM::execute("UPDATE module_imobles_enterprise_imgs set unit_type_id=" . $typeunitPai->id . " where id>=1 and unit_type_id=" . $i);
                    ORM::execute("UPDATE module_imobles_listings set unit_type_id=" . $typeunitPai->id . " where id>=1 and unit_type_id=" . $i);
                    $this->model->deleteTypeunity($typeunit);
                }
            }
        }

        if ($this->routes[3] == 1) {
            _notify($this->_L['module imobles group successfull'], 's');
        }
    }

    public function viewGroupByTypeUnity() {

        $typeUNit = ORM::for_table('module_imobles_enterprise_units_type')
                ->table_alias("e")
                ->select_expr("e.verified,e.crawler_type_id,e.id,ent.name as enterprise_name, e.module_imobles_enterprise_id, e.title, e.area, e.number_rooms, e.number_suite, e.number_bathroom, e.number_garage ")
                ->left_outer_join('module_imobles_enterprise', 'ent.id = e.module_imobles_enterprise_id', 'ent')
                ->where_in('e.id', $_POST['id'])
                ->where_null('e.delete_at')
                ->where_null('ent.delete_at')
                ->order_by_asc('e.title')
                ->find_many();
        $ent = 0;
        $showAllType = 1;
        if (count($typeUNit) > 0) {
            $enterprise = array();
            foreach ($typeUNit as $key => $t) {
                if ($t->verified == 1 OR $t->crawler_type_id == 4) {
                    $typeUNit[$key]->showOption = 1;
                    $showAllType = 0;
                } else {
                    $typeUNit[$key]->showOption = 0;
                }
                $ent = $t->module_imobles_enterprise_id;
                $enterprise[$t->module_imobles_enterprise_id] = $t->module_imobles_enterprise_id;
            }
        }
        if (count($enterprise) == 1) {
            $this->ui->assign('typeunitys', $typeUNit);
            $this->ui->assign('showAllType', $showAllType);
            $othersType = ORM::for_table('module_imobles_enterprise_units_type')
                    ->table_alias("e")
                    ->select_expr("e.title, e.id")
                    ->where("module_imobles_enterprise_id", $ent)
                    ->where_not_in('e.id', $_POST['id'])
                    ->where_null('delete_at')
                    ->order_by_asc('e.title')
                    ->find_many();
            $this->ui->assign('showNotification', false);

            $this->ui->assign('otherstypeunity', $othersType);
        } else {
            $this->ui->assign('showNotification', true);
        }
        $this->ui->assign('_include', 'typeunitys/group/typeUnity');
        $this->ui->display('wrapper_clean.tpl');
    }

    public function postSendTypeUnity() {

        $data = $_POST;
        $msg = '';
        if (empty(_post('id_account_add')) && empty(_post('id_account'))) {
            $msg .= $this->_L['Client'] . $this->_L['is required'];
        }

        if (empty(_post('type_send'))) {
            $msg .= $this->_L['module imobles type send'] . $this->_L['is required'];
        }
        if (empty($_POST['id'])) {
            $msg .= $this->_L['module imobles select one typenity'] . "<br/>";
        }

        if (empty($msg)) {
            $idAccount = "";
            if (!empty(_post('id_account'))) {
                $idAccount = _post('id_account');
            } else {
                $idAccount = _post('id_account_add');
            }
            $account = ORM::for_table('crm_accounts')->find_one($idAccount);

            //BUSCA OS TIPOS DE UNIDADES
//   $idAccount = 2;
//            $_POST['id'] = array(59,60,71,62);
            $sql = "Select "
                    . " e.title, e.number_rooms,e.number_bathroom, e.area, e.number_suite, e.number_garage, e.id, e.module_imobles_enterprise_id, "
                    . " ent.name as enterprise_name,ent.link_hotsite, ent.link_presentation ,ent.release_date, ent.address_log, ent.address_number, ent.address_neightborhood,"
                    . " DATE(tower.date_delivery) as date_delivery"
                    . ' FROM module_imobles_enterprise_units_type e'
                    . ' LEFT JOIN module_imobles_enterprise ent ON(ent.id=e.module_imobles_enterprise_id)'
                    . " 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 )"
                    . "  WHERE e.delete_at IS NULL and ent.delete_at IS NULL and e.id in( '" . implode("','", $_POST['id']) . "')";

            $records = ORM::for_table('module_imobles_enterprise_units_type')
                    ->raw_query($sql)
                    ->find_many();
            $description = "";
            if (count($records) > 0) {

                foreach ($records as $key => $value) {

                    if (!empty($value['date_delivery'])) {
                        $records[$key]['release_date'] = $value['date_delivery'];
                    }


                    $query_resale_listing = null;
                    $query_resale_unit = null;
                    if (!isset($filter['resale']) || $filter['resale'] != 1) {
                        $query_resale_listing = " AND crawler_type_id = 4 ";
                        $query_resale_unit = " AND sub.crawler_type_id = 4 ";
                    }
                    $d = ORM::for_table('module_imobles_enterprise_units_type')
                            ->raw_query(" select min(crawler_price) as min,"
                                    . " max(crawler_price) as max,"
                                    . " avg(crawler_price) as avg , "
                                    . " count(crawler_price) as listing,"
                                    . " (select count(sub.id) from module_imobles_enterprise_units "
                                    . "sub where sub.module_imobles_enterprise_units_type_id=" . $value['id'] . $query_resale_unit . ") as total_unit"
                                    . " from module_imobles_listings "
                                    . " where unavailable IS NULL AND entreprise_id=" . $value['module_imobles_enterprise_id'] . ""
                                    . " AND unit_type_id=" . $value['id'] . $query_resale_listing)
                            ->find_many();

                    if (count($d) > 0) {
                        if ($d[0]->min > 100000 && $d[0]->min < 1000000) {
                            $records[$key]['min_desc'] = $this->config['currency_code'] . " " . number_format($d[0]->min / 1000, 0) . " Mil";
                        } else {
                            $records[$key]['min_desc'] = $this->config['currency_code'] . " " . number_format($d[0]->min / 1000000, 2, $this->config['dec_point'], $this->config['thousands_sep']) . " Milhões";
                        }
                        $records[$key]['min'] = $d[0]->min;
                        $records[$key]['max'] = $d[0]->max;
                        $records[$key]['avg'] = $d[0]->avg;
                        $records[$key]['total_unit'] = $d[0]->total_unit;
                    } else {
                        $records[$key]['min_desc'] = "";
                        $records[$key]['min'] = 0;
                        $records[$key]['max'] = 0;
                        $records[$key]['avg'] = 0;
                        $records[$key]['total_unit'] = 0;
                    }

                    $c = ORM::for_table('module_imobles_enterprise_imgs')
                            ->table_alias('s')
                            ->select("s.*")
                            ->where('s.module_imobles_enterprise_id', $value['module_imobles_enterprise_id'])
                            ->where('s.type', 'backend')
                            ->where_raw('s.delete_at IS NULL')
                            ->find_many();

                    $tags = ORM::for_table('module_imobles_enterprise_img_backend_tags')
                            ->table_alias('s')
                            ->where_raw(" upper(name)='LOGO' ||  upper(name)='CAPA'")
                            ->find_many();
                    if (count($tags) > 0) {
                        $arrayTag = array();
                        foreach ($tags as $t) {
                            $arrayTag[$t->id] = $t->name;
                        }

                        foreach ($c as $im) {
                            try {
                                $tagsIm = json_decode($im->tags);
                                if ($tagsIm) {
                                    foreach ($tagsIm as $t) {
                                        if (isset($arrayTag[$t])) {
                                            $records[$key][strtoupper($arrayTag[$t])] = $im;
                                        }
                                    }
                                }
                            } catch (Exception $e) {
                                
                            }
                        }
                    }

                    $description .= "<br/>" . $records[$key]['enterprise_name'] . " | " . $records[$key]['title'] . " | Valor Médio de " . $this->config['currency_code'] . " " . number_format($records[$key]['avg'], 2, $this->config['dec_point'], $this->config['thousands_sep']);
                }
                //FAZER PDF
                define('_MPDF_PATH', 'application/lib/mpdf/');

                require('application/lib/mpdf/mpdf.php');

                $pdf_c = '';
                $ib_w_font = 'dejavusanscondensed';
                if ($config['pdf_font'] == 'default') {
                    $pdf_c = 'c';
                    $ib_w_font = 'Helvetica';
                }

                //
                $mpdf = new mPDF($pdf_c, 'IMOBLES_PROPOST', '14', '', 0, 0, 0, 0, 0, 0);
                //            $mpdf->SetProtection(array('print'));
                $mpdf->SetTitle($config['CompanyName']);
                $mpdf->SetAuthor($config['CompanyName']);
//            $mpdf->SetWatermarkText(ib_lan_get_line($d['status']));
//            $mpdf->showWatermarkText = true;
//            $mpdf->watermark_font = $ib_w_font;
//            $mpdf->watermarkTextAlpha = 0.1;
                $mpdf->SetDisplayMode('fullpage');
                $config = $this->config;
                $_L = $this->_L;
                if ($config['pdf_font'] == 'AdobeCJK') {
                    $mpdf->useAdobeCJK = true;
                    $mpdf->autoScriptToLang = true;
                    $mpdf->autoLangToFont = true;
                }
                $meses = array("Jan" => 'Janeiro',
                    'Feb' => 'Fevereiro',
                    'Mar' => 'Março',
                    'Apr' => 'Abril',
                    'Mai' => 'Maio',
                    'Jun' => 'Junho',
                    'Jul' => 'Julho',
                    'Sep' => 'Setembro',
                    'Oct' => 'Outubro',
                    'Nov' => 'Novembro',
                    'Dec' => 'Dezembro',
                );
                $pdf_tpl = 'application/plugins/module_imobles/assets/libs/propost.php';

                ob_start();

                require $pdf_tpl;

                $html = ob_get_contents();


                ob_end_clean();


                $mpdf->WriteHTML($html);


//            if ($r_type == 'dl') {
//                $mpdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'D'); # D
//            } elseif ($r_type == 'inline') {
                $mpdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'I'); # D
                die();
//            } elseif ($r_type == 'store') {
                $path = 'application/plugins/module_imobles/uploads/temp/';
                if (!is_dir($path)) {
                    mkdir($path, 0755, $recursive = true);
                }
                $file = $path . "imobles_sugestoes_" . $idAccount . date("d_m_Y_H_i_s") . '.pdf';
                $mpdf->Output($file, 'F');
//              } else {
//                $mpdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'I'); # D
//            }
            }
        } else {
            //ERRO
            echo json_encode(array("status" => 'ERROR',
                'msg' => $msg));
            exit();
        }


        //montar PDF AQUI DOS ITENS SELECIONADOS
        switch (_post('type_send')) {
            case 'store':
                // Registro uma atividade para o cliente
                $unit_type_ids = implode(',', $_POST['id']);
                $link_msg = "<br/><br/><a href='?ng=module_imobles/typeunity/search/unit_type_ids=" . $unit_type_ids . "' target='_blank'>VER RESULTADO DA PESQUISA NO BUSCADOR</a>";
                $user = User::_info();
                $d = ORM::for_table('sys_activity')->create();
                $d->cid = $idAccount;
                $d->msg = "Proposta gerada para apresentação posterior:<br/>" . $description . $link_msg;
                $d->icon = "fa fa-envelope";
                $d->stime = time();
                $d->sdate = date('Y-m-d');
                $d->o = $user->id;
                $d->oname = $user->fullname;
                $d->save();

                echo json_encode(array("status" => 'REDIRECT',
                    'msg' => 'PDF GERADO',
                    'href' => $file));
                exit();
                break;
            case 'email':
                if (empty($account['email'])) {
                    echo json_encode(array("status" => 'ERROR',
                        'msg' => 'Cliente sem informação no e-mail'));
                    exit();
                }

                if (Validator::Email($account['email']) == false) {
                    echo json_encode(array("status" => 'ERROR',
                        'msg' => 'Cliente com e-mail inválido'));
                    exit();
                }

                Notify_Email::_send($account['account'], $account['email'], $this->_L['module imobles email propost subject'], $this->_L['module imobles email propost message'], 0, 0, '', '', $file, "proposta.pdf");

                $user = User::_info();
                $d = ORM::for_table('sys_activity')->create();
                $d->cid = $idAccount;
                $d->msg = "Proposta enviada por e-mail para as opções abaixo<br/>" . $description;
                $d->icon = "fa fa-envelope";
                $d->stime = time();
                $d->sdate = date('Y-m-d');
                $d->o = $user->id;
                $d->oname = $user->fullname;
                $d->save();

                echo json_encode(array("status" => 'OK',
                    'msg' => 'E-mail enviado com sucesso '));
                break;
            case 'whatsapp':
                if (empty($account['cell_phone'])) {
                    echo json_encode(array("status" => 'ERROR',
                        'msg' => 'Cliente sem informação de celular'));
                    exit();
                }
                $cr = new CrawlerController($this->ui, $this->_L, $this->_pd, $this->config);
                //chama a função e manda o $file;
                if ($cr->sendProposal("55" . preg_replace('/\D/', '', $account['cell_phone']), $file)
                ) {
                    $user = User::_info();
                    $d = ORM::for_table('sys_activity')->create();
                    $d->cid = $idAccount;
                    $d->msg = "Proposta enviada por Whatsapp para as opções abaixo<br/>" . $description;
                    $d->icon = "fa fa-whatsapp";
                    $d->stime = time();
                    $d->sdate = date('Y-m-d');
                    $d->o = $user->id;
                    $d->oname = $user->fullname;
                    $d->save();


                    echo json_encode(array("status" => 'OK',
                        'msg' => 'E-mail enviado com sucesso'));
                } else {
                    echo json_encode(array("status" => 'ERROR',
                        'msg' => 'Erro ao enviar por whatsapp'));
                }
                break;
        }
    }

    public function viewSendPdfClient() {

        $typeUNit = ORM::for_table('module_imobles_enterprise_units_type')
                ->table_alias("e")
                ->select_expr("e.id,ent.name as enterprise_name, e.module_imobles_enterprise_id, e.title, e.area, e.number_rooms, e.number_suite, e.number_bathroom, e.number_garage ")
                ->left_outer_join('module_imobles_enterprise', 'ent.id = e.module_imobles_enterprise_id', 'ent')
                ->where_in('e.id', $_POST['id'])
                ->where_null('e.delete_at')
                ->where_null('ent.delete_at')
                ->order_by_asc('e.title')
                ->find_many();
        $this->ui->assign('typeunitys', $typeUNit);
        $this->ui->assign('_include', 'typeunitys/send/select_client');
        $this->ui->display('wrapper_clean.tpl');
    }

    public function data_listing() {
        $id = $this->routes[3];

        if (empty($this->routes[3]) || !is_numeric($this->routes[3])) {
            die($this->_L['Id_Required']);
        }


        $listingS = ORM::for_table('module_imobles_listings')
                ->table_alias("l")
                ->select_expr('(select count(sub.id) from module_imobles_listings sub where sub.unavailable IS NULL AND sub.advertiser_id=s.id) as total_listing')
                ->select_expr("s.name, s.phones, s.licenseNumber, s.websiteUrl, s.crawler_createdDate ")
                ->select_expr("e.name as enterprise_name, l.title, l.description, l.id, l.unit_type_id, l.crawler_listing_id, l.crawler_price,l.crawler_createdAt,l.crawler_updatedAt,l.crawler_whatsappNumber")
                ->where('l.unit_type_id', $id)
                ->where('l.crawler_businessType', 'SALE')
                ->where_not_null('l.advertiser_id')
                ->where_null('l.delete_at')
                ->where_null('l.unavailable')
                ->join('module_imobles_enterprise', 'e.id = l.entreprise_id', 'e')
                ->left_outer_join('module_imobles_advertisers', 's.id = l.advertiser_id', 's')
                ->order_by_desc('l.crawler_updatedAt');

        if (isset($_SESSION['filter']['module_imobles/typeunity/search'])) {
            $filter = $_SESSION['filter']['module_imobles/typeunity/search'];
        } else {
            $filter = array();
        }
        if (!empty(@$filter['search'])) {
            $arrstring = explode(",", $filter['search']);
            $string = implode("\"'  '\"", $arrstring);
            $string = "'\"" . $string . "\"'";

            $listingS->where_raw(
                    "MATCH(title, description, crawler_externalId)
                        AGAINST(" . $string . " IN BOOLEAN MODE) AND advertiser_id IS NOT NULL ");
        }

        $listing = $listingS->find_many();
        if ($listing) {
          
            foreach ($listing as $key => $val) {
                try {

//busca as imagens do anúncio
                    $listing[$key]->images = ORM::for_table('module_imobles_enterprise_imgs')
                            ->table_alias("i")
                            ->select_expr('i.src,i.module_imobles_enterprise_id')
                            ->select_expr('i.listing_id')
                            ->where("i.duplicated", 0)->where('i.listing_id', $val->id)
                            ->limit(10)
                            ->find_many();


                    $json = json_decode($val->phones);
                    if ($val->crawler_price > 100000 && $val->crawler_price < 1000000) {
                        $listing[$key]->crawler_price_desc = $this->config['currency_code'] . " " . number_format($val->crawler_price / 1000, 0) . "K";
                    } else {
                        $listing[$key]->crawler_price_desc = $this->config['currency_code'] . " " . number_format($val->crawler_price / 1000000, 1, ".", "") . "M";
                    }

                    $listing[$key]->mobile = mask($json->mobile, strlen($json->mobile) == 11 ? "(##) # ####-####" : "(##) #############");
                    $listing[$key]->primary = mask($json->primary, strlen($json->primary) == 11 ? "(##) # ####-####" : "(##) #############");
                    $listing[$key]->phones_desc = '<i class="fa fa-mobile"></i> &nbsp;' . $listing[$key]->mobile . "<br/>" . '<i class="fa fa-phone"></i> ' . $listing[$key]->primary;

                    $msgs = ORM::for_table('module_imobles_mandeumzap_listings')
                            ->table_alias("i")
                            ->join('sys_users', 'i.user_id = u.id', 'u')
                            ->select_expr('i.send_at, u.fullname as name')
                            ->where('i.listing_id', $val->id)
                            ->find_many();
                    if (count($msgs) > 0) {
                        $text = "";
                        foreach ($msgs as $m) {
                            $text .= date($this->config['df'] . " H:i:s", strtotime($m->send_at)) . " - " . $m->name . "<br/>";
                        }
                        $listing[$key]->msg_content = $text;
                        $listing[$key]->msg_total = count($msgs);
                    } else {
                        $listing[$key]->msg_content = "";
                        $listing[$key]->msg_total = 0;
                    }
                } catch (Exception $e) {
                    var_dump($e);
                }
            }
        }

        $this->ui->assign('listing', $listing);
        $this->ui->assign('_include', 'typeunitys/listing');
        $this->ui->display('wrapper_clean.tpl');
    }

    public function add() {
        // CARREGA CSS E JS'S
        $css_arr = array('s2/css/select2.min', 'dp/dist/datepicker.min',
            'ibilling/clockpicker/clockpicker', 'dropzone/dropzone', 'modal');

        $js_arr = array('modal',
            'dp/dist/datepicker.min',
            '/../../theme/lrsys/lib/jquery.maskMoney.min',
            'ibilling/clockpicker/clockpicker',
            's2/js/select2.min', 's2/js/i18n/' . lan(), 'dropzone/dropzone',
            '/../../../application/plugins/module_imobles/assets/js/typeunity-form',
        );
//
        $assets_css = Asset::css($css_arr, "5");
        $assets_js = Asset::js($js_arr, "5");
        $this->ui->assign('xheader', $assets_css);
        $this->ui->assign('xfooter', $assets_js);
        $this->ui->assign('xfooter', $assets_js);
        $this->ui->assign('rowNumTowers', 0);
        $this->ui->assign('typeunityTorers', array());



        $user = User::_info();

        $attach = ORM::for_table('module_imobles_enterprise_units_type_plant')->where('user_id', $user->id)->where_null('module_imobles_enterprise_units_type_id')->find_many();

        $att = "";
        $attachs = "";
        if (count($attach) > 0) {

            foreach ($attach as $i) {
                //temporario 100 o tamanho
                $att .= ' {id:"' . $i->id . '", name: "' . $i->name . '", size: 100,url:"' . APP_URL . '/application/plugins/module_imobles/uploads/typeunity/' . $i->src . '" },';
                $attachs .= "," . $i->id;
            }
        } else {
            $att = "";
        }
        $this->ui->assign('attachs', substr($attachs, 1));

        $this->ui->assign('jsvar', '
        _L[\'are_you_sure\'] = \'' . $this->_L['are_you_sure'] . '\';
        _L[\'Save\'] = \'' . $this->_L['Save'] . '\';
        _L[\'OK\'] = \'' . $this->_L['OK'] . '\';
        _L[\'Remove\'] = \'' . $this->_L['Remove'] . '\';
        _L[\'Cancel\'] = \'' . $this->_L['Cancel'] . '\';
        _L[\'Select\'] = \'' . $this->_L['Select'] . '\'; 
   _L[\'View\'] = \'' . $this->_L['View'] . '\'; 
        _L[\'module_imobles Delete Attach?\'] = \'' . $this->_L['module imobles Delete Image?'] . '\';

        var existingFiles = [' . $att . '
        ];
       ');

        //CARREGA A LISTA DE estados
        $e = ORM::for_table('state')->order_by_asc('state_name')->find_many();
        $this->ui->assign('state', $e);

        $this->ui->assign('typeunitys', json_decode(json_encode(array(
            "title" => "",
            "alias" => "",
            "desc" => "",
            "hobbox" => "0",
            "garage_drawer" => "0",
            "promotion" => "0",
            "roof" => "0",
            "area" => "",
            "number_rooms" => "",
            "number_suite" => "",
            "number_bathroom" => "",
            "number_toilet" => "",
            "number_garage" => "",
            "link_table_disponible" => "",
            "duplex" => "0",
            "link_plant" => "",
            "varanda" => "",
            "sacada" => "",
            "status_wordpress" => "",
            "garages_cheaper_plant" => "",
            "comparator_status" => "",
            "table_disponible" => "",
            'link_capa_comparator' => "",
            "showimages" => "0",
            "resale" => "0"
        ))));


        $this->ui->assign('typeForm', 'window');

        $this->ui->assign('_st', $this->_L['module imobles typeunity']);
        $this->ui->assign('_include', 'typeunitys/add');
        $this->ui->display('wrapper.tpl');
    }

    /**
     * Insert add to status diary
     */
    public function post() {
        try {
            $data = $_POST;
            $msg = '';
            if (empty(_post('title'))) {
                $msg .= $this->_L['module imobles typeunity title'] . $this->_L['is required'];
            }
            if (empty(_post('alias'))) {
                $msg .= $this->_L['module imobles typeunity alias'] . $this->_L['is required'];
            }
//            if (empty(_post('desc'))) {
//                $msg .= $this->_L['Description'] . $this->_L['is required'];
//            }

            if (empty($msg)) {

                if (isset($data['id']) && $data['id'] > 0) {
                    $typeunitys = $this->model->getOne($data['id']);
                    $typeunitys = $this->model->updateTypeunity($data, $typeunitys);
                    _notify($this->_L['module imobles typeunity'] . " " . $this->_L['Edited Successfull'], 's');
                } else {
                    $typeunitys = $this->model->createTypeunity($data);
                    _notify($this->_L['module imobles typeunity'] . " " . $this->_L['Add Successfull'], 's');
                }
                $msg = "OK";
            }
        } catch (Exception $ex) {
            echo ($ex->getMessage());
        }
        echo $msg;
    }

    /**
     * Show form to edit status exam
     */
    public function edit() {
        $this->id = $this->routes[3];

        if (empty($this->routes[3]) || !is_numeric($this->routes[3])) {
            die($this->_L['Id_Required']);
        }

        $typeunitys = $this->model->getOne($this->routes[3]);

        if (!$typeunitys) {
            die($this->_L['Not_Found']);
        }

        $css_arr = array('s2/css/select2.min', 'dp/dist/datepicker.min',
            'ibilling/clockpicker/clockpicker', 'dropzone/dropzone', 'modal');

        $js_arr = array('modal',
            'dp/dist/datepicker.min',
            '/../../theme/lrsys/lib/jquery.maskMoney.min',
            'ibilling/clockpicker/clockpicker',
            's2/js/select2.min', 's2/js/i18n/' . lan(), 'dropzone/dropzone',
            '/../../../application/plugins/module_imobles/assets/js/typeunity-form',
        );
//
        $assets_css = Asset::css($css_arr, '5');
        $assets_js = Asset::js($js_arr, '5');
        $this->ui->assign('xheader', $assets_css);
        $this->ui->assign('xfooter', $assets_js);


        $this->ui->assign('typeunitys', $typeunitys);




        //

        $c = ORM::for_table('module_imobles_enterprise_units_type_amenities')
                ->table_alias('s')
                ->select("sub.*")
                ->join('module_imobles_type_units_amenities', 's.module_imobles_type_units_amenities_id = sub.id', 'sub')
                ->where('s.module_imobles_enterprise_units_type_id', $typeunitys->id)
                ->find_many();

        $this->ui->assign('module_imobles_enterprise_units_type_amenities', $c);




        $enterprise = new EnterprisesModel();
        $c = $enterprise->getOne($typeunitys->module_imobles_enterprise_id);

        if ($c) {
            $this->ui->assign('module_imobles_enterprise', $c);
        }

        $typeunityModel = new Enterprise_standardModel();
        $c = $typeunityModel->getOne($typeunitys->module_imobles_enterprise_units_type_standard_id);
        if ($c) {
            $this->ui->assign('module_imobles_enterprise_units_type_standard', $c);
        }

        $attach = ORM::for_table('module_imobles_enterprise_units_type_plant')->where('module_imobles_enterprise_units_type_id', $typeunitys->id)->find_many();

        $att = "";
        $attachs = "";
        if (count($attach) > 0) {

            foreach ($attach as $i) {
                //temporario 100 o tamanho
                $att .= ' {id:"' . $i->id . '", name: "' . $i->name . '", size: 100,url:"' . APP_URL . '/application/plugins/module_imobles/uploads/typeunity/' . $i->src . '" },';
                $attachs .= "," . $i->id;
            }
        } else {
            $att = "";
        }
        $this->ui->assign('attachs', substr($attachs, 1));

        $this->ui->assign('jsvar', '
        _L[\'are_you_sure\'] = \'' . $this->_L['are_you_sure'] . '\';
        _L[\'Save\'] = \'' . $this->_L['Save'] . '\';
        _L[\'OK\'] = \'' . $this->_L['OK'] . '\';
        _L[\'Remove\'] = \'' . $this->_L['Remove'] . '\';
        _L[\'Cancel\'] = \'' . $this->_L['Cancel'] . '\';
        _L[\'Select\'] = \'' . $this->_L['Select'] . '\'; 
   _L[\'View\'] = \'' . $this->_L['View'] . '\'; 
        _L[\'module_imobles Delete Attach?\'] = \'' . $this->_L['module imobles Delete Image?'] . '\';

        var existingFiles = [' . $att . '
        ];
       ');
        //CARREGA A LISTA DE estados
        $e = ORM::for_table('state')->order_by_asc('state_name')->find_many();
        $this->ui->assign('state', $e);
        $this->ui->assign('typeForm', 'window');

        $this->ui->assign('_include', 'typeunitys/add');
        $this->ui->display('wrapper.tpl');
    }

    /**
     * Show form to edit status exam
     */
    public function view() {
        $this->id = $this->routes[3];

        if (empty($this->routes[3]) || !is_numeric($this->routes[3])) {
            die($this->_L['Id_Required']);
        }

        $typeunitys = $this->model->getOne($this->routes[3]);

        if (!$typeunitys) {
            die($this->_L['Not_Found']);
        }

        $css_arr = array('s2/css/select2.min', 'dp/dist/datepicker.min',
            'ibilling/clockpicker/clockpicker', 'dropzone/dropzone', 'modal');

        $js_arr = array('modal',
            'dp/dist/datepicker.min',
            '/../../theme/lrsys/lib/jquery.maskMoney.min',
            'ibilling/clockpicker/clockpicker',
            's2/js/select2.min', 's2/js/i18n/' . lan(), 'dropzone/dropzone',
            '/../../../application/plugins/module_imobles/assets/js/typeunity-view',
        );
//
        $assets_css = Asset::css($css_arr);
        $assets_js = Asset::js($js_arr);
        $this->ui->assign('xheader', $assets_css);
        $this->ui->assign('xfooter', $assets_js);


        $this->ui->assign('typeunitys', $typeunitys);




        //

        $c = ORM::for_table('module_imobles_enterprise_units_type_amenities')
                ->table_alias('s')
                ->select("sub.*")
                ->join('module_imobles_type_units_amenities', 's.module_imobles_type_units_amenities_id = sub.id', 'sub')
                ->where('s.module_imobles_enterprise_units_type_id', $typeunitys->id)
                ->find_many();

        $this->ui->assign('module_imobles_enterprise_units_type_amenities', $c);




        $enterprise = new EnterprisesModel();
        $c = $enterprise->getOne($typeunitys->module_imobles_enterprise_id);

        if ($c) {
            $this->ui->assign('module_imobles_enterprise', $c);
        }

        $typeunityModel = new Enterprise_standardModel();
        $c = $typeunityModel->getOne($typeunitys->module_imobles_enterprise_units_type_standard_id);
        if ($c) {
            $this->ui->assign('module_imobles_enterprise_units_type_standard', $c);
        }

        $attach = ORM::for_table('module_imobles_enterprise_units_type_plant')->where('module_imobles_enterprise_units_type_id', $typeunitys->id)->find_many();

        $this->ui->assign('attachs', $attach);

        $this->ui->assign('typeForm', 'window');

        $this->ui->assign('_include', 'typeunitys/view');
        $this->ui->display('wrapper.tpl');
    }

    public function delete() {
        $status = $this->model->getOne(_post('id'));
        $this->model->deleteTypeunity($status);
        r2(U . 'module_imobles/typeunity/listall', 's', $this->_L['delete_successful']);
    }

//    public function alterenable() {
//        $status = $this->model->getOne(_post('id'));
//        $status->enable = _post('id');
//        if ($status->save()) {
//            echo json_encode(array("status" => "OK", 'msg' => $this->_L['Edited Successfull']));
//        } else {
//            echo json_encode(array("status" => "OK", 'msg' => $this->_L['module imobles error operation']));
//        }
//    }

    public function import_csv() {

        @ini_set('memory_limit', '40095M');
        @ini_set('max_execution_time', 0);
        @set_time_limit(0);

        $css_arr = array('dropzone/dropzone');
        $js_arr = array('dropzone/dropzone',
            '/../../../application/plugins/module_imobles/assets/js/import-typeunity',
        );

        $assets_css = Asset::css($css_arr);
        $assets_js = Asset::js($js_arr);
        $this->ui->assign('xheader', $assets_css);
        $this->ui->assign('xfooter', $assets_js);

        $this->ui->assign('_st', $this->_L['Import'] . " " . $this->_L['module imobles typeunity']);
        $this->ui->assign('_include', 'typeunitys/import');
        $this->ui->display('wrapper.tpl');
    }

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

        $uploader = new Uploader();
        $uploader->setMaxSize(50);
        $uploader->setDir('application/storage/temp/');
        $uploader->sameName(false);
        $uploader->setExtensions(array('csv'));  //allowed extensions list//
        if ($uploader->uploadFile('file')) {   //txtFile is the filebrowse element name //
            $uploaded = $uploader->getUploadName(); //get uploaded file name, renames on upload//

            $_SESSION['uploaded'] = $uploaded;
        } else {//upload failed
            _msglog('e', $uploader->getMessage()); //get upload error message
        }
    }

    public function csv_uploaded() {
        @ini_set('memory_limit', '40095M');
        @ini_set('max_execution_time', 0);
        @set_time_limit(0);
        $uploaded = false;
//        $uploaded = 'Unidades (3).csv';
        if (isset($_SESSION['uploaded']) || $uploaded) {
            $uploaded = $_SESSION['uploaded'];
            $csv = new parseCSV();
            $csv->auto('application/storage/temp/' . $uploaded);
            $enterps = $csv->data;
            $cn = 0;
            $count_updated = 0;
            $msg_erro = null;
            $count_total = 0;
            foreach ($enterps as $enterp) {
                $data = array();
                //solução para bug da primeira colna que não reconhece no array a posição
                foreach ($enterp as $value) {
                    $data['alias'] = $value;
                    break;
                }

//                var_dump($count_total);
//                $count_total++;
//                var_dump($enterp);exit;
                // Verifico se é pra para cadastrar as Unidades
                if ($enterp['Unid. Disp'] == 999) {
                    continue;
                }
                $data['crawler_type_id'] = 4;
                $data['verified'] = 1;
                $data['title'] = $enterp['Unidade - Descrição'];
                $data['desc'] = @$enterp['Unidade - Descrição'];
                $data['area'] = (isset($enterp['Área - m²'])) ? $enterp['Área - m²'] : '0';
                $data['roof'] = (isset($enterp['Cobertura/Duplex'])) ? ($enterp['Cobertura/Duplex'] == 'Sim' ? 1 : 0) : '0';
                $data['duplex'] = (isset($enterp['Cobertura/Duplex'])) ? ($enterp['Cobertura/Duplex'] == 'Sim' ? 1 : 0) : '0';
                $data['garage_drawer'] = (isset($enterp['Gaveta'])) ? ($enterp['Gaveta'] == 'Sim' ? 1 : 0) : '0';
                $data['link_plant'] = (isset($enterp['Link Planta'])) ? $enterp['Link Planta'] : '';
                $data['number_rooms'] = (isset($enterp['Quartos'])) ? intval($enterp['Quartos']) : '';
                $data['number_suite'] = (isset($enterp['Suítes'])) ? intval($enterp['Suítes']) : '';
                $data['number_garage'] = (isset($enterp['Garagens'])) ? intval($enterp['Garagens']) : '0';
                $data['number_bathroom'] = (isset($enterp['Banheiros'])) ? $enterp['Banheiros'] : '0';
                $data['varanda_sacada'] = (isset($enterp['Varanda/Sacada'])) ? ($enterp['Varanda/Sacada'] == 'Sim' ? 'Little' : null) : null;
//                $data['hobbox'] = (isset($enterp['Gaveta'])) ? ($enterp['Gaveta']=='Sim'?1:0): '0';
                // $data['number_toilet'] = (isset($enterp['Gaveta'])) ? ($enterp['Gaveta']=='Sim'?1:0): '0';
                $data['promo'] = (isset($enterp['Promo'])) ? ($enterp['Promo'] == 'Sim' ? 1 : 0) : '0';
                $data['garage_drawer'] = (isset($enterp['Gaveta'])) ? ($enterp['Gaveta'] == 'Sim' ? 1 : 0) : '0';
//                $data['table_disponible'] = (isset($enterp['Tabela Disponibilidade'])) ? $enterp['Tabela Disponibilidade'] : '';
//                $data['status_wordpress'] = (isset($enterp['Status Wordpress'])) ? $enterp['Status Wordpress'] : '';
//                $data['garages_cheaper_plant'] = (isset($enterp['Garagens - Planta mais Barata'])) ? $enterp['Garagens - Planta mais Barata'] : '';
//                $data['link_capa_comparator'] = (isset($enterp['Link Capa - Formato Comparador'])) ? $enterp['Link Capa - Formato Comparador'] : '';
//                switch (@$enterp['Status Comparador']) {
//                    case "Concluído / Publicar": $data['comparator_status'] = "Finished";
//                        break;
//                    case "Iniciado": $data['comparator_status'] = "Started";
//                        break;
//                    case "Não iniciado - Backlog": $data['comparator_status'] = "Backlog";
//                        break;
//                    default :$data['comparator_status'] = "";
//                        break;
//                }
//
//                if (isset($enterp['Área Comum']) && !empty(trim($enterp['Área Comum']))) {
//                    $amenitiModel = new Enterprise_amenitiesModel();
//                    $areas = explode(",", $enterp['Área Comum']);
//                    foreach ($areas as $area) {
//                        if (!empty(trim($area))) {
//                            $c = $amenitiModel->getOneCollum('name', mb_strtoupper(trim($area)));
//                            if ($c) {
//                                $data['module_imobles_enterprise_units_type_amenities'][] = $c->id;
//                            } else {
//                                $typeunity_amenities = $amenitiModel->createEnterprise_amenities(array('name' => trim($area)));
//                                $data['module_imobles_enterprise_units_type_amenities'][] = $typeunity_amenities->id;
//                            }
//                        }
//                    }
//                }

                if (isset($enterp['Nome Empreendimento']) && !empty(trim($enterp['Nome Empreendimento']))) {
                    $stModel = new EnterprisesModel();
                    $c = $stModel->getOneCollum('alias', trim($enterp['Empreendimento - Descrição']));
                    if ($c) {
                        $data['module_imobles_enterprise_id'] = $c->id;
                    } else {
                        $msg_erro .= 'Empreendimento não encontrado: ' . $enterp['Nome Empreendimento'] . '<br/>';
                        continue;
                    }
                }

                $tower = ORM::for_table('module_imobles_enterprise_towers')->where('module_imobles_enterprise_id', $c->id)->find_one();
                if (!isset($tower->id)) {
                    $msg_erro .= 'Unidade Não cadastrada | Torre não encontrada: ' . $c->name . '<br/>';
                    continue;
                }

                // Verifico a quantidade de unidades disponíveis para o Tipo de Unidade
                $unidades = intval($enterp['Unid. Disp']);

                // Verifico se o tipo de Unidade já foi cadastrado
                $unit_type_aux = ORM::for_table('module_imobles_enterprise_units_type')
                        ->where('title', $enterp['Unidade - Descrição'])
                        ->where('crawler_type_id', 4)
                        ->where('module_imobles_enterprise_id', $c->id)
                        ->find_one();
                if (isset($unit_type_aux->id)) {
                    $typeunitys = $this->model->getOne($unit_type_aux->id);
                    $typeunitys = $this->model->updateTypeunity($data, $typeunitys);

                    $msg_erro .= '#################### TIPO DE UNIDADE ATUALIZADA: ' . $c->name . ' | TIPO DE UNIDADE: ' . $enterp['Unidade - Descrição'] . '<br/>';

                    $arr_units = ORM::for_table('module_imobles_enterprise_units')
                                    ->where('crawler_type_id', 4)
                                    ->where('module_imobles_enterprise_units_type_id', $unit_type_aux->id)
                                    ->order_by_asc('id')->find_many();
                    if ($arr_units) {
                        $datetime = 0;
                        $count_units = 0;
                        $count_deleted_units = 0;
                        $count_updated_units = 0;
                        $sqlUpdate = "";
                        foreach ($arr_units as $unit) {
                            if ($count_units >= $unidades) {
                                // Deleto a unidade
//                                $unit->verified = 1;
//                                $unit->crawler_type_id = 4;
//                                $unit->updated_at = date('Y-m-d H:i:s');
//                                $unit->unavailable = 1;
//                                $unit->save();
                                $sqlUpdate.=" UPDATE module_imobles_enterprise_units"
                                        . " SET verified=1,  crawler_type_id=4, unavailable=1,"
                                        . "  updated_at='" . date('Y-m-d H:i:s') . "'
                                            
                                 WHERE id='".$unit->id."' ; ";
                                
                                $count_deleted_units++;
                            } else {
                                // Atualizo a Unidade
//                                $unit->verified = 1;
//                                $unit->crawler_type_id = 4;
//                                $unit->updated_at = date('Y-m-d H:i:s');
//                                $unit->save();
                                $count_updated_units++;
                                
                                $sqlUpdate.=" UPDATE module_imobles_enterprise_units"
                                        . " SET verified=1,  crawler_type_id=4, "
                                       . "  updated_at='" . date('Y-m-d H:i:s') . "' 
                                        WHERE id='".$unit->id."' ; ";
//                                
                            }


                            $sqlUpdate .= " UPDATE `module_imobles_listings` 
                                            SET verified='1',crawler_type_id=4, crawler_type='airtable' , 
                                            crawler_price='" . intval(str_replace(',', '', $enterp['R$ Preço'])) . "', 
                                            updated_at='" . date('Y-m-d H:i:s') . "'
                                            WHERE unit_id='".$unit->id."' AND crawler_type_id=4 order by id ASC limit 1; ";

                            // Atualizo o Anúncio
//                            $arr_listing = ORM::for_table('module_imobles_listings')
//                                            ->where('unit_id', $unit->id)
//                                            ->where('crawler_type_id', 4)
//                                            ->order_by_asc('id')->find_one();
//                            if (isset($arr_listing->id)) {
//                                $arr_listing->crawler_type = 'airtable';
//                                $arr_listing->crawler_type_id = 4;
//                                $arr_listing->verified = 1;
//                                $arr_listing->crawler_price = intval(str_replace(',', '', $enterp['R$ Preço']));
//                                $arr_listing->updated_at = date('Y-m-d H:i:s');
//                                $arr_listing->save();
//                            }
                            $count_units++;
                            $datetime = strtotime($unit->created_at);
                        }

//                        if (!empty($sqlUpdate)) {
//                            ORM::for_table('module_imobles_listings')->execute($sqlUpdate);
//                        }
                        $sqlUpdate = "";

                        $unidades_aux = $unidades - $count_units;
                        $count_created_units = 0;
                        if ($unidades_aux > 0) {
                            for ($i = 0; $i < $unidades_aux; $i++) {
                                // Cadastro a Unidade
                                $d = ORM::for_table('module_imobles_enterprise_units')->create();
                                $d->module_imobles_enterprise_units_type_id = $unit_type_aux->id;
                                $d->module_imobles_enterprise_towers_id = $tower->id;
                                $d->created_at = date('Y-m-d H:i:s');
                                $d->created_by = 0;
                                $d->crawler_type_id = 4;
                                $d->verified = 1;
                                $d->save();
                                $unit = $d->id;

                                // Cadastro o anúncio
                                $d = ORM::for_table('module_imobles_listings')->create();
                                $d->entreprise_id = $c->id;
                                $d->unit_type_id = $unit_type_aux->id;
                                $d->unit_id = $unit;
                                $d->crawler_type = 'airtable';
                                $d->crawler_type_id = 4;
                                $d->crawler_price = intval(str_replace(',', '', $enterp['R$ Preço']));
                                $d->created_at = date('Y-m-d H:i:s');
                                $d->created_by = 0;
                                $d->verified = 1;
                                $d->save();
                                $count_created_units++;
                            }
                        }

                        $msg_erro .= 'UNIDADES ATUALIZADAS: ' . $count_updated_units . '<br/>';
                        $msg_erro .= 'UNIDADES DELETADAS: ' . $count_deleted_units . '<br/>';
                        $msg_erro .= 'UNIDADES CRIADAS: ' . $count_created_units . '<br/>';
                    } else {
                        // Erro
                        $msg_erro .= 'Unidade não encontrada: UNIT TYPE ID: ' . $unit_type_aux->id . '<br/>';
                        continue;
                    }
                } else {
                    $unit_type_aux = $this->model->createTypeunity($data);
                    $msg_erro .= 'TIPO DE UNIDADE CRIADA: ' . $c->name . ' | TIPO DE UNIDADE: ' . $enterp['Unidade - Descrição'] . '<br/>';
                    if (is_numeric($unit_type_aux->id)) {
                        $cn++;

                        $unavailable = null;
                        if ($unidades == 0) {
                            $unidades = 1;
                            $unavailable = 1;
                        }
                        $count_created_units = 0;
                        for ($i = 0; $i < $unidades; $i++) {
                            // Cadastro a Unidade
                            $d = ORM::for_table('module_imobles_enterprise_units')->create();
                            $d->module_imobles_enterprise_units_type_id = $unit_type_aux->id;
                            $d->module_imobles_enterprise_towers_id = $tower->id;
                            $d->created_at = date('Y-m-d H:i:s');
                            $d->created_by = 0;
                            $d->crawler_type_id = 4;
                            $d->verified = 1;
                            $unit->unavailable = $unavailable;
                            $d->save();
                            $unit = $d->id;

                            // Cadastro o anúncio
                            $d = ORM::for_table('module_imobles_listings')->create();
                            $d->entreprise_id = $c->id;
                            $d->unit_type_id = $unit_type_aux->id;
                            $d->unit_id = $unit;
                            $d->crawler_type = 'airtable';
                            $d->crawler_type_id = 4;
                            $d->crawler_price = intval(str_replace(',', '', $enterp['R$ Preço']));
                            $d->created_at = date('Y-m-d H:i:s');
                            $d->created_by = 0;
                            $d->verified = 1;
                            $d->save();
                            $count_created_units++;
                        }
                        $msg_erro .= '###################### UNIDADES CRIADAS: ' . $count_created_units . '<br/>';
                    } else {
                        $msg_erro .= 'Erro ao cadastrar TIPO DE UNIDADE: ' . $enterp['Unidade - Descrição'] . ' | ' . $enterp['Nome Empreendimento'];
                    }
                }
            }

//            echo 'FIMMMMMMM';
            unlink('application/storage/temp/' . $uploaded);
            _msglog('s', $cn . " " . $this->_L['module imobles typeunity Imported'] . '<br/>' . $msg_erro);

//            ob_start();
//            var_dump($enterps);
//            $result = ob_get_clean();
//
//            _msglog('s',$result);
        } else {

            _msglog('e', $this->_L['module imobles typeunity Imported error']);
        }
        r2(U . 'module_imobles/typeunity/listAll');
    }

    public function add_attach() {
        $uploader = new Uploader();

        $uploader->setDir('application/plugins/module_imobles/uploads/typeunity/');
        $uploader->sameName(false);
        $uploader->setExtensions(array('jpg', 'jpeg', 'png', 'gif', 'pdf'));
        $uploader->setMaxSize(5);
        if ($uploader->uploadFile('file')) {
            $uploaded = $uploader->getUploadName();
            $file = $uploaded;
            $msg = "Envio concluído";
            $success = 'Yes';
            $d = ORM::for_table('module_imobles_enterprise_units_type_plant')->create();
            $d->src = $uploaded;
            $d->name = $uploader->getOldName();
            if (isset($this->routes['3']) && $this->routes['3'] > 0) {
                $d->module_imobles_enterprise_units_type_id = $this->routes['3'];
            } else {
                //grava a imagem como pertencente ao usuário, antes dele salvar o novo produto
                $user = User::_info();
                $d->user_id = $user->id;
            }
            $d->save();
            $id = $d->id;
        } else {//upload failed
            $file = '';
            $msg = $uploader->getMessage();
            $success = 'No';
            $id = '';
        }

        $a = array(
            'success' => $success,
            'msg' => $msg,
            'file' => $file,
            'id' => $id,
            'url' => APP_URL . '/application/plugins/module_imobles/uploads/typeunity/' . $file
        );

        header('Content-Type: application/json');

        echo json_encode($a);
    }

    public function delete_attach() {
        $id = _post('id');
        $d = ORM::for_table('module_imobles_enterprise_units_type_plant')->find_one($id);
        if ($d) {
            $d->delete();
            unlink('application/plugins/module_imobles/uploads/typeunity/' . $d->src);
            $msg = $this->_L['Deleted Successfully'];
            $status = 'Yes';
        } else {
            $msg = $this->_L['Not found'];
            $status = "ERROR";
        }
        $data = array(
            'status' => $status,
            'msg' => $msg,
        );
        header('Content-Type: application/json');
        echo json_encode($data);
    }

    function saveMandeUmZap() {
        $arr_ids = $_POST['id'];
        $arr_phones = $_POST['whatsapp'];
        $arr_names = $_POST['name'];
        $arr_listings = $_POST['crawler_listing_id'];

        $user = User::_info();

        for ($i = 0; $i < count($arr_ids); $i++) {
            $listing = ORM::for_table('module_imobles_listings')->find_one($arr_ids[$i]);

            if (!$listing->crawler_whatsappNumber) {
                continue;
            }

            switch ($listing->crawler_portal) {
                case 'GRUPOZAP':
                    $portal = "zapimoveis.com.br";
                    break;
                case 'VIVAREAL':
                    $portal = "vivareal.com.br";
                    break;
                default:
                    $portal = "zapimoveis.com.br";
                    break;
            }

            if (!empty($_POST['msg'])) {
                $msg = $_POST['msg'];

                $msg = str_replace("{{USER_NAME}}", $user_name, $msg);
                $msg = str_replace("{{LISTING_LINK}}", $portal . $listing->crawler_listing_link, $msg);
            } else {
                $msg = "Olá, tudo bem? Me chamo " . $user_name . ", sou Consultor de Vendas na imobles.com\n\n"
                        . "Tenho um cliente interessado na unidade do seu anúncio:\n"
                        . $portal . $listing->crawler_listing_link . "\n\n"
                        . "Essa unidade está disponível? Você tem interesse em uma parceria para essa venda? Grato pelo retorno! Abraço!";
            }

            $what = ORM::for_table('module_imobles_mandeumzap_listings')->create();
            $what->msg = $msg;
            $what->listing_id = $listing->id;
            $what->advertise_id = $listing->advertise_id;
            $what->user_id = $user->id;
            $what->created_at = date('Y-m-d H:i:s');
            $what->updated_at = $tower->created_at;
            $what->send_at = $tower->created_at;
            $what->created_by = $user->id;
            $what->updated_by = $user->id;
            if (!empty(_post("muz_msg_id_" . $listing->id))) {
                $what->muz_msg_id = _post("muz_msg_id_" . $listing->id);
            }
            $what->save();
        }
        $return = array("status" => 'ok');
        echo json_encode($return);
    }

}

Anon7 - 2022
AnonSec Team