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

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/lrsys/public_html/lrsys_apps/mundotennis/application/controllers/contacts.php
<?php

// *************************************************************************
// *                                                                       *
// * iBilling -  Accounting, Billing Software                              *
// * Copyright (c) Sadia Sharmin. All Rights Reserved                      *
// *                                                                       *
// *************************************************************************
// *                                                                       *
// * Email: sadiasharmin3139@gmail.com                                                *
// * Website: http://www.sadiasharmin.com                                  *
// *                                                                       *
// *************************************************************************
// *                                                                       *
// * This software is furnished under a license and may be used and copied *
// * only  in  accordance  with  the  terms  of such  license and with the *
// * inclusion of the above copyright notice.                              *
// * If you Purchased from Codecanyon, Please read the full License from   *
// * here- http://codecanyon.net/licenses/standard                         *
// *                                                                       *
// *************************************************************************

if (!isset($myCtrl)) {
    $myCtrl = 'contacts';
}
_auth();
$ui->assign('_application_menu', 'contacts');
$ui->assign('_title', $_L['Contacts'] . ' - ' . $config['CompanyName']);
$ui->assign('_st', $_L['Contacts']);
$ui->assign('content_inner', inner_contents($config['c_cache']));
$action = $routes['1'];
$user = User::_info();
$ui->assign('user', $user);

$ui->assign('jsvar', '
_L[\'Working\'] = \'' . $_L['Working'] . '\';
_L[\'Submit\'] = \'' . $_L['Submit'] . '\';
 ');


switch ($action) {
    case 'add':

        // TODO: verificar pq tem que limpar o Cookie pra não dar problemas quando o site da Receita bloqueia as requisições. 
        unset($_COOKIE['PHPSESSID']);

        Event::trigger('contacts/add/');

        $ui->assign('countries', Countries::all()); // may add this $config['country_code']

        $fs = ORM::for_table('crm_customfields')->where('ctype', 'crm')->order_by_asc('id')->find_many();
        $ui->assign('fs', $fs);


        $css_arr = array('s2/css/select2.min', 'modal', 'dp/dist/datepicker.min', 'redactor/redactor');
        $js_arr = array('redactor/redactor.min', 'modal', 'numeric', 'modal-add-contact', 's2/js/select2.min', 's2/js/i18n/' . lan(), 'dp/dist/datepicker.min', 'dp/i18n/' . $config['language'], 'add-contact');


        $ui->assign('xheader', Asset::css($css_arr));
        $ui->assign('xfooter', Asset::js($js_arr));
        $ui->assign('xjq', '
            $(".select2").select2({
            theme: "bootstrap"
            });
             $(\'.amount\').autoNumeric(\'init\');
            ');

        $ui->assign('jsvar', '
        _L[\'Working\'] = \'' . $_L['Working'] . '\';
        _L[\'CPF Invalid\'] = \'' . $_L['CPF Invalid'] . '\';
        _L[\'CNPJ Invalid\'] = \'' . $_L['CNPJ Invalid'] . '\';
         ');


        $currencies = Model::factory('Models_Currency')->find_array();

        $ui->assign('currencies', $currencies);

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

        $ui->display('add-contact.tpl');
        break;

    case 'summary':


        Event::trigger('contacts/summary/');


        $cid = _post('cid');
        $d = ORM::for_table('crm_accounts')->find_one($cid);
        if ($d) {
            $ti = ORM::for_table('sys_transactions')
                    ->where('payerid', $cid)
                    ->sum('cr');
            if ($ti == '') {
                $ti = '0';
            }
            $ui->assign('ti', $ti);
            $te = ORM::for_table('sys_transactions')
                    ->where('payeeid', $cid)
                    ->sum('dr');
            if ($te == '') {
                $te = '0';
            }

            $ui->assign('te', $te);
            $ui->assign('d', $d);

            $cf = ORM::for_table('crm_customfields')->where('ctype', 'crm')->order_by_asc('id')->find_many();
            $ui->assign('cf', $cf);

            // Find Profit

            if ($ti > $te) {

                $happened = $_L['Profit'];
                $css_class = 'green';

                $d_amount = $ti - $te;
            } else {
                $happened = $_L['Loss'];
                $css_class = 'danger';
                $d_amount = $te - $ti;
            }

            $ui->assign('happened', $happened);
            $ui->assign('css_class', $css_class);
            $ui->assign('d_amount', $d_amount);

            $address = ORM::for_table('crm_accounts_address')->where('crm_account_id', $cid)->where('type_address', 'tax_address')->find_many();
            if (count($address) > 0) {
                $ui->assign('address', $address[0]);
                $city = ORM::for_table('city')->find_one($address[0]->city_id);
                $ui->assign('city', $city);

                $state = ORM::for_table('state')->find_one($address[0]->state_id);
                $ui->assign('state', $state);
            } else {
                $ui->assign('address', '');
                $ui->assign('city', '');
                $ui->assign('state', '');
            }

            //carrrrega os grupos do usuário seguindo o padrão anterior que carregava com ,
            $grupos = ORM::for_table('crm_groups')
                            ->table_alias('g')
                            ->select('g.*')
                            ->select('cg.*')
                            ->left_outer_join('crm_accounts_groups', array('g.id', '=', 'cg.crm_group_id'), 'cg')
                            ->where('cg.crm_accounts_id', $cid)->find_many();
            $text_grupos = '';

            $indFunc = false;

            foreach ($grupos as $gup) {
                if ($gup->default) {
                    $text_grupos .= "," . $_L[$gup->gname] . " ";
                } else {
                    $text_grupos .= "," . $gup->gname . " ";
                }
                if ($gup['crm_group_id'] == 5)
                    $indFunc = true;
            }

            $ui->assign('grupos', empty($text_grupos) ? '' : substr($text_grupos, 1) );

            if ($indFunc) {
                //view para funcs
                $compls = ORM::for_table('module_hr_compl_data')->where('func', $cid)->find_many();
                if (count($compls) > 0) {
                    $compls[0]['func_dt_admss'] = implode("/", array_reverse(explode("-", $compls[0]['func_dt_admss'])));
                    $compls[0]['dt_ctps'] = implode("/", array_reverse(explode("-", $compls[0]['dt_ctps'])));
                    $compls[0]['rg_dt_emiss'] = implode("/", array_reverse(explode("-", $compls[0]['rg_dt_emiss'])));
                    $d['date_of_birth'] = implode("/", array_reverse(explode("-", $d['date_of_birth'])));

                    $state = ORM::for_table('state')->find_one($compls[0]['rg_uf']);
                    $compls[0]['rg_uf'] = $state['state_name'];
                    if ($d['sex'] == 2) {
                        $d['sex'] = $_L['Female'];
                    } else if ($d['sex'] == 1) {
                        $d['sex'] = $_L['Male'];
                    } else {
                        $d['sex'] = "";
                    }
                    $state = ORM::for_table('state')->find_one($compls[0]['uf_ctps']);
                    $compls[0]['uf_ctps'] = $state['state_name'];

                    if ($compls[0]['civil'] == '') {
                        $compls[0]['civil'] = '';
                    } else if ($compls[0]['civil'] == 1) {
                        $compls[0]['civil'] = $_L['Single'];
                    } else if ($compls[0]['civil'] == 2) {
                        $compls[0]['civil'] = $_L['Married'];
                    } else if ($compls[0]['civil'] == 3) {
                        $compls[0]['civil'] = $_L['Separate'];
                    } else if ($compls[0]['civil'] == 4) {
                        $compls[0]['civil'] = $_L['Divorced'];
                    } else if ($compls[0]['civil'] == 5) {
                        $compls[0]['civil'] = $_L['Widower'];
                    }

                    if ($compls[0]['skin'] == '') {
                        $compls[0]['skin'] = '';
                    } else if ($compls[0]['skin'] == 1) {
                        $compls[0]['skin'] = $_L['White'];
                    } else if ($compls[0]['skin'] == 2) {
                        $compls[0]['skin'] = $_L['Black'];
                    } else if ($compls[0]['skin'] == 3) {
                        $compls[0]['skin'] = $_L['Brown'];
                    } else if ($compls[0]['skin'] == 4) {
                        $compls[0]['skin'] = $_L['Yellow'];
                    } else if ($compls[0]['skin'] == 5) {
                        $compls[0]['skin'] = $_L['Indigenous'];
                    }

                    if ($compls[0]['dgr_instruction'] == '') {
                        $compls[0]['dgr_instruction'] = '';
                    } else if ($compls[0]['dgr_instruction'] == 1) {
                        $compls[0]['dgr_instruction'] = $_L['Basic level (1st grade)'];
                    } else if ($compls[0]['dgr_instruction'] == 2) {
                        $compls[0]['dgr_instruction'] = $_L['Middle level (2nd grade)'];
                    } else if ($compls[0]['dgr_instruction'] == 3) {
                        $compls[0]['dgr_instruction'] = $_L['Superior'];
                    } else if ($compls[0]['dgr_instruction'] == 4) {
                        $compls[0]['dgr_instruction'] = $_L['Postgraduate'];
                    } else if ($compls[0]['dgr_instruction'] == 5) {
                        $compls[0]['dgr_instruction'] = $_L['Master'];
                    } else if ($compls[0]['dgr_instruction'] == 6) {
                        $compls[0]['dgr_instruction'] = $_L['Doctorate'];
                    } else if ($compls[0]['dgr_instruction'] == 7) {
                        $compls[0]['dgr_instruction'] = $_L['Post doctoral'];
                    }

                    if ($compls[0]['cat_cnh'] == '') {
                        $compls[0]['cat_cnh'] = '';
                    } else if ($compls[0]['cat_cnh'] == 1) {
                        $compls[0]['cat_cnh'] = $_L['Cnh A'];
                    } else if ($compls[0]['cat_cnh'] == 2) {
                        $compls[0]['cat_cnh'] = $_L['Cnh B'];
                    } else if ($compls[0]['cat_cnh'] == 3) {
                        $compls[0]['cat_cnh'] = $_L['Cnh C'];
                    } else if ($compls[0]['cat_cnh'] == 4) {
                        $compls[0]['cat_cnh'] = $_L['Cnh D'];
                    } else if ($compls[0]['cat_cnh'] == 5) {
                        $compls[0]['cat_cnh'] = $_L['Cnh E'];
                    } else if ($compls[0]['cat_cnh'] == 6) {
                        $compls[0]['cat_cnh'] = $_L['Cnh AB'];
                    }

                    $cost_center = ORM::for_table('module_billing_cost_center')->find_one($compls[0]['cost_center']);
                    $compls[0]['cost_center'] = $cost_center[0]['name'];

                    $ui->assign('compls', $compls[0]);
                } else {
                    $ui->assign('compls', '');
                }
                $imgs = ORM::for_table('module_hr_empl_files')->where('func', $cid)->find_many();
                if (count($compls) > 0) {
                    $ui->assign('imgs', $imgs[0]);
                } else {
                    $ui->assign('imgs', '');
                }
                $jobs = ORM::for_table('module_hr_job_journey')->where('func', $cid)->find_many();
                if (count($jobs) > 0) {
                    $ui->assign('jobs', $jobs);
                } else {
                    $ui->assign('jobs', '');
                }
                $suns = ORM::for_table('module_hr_suns')->where('func', $cid)->find_many();
                if (count($suns) > 0) {
                    $val = sizeof($suns);
                    $ui->assign('qtdsuns', $val);
                    $ui->assign('suns', $suns);
                } else {
                    $ui->assign('qtdsuns', '');
                    $ui->assign('suns', '');
                }
                $sectors = ORM::for_table('module_hr_sectors')->where('id', $compls[0]['func_sector'])->find_many();
                if (count($sectors) > 0) {
                    $ui->assign('sectors', $sectors[0]);
                } else {
                    $ui->assign('sectors', '');
                }
                $functions = ORM::for_table('module_hr_functions')->where('id', $compls[0]['func_carg'])->find_many();
                if (count($functions) > 0) {
                    $ui->assign('functions', $functions[0]);
                } else {
                    $ui->assign('functions', '');
                }
            }

            //fim view func
            $ui->assign('config', $config);
            $ui->assign('indFunc', $indFunc);

            $ui->display('ajax.contact-summary.tpl');
        }


        break;

    case 'activity':

        Event::trigger('contacts/activity/');

        $cid = _post('cid');
        $d = ORM::for_table('crm_accounts')->find_one($cid);
        if ($d) {
            $ac = ORM::for_table('sys_activity')->where('cid', $cid)->limit(20)->order_by_desc('id')->find_many();
            $ui->assign('ac', $ac);
            $ui->display('ajax.contact-activity.tpl');
        } else {
            
        }


        break;


    case 'invoices':

        Event::trigger('contacts/invoices/');
        $cid = _post('cid');
        $ui->assign('cid', $cid);
        $d = ORM::for_table('crm_accounts')->find_one($cid);
        if ($d) {
            $i = ORM::for_table('sys_invoices')->where('userid', $cid)->find_many();
            $ui->assign('i', $i);
            $ui->display('ajax.contact-invoices.tpl');
        } else {
            
        }
        break;

    case 'module_med_agreement':

        Event::trigger('contacts/module_med_agreement/');
        $cid = _post('cid');
        $ui->assign('id', $cid);
        $d = ORM::for_table('crm_accounts')->find_one($cid);
        if ($d) {
            $i = ORM::for_table('module_med_agreement_patient')
                            ->table_alias('map')
                            ->select('map.*')
                            ->select('ma.agreement_company_name')
                            ->left_outer_join('module_med_agreement', array('ma.id', '=', 'map.module_med_agreement_id'), 'ma')
                            ->where('map.crm_accounts_id', $cid)->find_many();


            $ui->assign('agreementPatient', $i);
            $ui->display('ajax.contact-module_med_agreements.tpl');
        } else {
            
        }
        break;
        
        
    case 'module_med_shedulling_post':
         if (_post('filter') == 'Y') {
            
            $_SESSION['filter_contact_med_schedulling_diary_id'] = _post('diary_id');
            $_SESSION['filter_contact_med_schedulling_professional_id'] = _post('professional_id');
            $_SESSION['filter_contact_med_schedulling_situation'] = _post('situation');
            $_SESSION['filter_contact_med_schedulling_search'] = _post('search');
            $_SESSION['filter_contact_med_schedulling_period'] = _post('period');
            $_SESSION['filter_contact_med_schedulling_date'] = _postDate('date');
            if ($_SESSION['filter_contact_med_schedulling_period'] == 'interval') {
                $_SESSION['filter_contact_med_schedulling_period_ini'] = _postDate('period_ini');
                $_SESSION['filter_contact_med_schedulling_period_end'] = _postDate('period_end');
            } else {
                $_SESSION['filter_contact_med_schedulling_period_ini'] = '';
                $_SESSION['filter_contact_med_schedulling_period_end'] = '';
            }
         }
        if(isset($routes['2']) && intval($routes['2'])){
            r2(U."contacts/view/".$routes['2']."/module_med_shedulling");
        }else{
        r2(U."contacts/list/",'e', $_L['not Found']);
        }
    break;
    case 'module_med_shedulling':
        if (isset($_SESSION['filter_contact_med_schedulling_diary_id'])) {
            $filter['filter_contact_med_schedulling_diary_id'] = $_SESSION['filter_contact_med_schedulling_diary_id'];
        } else {
            $filter['filter_contact_med_schedulling_diary_id'] = '';
        }
        if (isset($_SESSION['filter_contact_med_schedulling_professional_id'])) {
            $filter['filter_contact_med_schedulling_professional_id'] = $_SESSION['filter_contact_med_schedulling_professional_id'];
        } else {
            $filter['filter_contact_med_schedulling_professional_id'] = '';
        }
        if (isset($_SESSION['filter_contact_med_schedulling_situation'])) {
            $filter['filter_contact_med_schedulling_situation'] = $_SESSION['filter_contact_med_schedulling_situation'];
        } else {
            $filter['filter_contact_med_schedulling_situation'] = '';
        }
        
        if (isset($_SESSION['filter_contact_med_schedulling_period'])) {
            $filter['filter_contact_med_schedulling_period'] = $_SESSION['filter_contact_med_schedulling_period'];
        } else {
            $filter['filter_contact_med_schedulling_period'] = '';
        }
        if (isset($_SESSION['filter_contact_med_schedulling_period_ini'])) {
            $filter['filter_contact_med_schedulling_period_ini'] = $_SESSION['filter_contact_med_schedulling_period_ini'];
        } else {
            $filter['filter_contact_med_schedulling_period_ini'] = '';
        }
        if (isset($_SESSION['filter_contact_med_schedulling_period_end'])) {
            $filter['filter_contact_med_schedulling_period_end'] = $_SESSION['filter_contact_med_schedulling_period_end'];
        } else {
            $filter['filter_contact_med_schedulling_period_end'] = '';
        }

        if (isset($_SESSION['filter_contact_med_schedulling_date'])) {
            $filter['filter_contact_med_schedulling_date'] = $_SESSION['filter_contact_med_schedulling_date'];
        } else {
            $filter['filter_contact_med_schedulling_date'] = '';
        }

        $ui->assign('filter', $filter);
        
        
        
        Event::trigger('contacts/module_med_agreement/');
        $cid = _post('cid');
        $ui->assign('id', $cid);
        $d = ORM::for_table('crm_accounts')->find_one($cid);
        if ($d) {
            $scheduling = ORM::for_table('module_med_scheduling')
                    ->table_alias('s');
            $scheduling->select(array('s.urgency', 's.queue_number', 's.date', 's.hour_start', 's.id', 's.status', 's.observation', 'patient.account', 'patient.phone', 'patient.cell_phone', 'patient.email', 'diary.diary'))
                    ->select('professional.account', 'professional_name')
                    ->select('requester.account', 'requester_name')
                    ->select('sys_users.fullname', 'useradmin_name')
                    ->select(array('diary.diary', 'agreement.agreement_company_name'))
//                ->select_expr('concat(patient.account," | "," (",diary.diary,")")', 'patient')
          //          ->select_expr('concat(s.date," ",s.hour_start)', 'start')
                    ->select_expr('patient.id as patient_id')
                //    ->select_expr('(select sum(value) from module_med_payments where module_med_payments.scheduling_id= s.id) as value_payment_patient')
             //       ->select_expr('concat(s.date," ",s.hour_finish)', 'end')
                    ->select('agreement.create_invoice');




            $scheduling->left_outer_join('module_med_diary', array('diary.id', '=', 's.diary_id'), 'diary')
                    ->left_outer_join('crm_accounts', array('patient.id', '=', 's.patient_id'), 'patient')
                    ->left_outer_join('crm_accounts', array('professional.id', '=', 's.professional_id'), 'professional')
                    ->left_outer_join('crm_accounts', array('requester.id', '=', 's.requester_id'), 'requester')
                    ->left_outer_join('sys_users', array('sys_users.id', '=', 's.created_user_id'), 'sys_users')
                    ->left_outer_join('module_med_agreement', array('agreement.id', '=', 's.agreement_id'), 'agreement')
                    ->where_null('s.deleted_at')
                  
            ;

            if (isset($_SESSION['filter_contact_med_schedulling_diary_id']) && $_SESSION['filter_contact_med_schedulling_diary_id'] != 'All' && !empty($_SESSION['filter_contact_med_schedulling_diary_id'])) {
                $scheduling->where('s.diary_id', $_SESSION['filter_contact_med_schedulling_diary_id']);
            }
            if (isset($_SESSION['filter_contact_med_schedulling_professional_id']) && $_SESSION['filter_contact_med_schedulling_professional_id'] != 'whithout' && $_SESSION['filter_contact_med_schedulling_professional_id'] != 'All' && !empty($_SESSION['filter_contact_med_schedulling_professional_id'])) {
                $scheduling->where('s.professional_id', $_SESSION['filter_contact_med_schedulling_professional_id']);
            }
            //sem profissional registrado
            if (isset($_SESSION['filter_contact_med_schedulling_professional_id']) && $_SESSION['filter_contact_med_schedulling_professional_id'] == 'whithout') {
                $scheduling->where('s.professional_id', 0);
            }
            if (isset($_SESSION['filter_contact_med_schedulling_situation']) && $_SESSION['filter_contact_med_schedulling_situation'] != 'All' && !empty($_SESSION['filter_contact_med_schedulling_situation'])) {
                $scheduling->where('s.status', $_SESSION['filter_contact_med_schedulling_situation']);
            }
            if (isset($_SESSION['filter_contact_med_schedulling_search']) && !empty($_SESSION['filter_contact_med_schedulling_search'])) {
                $scheduling->where_any_is(array(array("patient.account" => '%' . $_SESSION['filter_contact_med_schedulling_search'] . '%'),
                    array("patient.cpf_cnpj" => '%' . $_SESSION['filter_contact_med_schedulling_search'] . '%')), 'like');
            }


            if (isset($_SESSION['filter_contact_med_schedulling_period']) && $_SESSION['filter_contact_med_schedulling_period'] != 'all' && !empty($_SESSION['filter_contact_med_schedulling_period'])) {

                if ($_SESSION['filter_contact_med_schedulling_period'] == 'day') {
                    $scheduling->where_raw("  s.date = '" . date('Y-m-d') . "'");
                } else if ($_SESSION['filter_contact_med_schedulling_period'] == 'week') {
                    $scheduling->where_raw("  WEEK(s.date) = WEEK('" . date('Y-m-d') . "')");
                } else if ($_SESSION['filter_contact_med_schedulling_period'] == 'month') {
                    $scheduling->where_raw("  MONTH(s.date) = MONTH('" . date('Y-m-d') . "')");
                } else {
                    if (!empty($_SESSION['filter_contact_med_schedulling_period_ini'])) {
                        $scheduling->where_raw("  s.date >='" . date('Y-m-d', strtotime($_SESSION['filter_contact_med_schedulling_period_ini'])) . "'");
                    }
                    if (!empty($_SESSION['filter_contact_med_schedulling_period_end'])) {
                        $scheduling->where_raw("  s.date <='" . date('Y-m-d', strtotime($_SESSION['filter_contact_med_schedulling_period_end'])) . "'");
                    }
                }
            }
            $scheduling->where("patient.id",$cid);
            $scheduling = $scheduling->find_many();

        $ormD = ORM::for_table('module_med_diary')->order_by_asc('id');
        $ui->assign('diarys', $ormD->find_many());
        
        $orm = ORM::for_table('crm_accounts')
                        ->table_alias('p')
                        ->select('p.account', 'name')
                        ->select('p.id')
                        ->join('crm_accounts_groups', array('p.id', '=', 'gp.crm_accounts_id'), 'gp')
                        ->join('crm_groups', array('g.id', '=', 'gp.crm_group_id'), 'g')
                        ->where('g.alias', 'doctor')->order_by_asc('name');
        ;
        
        $ui->assign('doctors', $orm->find_many());
     
        
if(count($scheduling)>0){
    foreach($scheduling as $s){
         if ($s->urgency == 'Y' && $s->status!= 'Finished') {
               $s->color= "#FF0000";
            } else {
                if ($s->status == 'Scheduled')
                    $s->color = "#6395ed";
                else if ($s->status == 'Confirmed')
                    $s->color = "#228B22";
                else if ($s->status == 'In progress')
                    $s->color = "#607d8b";
                else if ($s->status == 'On Hold')
                    $s->color = "#9c27b0";
                else if ($s->status == 'Canceled')
                    $s->color = "#f34a4a";
                else if ($s->status == 'Canceled Patient')
                    $s->color = "#d48080";
                else if ($s->status == 'Finished')
                    $s->color = "#000080";
                else if ($s->status == 'Missed')
                    $s->color = "#d46565";
                else if ($s->status == 'Payment')
                    $s->color = "#006400";
                else if ($s->status == 'PreAttribute')
                    $s->color = "#87CEFA";
                else if ($s->status == 'Redial')
                    $s->color = "#87CEFA";
            }
    }
}
        
        
            $ui->assign('scheduling', $scheduling);
            $ui->display('ajax.contact-module_med_schedulling.tpl');
        } else {
            
        }
        break;

    case 'quotes':

        Event::trigger('contacts/quotes/');

        $cid = _post('cid');
        $ui->assign('cid', $cid);
        $d = ORM::for_table('crm_accounts')->find_one($cid);
        if ($d) {
            $i = ORM::for_table('sys_quotes')->where('userid', $cid)->find_many();
            $ui->assign('i', $i);
            $ui->display('ajax.contact-quotes.tpl');
        } else {
            
        }


        break;





    case 'transactions':

        Event::trigger('contacts/transactions/');

        $cid = _post('cid');
        $d = ORM::for_table('crm_accounts')->find_one($cid);
        if ($d) {
            $tr = ORM::for_table('sys_transactions')
                            ->where_raw('(`payerid` = ? OR `payeeid` = ?)', array($cid, $cid))
                            ->order_by_desc('id')->find_many();
            $ui->assign('tr', $tr);
            $ui->display('ajax.contact-transactions.tpl');
        } else {
            
        }


        break;

    case 'email':

        Event::trigger('contacts/email/');

        $cid = _post('cid');
        $d = ORM::for_table('crm_accounts')->find_one($cid);
        if ($d) {
            $e = ORM::for_table('sys_email_logs')
                            ->where('userid', $cid)
                            ->order_by_desc('id')->find_many();
            $ui->assign('d', $d);
            $ui->assign('e', $e);
            $ui->display('ajax.contact-emails.tpl');
        } else {
            
        }


        break;


    case 'edit':

        Event::trigger('contacts/edit/');

        $cid = _post('cid');
        $d = ORM::for_table('crm_accounts')->find_one($cid);
        if ($d) {
            $fs = ORM::for_table('crm_customfields')->where('ctype', 'crm')->order_by_asc('id')->find_many();
            $ui->assign('fs', $fs);
            $ui->assign('countries', Countries::all($d['country']));
            $ui->assign('d', $d);

            //busca as tags
            $tags = Tags::get_all('Contacts');
            $ui->assign('tags', $tags);
            $dtags = explode(',', $d['tags']);
            $ui->assign('dtags', $dtags);

            //busca os estados
            $e = ORM::for_table('state')->order_by_asc('state_name')->find_many();
            $ui->assign('state', $e);

            // find all groups
            $groups = ORM::for_table('crm_groups')->order_by_asc('gname')->find_many();
            $ui->assign('groups', $groups);
            //busca os grupos selecionados
            $groupsSelected = ORM::for_table('crm_accounts_groups')->select('crm_group_id')->where('crm_accounts_id', $cid)->find_many();
            $dgroups = array('');
            //validar func para view - lpillon 17/03/2017
            $indFunc = false;
            foreach ($groupsSelected as $g) {
                $dgroups[] = $g['crm_group_id'];
                if ($g['crm_group_id'] == 5)
                    $indFunc = true;
            }
            $ui->assign('dgroups', $dgroups);

            //SEGMENTOS listagem
            $segments = ORM::for_table('crm_segments')->order_by_asc('name')->find_many();
            $ui->assign('segments', $segments);

            //busca o nome do salesman
            $nameSalesman = '';
            if ($d->salesman_id > 0) {
                $salesman = ORM::for_table('crm_accounts')->find_one($d->salesman_id);
                if ($salesman) {
                    if ($salesman->kind_of_person == 'PF') {
                        $nameSalesman = $salesman->cpf_cnpj . " - " . $salesman->account . " - " . $salesman->company;
                    } else {
                        $nameSalesman = $salesman->foreign_doc_identification . " - " . $salesman->account . " - " . $salesman->company;
                    }
                }
            }
            $ui->assign('nameSalesman', $nameSalesman);

            //pessoas de  contato busca a listagem
            $contacts = ORM::for_table('crm_accounts')
                            ->table_alias('c')
                            ->select('c.*')
                            ->left_outer_join('crm_accounts_contacts', array('c.id', '=', 'crm_c.crm_accounts_id_contact'), 'crm_c')
                            ->where('crm_c.crm_accounts_id', $cid)
                            ->order_by_desc('c.cpf_cnpj')->find_array();
            $ui->assign('contacts', $contacts);

            //buca o endereço
            $address = ORM::for_table('crm_accounts_address')->where('crm_account_id', $cid)->where('type_address', 'tax_address')->find_many();
            if (count($address) > 0) {
                $ui->assign('address', $address[0]);
            } else {
                $ui->assign('address', '');
            }
            //endereço de cobrança
            $address_c = ORM::for_table('crm_accounts_address')->where('crm_account_id', $cid)->where('type_address', 'billing_address')->find_many();
            if (count($address_c) > 0) {
                $ui->assign('address_c', $address_c[0]);
            } else {
                $ui->assign('address_c', '');
            }

            $currencies = Model::factory('Models_Currency')->find_array();

            $ui->assign('currencies', $currencies);

            //Funcs.
            if ($indFunc) {
                $compls = ORM::for_table('module_hr_compl_data')->where('func', $cid)->find_many();
                if (count($compls) > 0) {
                    $compls[0]['func_dt_admss'] = implode("/", array_reverse(explode("-", $compls[0]['func_dt_admss'])));
                    $compls[0]['dt_ctps'] = implode("/", array_reverse(explode("-", $compls[0]['dt_ctps'])));
                    $compls[0]['rg_dt_emiss'] = implode("/", array_reverse(explode("-", $compls[0]['rg_dt_emiss'])));
                    $d['date_of_birth'] = implode("/", array_reverse(explode("-", $d['date_of_birth'])));
                    $ui->assign('compls', $compls[0]);
                } else {
                    $ui->assign('compls', '');
                }
                $imgs = ORM::for_table('module_hr_empl_files')->where('func', $cid)->find_many();
                if (count($compls) > 0) {
                    $ui->assign('imgs', $imgs[0]);
                } else {
                    $ui->assign('imgs', '');
                }
                $jobs = ORM::for_table('module_hr_job_journey')->where('func', $cid)->find_many();
                if (count($jobs) > 0) {
                    $ui->assign('jobs', $jobs);
                } else {
                    $ui->assign('jobs', '');
                }
                $suns = ORM::for_table('module_hr_suns')->where('func', $cid)->find_many();
                if (count($suns) > 0) {
                    $val = sizeof($suns);
                    $ui->assign('qtdsuns', $val);
                    $ui->assign('suns', $suns);
                } else {
                    $ui->assign('qtdsuns', '');
                    $ui->assign('suns', '');
                }
                $sectors = ORM::for_table('module_hr_sectors')->find_many();
                if (count($sectors) > 0) {
                    $ui->assign('sectors', $sectors);
                } else {
                    $ui->assign('sectors', array());
                }
                $functions = ORM::for_table('module_hr_functions')->find_many();
                if (count($functions) > 0) {
                    $ui->assign('functions', $functions);
                } else {
                    $ui->assign('functions', array());
                }
                $cost_center = ORM::for_table('module_billing_cost_center')->order_by_asc('name')->find_many();
                $ui->assign('cost_center', $cost_center);
                $ui->assign('user', ORM::for_table('sys_users')->where("crm_accounts_id", $cid)->find_one());
                $roles = Model::factory('Models_Role')->find_array();
                $ui->assign('roles', $roles);
                $ui->assign('func', $cid);
                $ui->assign('screen', '2');
                $ui->display('application/plugins/module_hr/views/edit.tpl');
            } else {
                $ui->display('ajax.contact-edit.tpl');
            }
        }


        break;

    case 'modal_edit_contact_address':


        $cid = _post('cid');
        $d = ORM::for_table('crm_accounts')->find_one($cid);
        if ($d) {
            //busca os estados
            $e = ORM::for_table('state')->order_by_asc('state_name')->find_many();
            $ui->assign('state', $e);

            //buca o endereço
            $address = ORM::for_table('crm_accounts_address')->where('crm_account_id', $cid)->where('type_address', 'tax_address')->find_many();
            if (count($address) > 0) {
                $ui->assign('address', $address[0]);
            } else {
                $ui->assign('address', '');
            }
            //endereço de cobrança
            $address_c = ORM::for_table('crm_accounts_address')->where('crm_account_id', $cid)->where('type_address', 'billing_address')->find_many();
            if (count($address_c) > 0) {
                $ui->assign('address_c', $address_c[0]);
            } else {
                $ui->assign('address_c', '');
            }
            $ui->assign('d', $d);
            $ui->display('modal_edit_contact_address.tpl');
        }


        break;


    case 'add-activity-post':

        Event::trigger('contacts/add-activity-post/');

        $cid = _post('cid');
        $msg = $_POST['msg'];
        $icon = $_POST['icon'];
        $icon = trim($icon);
        //<a href="#"><i class="fa fa-camera"></i></a>

        $icon = str_replace('<a href="#"><i class="', '', $icon);
        $icon = str_replace('"></i></a>', '', $icon);
        if ($icon == '') {
            $icon = 'fa fa-check';
        }

        if (Validator::Length($msg, 1000, 5) == false) {
            echo $_L['Message Should be between 5 to 1000 characters'];
        } else {
            $d = ORM::for_table('sys_activity')->create();
            $d->cid = $cid;
            $d->msg = $msg;
            $d->icon = $icon;
            $d->stime = time();
            $d->sdate = date('Y-m-d');
            $d->o = $user['id'];
            $d->oname = $user['fullname'];
            $d->save();

            echo $cid;
        }

        break;


    case 'activity-delete':

        Event::trigger('contacts/activity-delete/');

        $id = $routes['3'];
        $d = ORM::for_table('sys_activity')->find_one($id);
        $d->delete();
        $cid = $routes['2'];
        r2(U . $myCtrl . '/view/' . $cid . '/', 's', $_L['Deleted Successfully']);
        break;

    case 'view':

        Event::trigger('contacts/view/');

        $id = $routes['2'];
        $d = ORM::for_table('crm_accounts')->find_one($id);
        if ($d) {

            $extra_tab = '';
            $extra_jq = '';

            $tab = route(3);

            if (!$tab) {

                $tab = 'summary';
            }

            $ui->assign('tab', $tab);

            Event::trigger('contacts/view/_on_start');

            $ui->assign('extra_tab', $extra_tab);

            // orders count

            $order_count = ORM::for_table('sys_orders')->where('crm_accounts_id', $id)->count();

            if ($order_count == '') {
                $order_count = 0;
            }

            $ui->assign('order_count', $order_count);

            // invoice count

            $inv_count = ORM::for_table('sys_invoices')->where('userid', $id)->count();

            if ($inv_count == '') {
                $inv_count = 0;
            }

            $ui->assign('inv_count', $inv_count);

            $quote_count = ORM::for_table('sys_quotes')->where('userid', $id)->count();

            if ($quote_count == '') {
                $quote_count = 0;
            }

            $ui->assign('quote_count', $quote_count);

            if (haveInstallPlugin("module_med_scheduling")) {
                $ui->assign('plugin_module_med_schedulling', true);

                $module_med_agreement_count = ORM::for_table('module_med_agreement_patient')->where('crm_accounts_id', $id)->count();
                if ($module_med_agreement_count == '') {
                    $module_med_agreement_count = 0;
                }

                $ui->assign('module_med_agreement_count', $module_med_agreement_count);

                $module_med_schedulling_count = ORM::for_table('module_med_scheduling')->where('patient_id', $id)->count();
                if ($module_med_schedulling_count == '') {
                    $module_med_schedulling_count = 0;
                }

                $ui->assign('module_med_schedulling_count', $module_med_schedulling_count);
            } else {
                $ui->assign('plugin_module_med_schedulling', false);
            }

            //find all activity for this user
//            $ac = ORM::for_table('sys_activity')->where('cid',$id)->limit(20)->order_by_desc('id')->find_many();
//            $ui->assign('ac',$ac);


            $ui->assign('xheader', Asset::css(array('modal',   'footable2018/css/footable.bootstrap.min', 'redactor/redactor', 'dp/dist/datepicker.min', 's2/css/select2.min', 'imgcrop/assets/css/croppic')) . '<link rel="stylesheet" type="text/css" href="application/plugins/module_hr/assets/css/default.css"><link rel="stylesheet" type="text/css" href="ui/lib/dropzone/dropzone.css">' . '
            
            <style>
            .redactor-box {

     margin-bottom: 0;
}
            </style>
            ');




            $ui->assign('xfooter', '<script type="text/javascript" src="ui/lib/dropzone/dropzone.js"></script>' . Asset::js(array('modal',  'footable2018/js/footable.min', 'modal-add-contact', 'redactor/redactor.min', 'dp/dist/datepicker.min', 's2/js/select2.min', 's2/js/i18n/' . lan(), 'imgcrop/croppic', 'numeric', 'profile', '/../../theme/lrsys/lib/jquery.maskMoney.min',), $file_build));

            $ui->assign('xjq', '
            var cid = $(\'#cid\').val();
               var _url = $("#_url").val();
               var cb = function cb (){
            };' . $extra_jq);

            //carrega os textos de idiomas necessários nos js    
            $ui->assign('jsvar', '
        _L[\'Working\'] = \'' . $_L['Working'] . '\';
        _L[\'CPF Invalid\'] = \'' . $_L['CPF Invalid'] . '\';
        _L[\'CNPJ Invalid\'] = \'' . $_L['CNPJ Invalid'] . '\';
         ');

            $ui->assign('d', $d);

            Event::trigger('contacts/view/_on_display');
            $ui->display('account-profile-alt.tpl');
        } else {
            r2(U . 'customers/list/', 'e', $_L['Account_Not_Found']);
        }

        break;
    //valida o documento informado, de acordo com cpf, cnpj ou doicumento de identificação
    case 'ajax-validation-document-contact':
        //caso seja alteração manda o id do contato
        //valida se veio o cpf
        $contatoId = _post("id");
        if (!empty(_post("cpf"))) {
            $data = ORM::for_table('crm_accounts')->where('kind_of_person', 'PF');
            //acrecenta que o cpf pode ser o do proprio contato
            if (intval($contatoId) > 0) {
                $data->where_not_equal('id', intval($contatoId));
            }
            $result = $data->where('cpf_cnpj', _post("cpf"))->find_one();
            if ($result) {
                echo $_L['CPF number already exist'] . ' <br>';
            }
            //valida se veio o cnpj
        } else if (!empty(_post("cnpj"))) {
            $data = ORM::for_table('crm_accounts')->where('kind_of_person', 'PJ');
            //acrecenta que o cpf pode ser o do proprio contato
            if (intval($contatoId) > 0) {
                $data->where_not_equal('id', intval($contatoId));
            }
            $result = $data->where('cpf_cnpj', _post("cnpj"))->find_one();
            if ($result) {
                echo $_L['CNPJ number already exist'] . ' <br>';
            }
        } else if (!empty(_post("foreign_doc"))) {
            $data = ORM::for_table('crm_accounts')
                    ->where('foreign_doc_identification', _post("foreign_doc"))
                    ->where('kind_of_person', 'E');
            //acrecenta que o cpf pode ser o do proprio contato
            if (intval($contatoId) > 0) {
                $data->where_not_equal('id', intval($contatoId));
            }
            $result = $data->find_one();
            if ($result) {
                echo $_L['Identification Document Foreigner number already exist'] . ' <br>';
            }
        }
        break;

    case 'add-post':

        Event::trigger('contacts/add-post/');

        Event::trigger('contacts/add-post/_on_start');

//recebe os dados por post
        $d = ORM::for_table('crm_accounts')->create();

        $d->account = _post('account');
        $d->kind_of_person = _post('kind_of_person');
        $d->company = _post('company');
        $d->code = _post('code');
        $d->rg = _post('rg');
        $d->foreign_doc_identification = _post('foreign_doc_identification');
        $d->taxpayer = _post('taxpayer');
        $d->ie = _post('ie');
        $d->im = _post('im');
        $d->email = _post('email');
        $d->email_nfe = _post('email_nfe');
        $d->phone = _post('phone');
        $d->fax = _post('fax');
        $d->cell_phone = _post('cell_phone');
        $d->web_site = _post('web_site');
        $d->currency = _post('currency');
        $d->country = _post('country');
        $d->notes = _post('notes');
        $d->marital_status = _post('marital_status');
        $d->jobtitle = _post('jobtitle');
        $d->sex = _post('sex');
        if (!empty(_post('date_of_birth'))) {
            $d->date_of_birth = _post('date_of_birth');
        }
        $d->naturalness = _post('naturalidade');
        $d->father_name = _post('father_name');
        $d->father_cpf = _post('father_cpf');
        $d->mother_name = _post('mother_name');
        $d->mother_cpf = _post('mother_cpf');
        $d->crt = _post('crt');
        $d->inscription_suframa = _post('inscription_suframa');
        $d->billing_address = empty(_post('billing_address')) ? 'N' : 'Y';
        if (intval(_post('salesman_id')) > 0) {
            $d->salesman_id = _post('salesman_id');
        }
        $d->payment_condition = _post('payment_condition');
        $d->status_crm = _post('status_crm');
        if (intval(_post('segment')) > 0) {
            $d->segment_id = _post('segment');
        }
        //recebe o valor e pssa para o método de fincas formatar adequadamente para registrar no BD
        $credit = _post('credit_limit');
        $d->credit_limit = Finance::amount_fix($credit);

        $msg = '';

        if ($d->kind_of_person == 'PJ') {
            $d->cpf_cnpj = _post('cnpj');
            $cpfCnpjTipo = 'CNPJ';
            $d->country = 'Brazil';
        } else if ($d->kind_of_person == 'PF') {
            $d->cpf_cnpj = _post('cpf');
            $cpfCnpjTipo = 'CPF';
            $d->country = 'Brazil';
        } else {
            $d->cpf_cnpj = '';
        }

        if ($d->currency == '') {
            $d->currency = '0';
        }

        if (isset($_POST['tags']) AND ( $_POST['tags']) != '') {
            $tags = $_POST['tags'];
        } else {
            $tags = '';
        }

//check if tag is already exisit
        if ($d->account == '') {
            $msg .= $_L['Name'] . $_L['is required'];
        }

        if ($d->email != '') {
            if (Validator::Email($d->email) == false) {
                $msg .= $_L['Invalid Email'] . ' <br>';
            }
            $f = ORM::for_table('crm_accounts')->where('email', $d->email)->find_one();

            if ($f) {
                $msg .= $_L['Email already exist'] . ' <br>';
            }
        }

        if ($d->email_nfe != '') {
            if (Validator::Email($d->email_nfe) == false) {
                $msg .= $_L['Invalid Email Nfe'] . ' <br>';
            }
        }

        if ($d->cpf_cnpj != '') {

            $f = ORM::for_table('crm_accounts')->where('cpf_cnpj', $d->cpf_cnpj)->find_one();
            if ($f) {
                $msg .= $_L[$cpfCnpjTipo . ' number already exist'] . ' <br>';
            }
        }
        if ($d->kind_of_person == 'E') {
            if ($d->foreign_doc_identification != '') {
                $f = ORM::for_table('crm_accounts')->where('foreign_doc_identification', $d->foreign_doc_identification)->find_one();
                if ($f) {
                    $msg .= $_L['Identification Document Foreigner number already exist'] . ' <br>';
                }
            }
        }

        $password = _post('password');
        $cpassword = _post('cpassword');

        $u_password = '';

        //valida tamanho da senha
        if ($password != '') {
            if (!Validator::Length($password, 15, 5)) {
                $msg .= $_L['Password should be between 6 to 15 characters'] . '<br>';
            }

            if ($password != $cpassword) {
                $msg .= $_L['Passwords does not match'] . '<br>';
            }
            $u_password = $password;
            $password = Password::_crypt($password);
        }


        if ($msg == '') {
            //Tags::save($tags, 'Contacts');
            if (isset($_POST['tags']) AND ( $_POST['tags']) != '') {
                $tags = $_POST['tags'];
            } else {
                $tags = '';
            }
            $d->tags = Arr::arr_to_str($tags);

            //others
            $d->password = $password;
            $d->fname = '';
            $d->lname = '';
            $d->cid = '0';
            $d->o = '0';
            $d->balance = '0.00';
            $d->status = 'Active';
            $d->token = '';
            $d->ts = '';
            $d->img = '';
            $d->web = '';
            $d->facebook = '';
            $d->google = '';
            $d->linkedin = '';

            //
            $d->save();
            $cid = $d->id();
            _log($_L['New Contact Added'] . ' ' . $d->account . ' [CID: ' . $cid . ']', 'Admin', $user['id']);

            //salva os grupos para o Contato
            if (isset($_POST['group'])) {
                $group = $_POST['group'];
                if (!empty($group)) {
                    foreach ($group as $g) {
                        $dataGroup = ORM::for_table('crm_accounts_groups')->create();
                        $dataGroup->crm_accounts_id = $cid;
                        $dataGroup->crm_group_id = $g;
                        $dataGroup->save();
                    }
                }
            }

            // Cleberson Falk - Condição para o Módulo Billing
            if (!isset($_POST['group']) || empty($_POST['group'])) {
                $url_origin = $_SERVER['HTTP_REFERER'];
                $url_part = explode('?ng=', $url_origin);

                $expense_route = "/module_billing\/billing\/expense\/?/";
                $income_route = "/module_billing\/billing\/income\/?/";

                // Se vier de contas a pagar, adiciona o grupo "Payee"
                if (isset($url_part[1]) && preg_match($expense_route, $url_part[1])) {
                    $dataGroup = ORM::for_table('crm_accounts_groups')->create();
                    $dataGroup->crm_accounts_id = $cid;
                    $dataGroup->crm_group_id = 2;
                    $dataGroup->save();
                }
                // Se vier de contas a receber, adiciona o grupo "Customer"
                else if (isset($url_part[1]) && preg_match($income_route, $url_part[1])) {
                    $dataGroup = ORM::for_table('crm_accounts_groups')->create();
                    $dataGroup->crm_accounts_id = $cid;
                    $dataGroup->crm_group_id = 1;
                    $dataGroup->save();
                }
            }

            //salva o endereço do contato
            $address = ORM::for_table('crm_accounts_address')->create();
            //recebe os dados do endereço
            if (intval(_post('state'))) {
                $address->state_id = _post('state');
            }

            if (intval(_post('city')) > 0) {
                $address->city_id = _post('city');
            }
            $address->zip = _post('zip');
            $address->address = _post('address');
            $address->neighborhood = _post('neighborhood');
            $address->number = _post('number');
            $address->complement = _post('complement');
            $address->reference = _post('reference');
            $address->type_address = "tax_address";
            $address->crm_account_id = $cid;
            $address->save();

            //salva endereço de cobrança Billing Address
            $address_c = ORM::for_table('crm_accounts_address')->create();
            //recebe os dados da div de endereço de cobrança
            if (intval(_post('state_c')) > 0) {
                $address_c->state_id = _post('state_c');
            }
            if (intval(_post('city_c')) > 0) {
                $address_c->city_id = _post('city_c');
            }
            $address_c->zip = _post('zip_c');
            $address_c->address = _post('address_c');
            $address_c->neighborhood = _post('neighborhood_c');
            $address_c->number = _post('number_c');
            $address_c->complement = _post('complement_c');
            $address_c->reference = _post('reference_c');
            $address_c->type_address = "billing_address";
            $address_c->crm_account_id = $cid;
            $address_c->save();

            //se pessoa jurídica adiciona os contatos
            if ($d->kind_of_person == 'PJ') {
                if (isset($_POST['contacts'])) {
                    $contacts = $_POST['contacts'];
                    foreach ($contacts as $c) {
                        $dadosContact = ORM::for_table('crm_accounts_contacts')->create();
                        $dadosContact->crm_accounts_id = $cid;
                        $dadosContact->crm_accounts_id_contact = $c;
                        $dadosContact->save();
                    }
                }
            }

            //now add custom fields
            $fs = ORM::for_table('crm_customfields')->where('ctype', 'crm')->order_by_asc('id')->find_many();
            foreach ($fs as $f) {
                $fvalue = _post('cf' . $f['id']);
                $fc = ORM::for_table('crm_customfieldsvalues')->create();
                $fc->fieldid = $f['id'];
                $fc->relid = $cid;
                $fc->fvalue = $fvalue;
                $fc->save();
            }
            //

            Event::trigger('contacts/add-post/_on_finished');

            // send welcome email if needed

            $send_client_signup_email = _post('send_client_signup_email');


            if (($d->email != '') && ($send_client_signup_email == 'Yes') && ($u_password != '')) {

                $email_data = array();
                $email_data['account'] = $d->account;
                $email_data['company'] = $d->company;
                $email_data['password'] = $u_password;
                $email_data['email'] = $d->email;

                $send_email = Ib_Email::send_client_welcome_email($email_data);
            }



            echo $cid;
        } else {
            echo $msg;
        }
        break;

    case 'list':

        Event::trigger('contacts/list/');

        //  $ui->assign('_st', $_L['Contacts'].'<span class="pull-right"><a href="'.U.'contacts/set_view_mode/card/'.'"><i class="fa fa-th"></i></a> <a href="'.U.'contacts/set_view_mode/tbl/'.'"><i class="fa fa-align-justify"></i></a> <a href="'.U.'contacts/set_view_mode/search/'.'"><i class="fa fa-search"></i></a></span>');
//        $ui->assign('_st', $_L['Contacts'].' <div class="btn-group pull-right" style="padding-right: 10px;">
//  <a class="btn btn-success btn-xs" href="'.U.'contacts/set_view_mode/card/'.'" style="box-shadow: none;"><i class="fa fa-th"></i></a>
//  <a class="btn btn-primary btn-xs" href="'.U.'contacts/set_view_mode/tbl/'.'" style="box-shadow: none;"><i class="fa fa-align-justify"></i></a>
//  <a class="btn btn-success btn-xs" href="'.U.'contacts/set_view_mode/search/'.'" style="box-shadow: none;"><i class="fa fa-search"></i></a>
//  <a class="btn btn-primary btn-xs" href="'.U.'contacts/export_csv/'.'" style="box-shadow: none;"><i class="fa fa-download"></i></a>
//  <a class="btn btn-success btn-xs" href="'.U.'contacts/import_csv/'.'" style="box-shadow: none;"><i class="fa fa-upload"></i></a>
//</div>');

        $name = _post('name');
        $dir = "application/plugins/module_hr";

        // Filtro por Grupo de Contatos
//        $filter['type'] = _post('type');


        //find all tags
        $t = ORM::for_table('sys_tags')->where('type', 'contacts')->find_many();
        $ui->assign('t', $t);

        $mode_css = '';
        $mode_js = '';

        if ($config['contact_set_view_mode'] == 'search') {
            
            // Foo Table

            $mode_css = Asset::css(array('../../application/plugins/module_hr/assets/css/default',
                                    's2/css/select2.min'));

            $mode_js = Asset::js(array(
                's2/js/select2.min',
//                'footable/js/footable.all.min', 
//                'contacts/mode_search', 
                '../../application/plugins/module_hr/assets/js/list'));


            $filter = array();
            $filter['items_per_page'] = 10;
            
            if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                $filter['search'] = filter_var(_post('search'), FILTER_SANITIZE_STRING);
                $filter['items_per_page'] = filter_var(_post('items_per_page'), FILTER_SANITIZE_STRING);
                $filter['type'] = filter_var(_post('type'), FILTER_SANITIZE_STRING);
            } else {
                if ($i = array_search('search', $routes))
                    $filter['search'] = filter_var($routes[$i + 1], FILTER_SANITIZE_STRING);
                if ($i = array_search('items_per_page', $routes))
                    $filter['items_per_page'] = filter_var($routes[$i + 1], FILTER_SANITIZE_STRING);
                if ($i = array_search('type', $routes))
                    $filter['type'] = filter_var($routes[$i + 1], FILTER_SANITIZE_STRING);
            }
            
            $select = "SELECT 
                        c.*
                    FROM
                        crm_accounts as c";
            
            // Filtro pelo grupo
            $select_join = '';
            if (isset($filter['type']) && $filter['type'] > 0) 
            {
                $select_join = ' JOIN crm_accounts_groups as cg ON cg.crm_group_id = '.$filter['type'].' AND cg.crm_accounts_id = c.id';
            }
            
            $where = "";
            // Filtro pelo campo de busca
            if (isset($filter['search']) && $filter['search'] != '') {
                $where .= " WHERE (c.account LIKE '%" . $filter['search'] . "%' 
                            OR c.company LIKE '%" . $filter['search'] . "%' 
                            OR c.code LIKE '%" . $filter['search'] . "%' 
                            OR c.cpf_cnpj LIKE '%" . $filter['search'] . "%')";
            }
            
            // Pego a query
            $group_by = " ";
            $order_by = " ORDER BY c.account ASC ";
            $query = $select . $select_join. $where . $group_by . $order_by;
            
            // pego o filtro
            if ($filter['items_per_page'] != 'all')
                $filter['items_per_page'] = ($filter['items_per_page'] > 0) ? $filter['items_per_page'] : 10;
            
            // pego a pagina atual
            $page = isset($routes['2']) ? $routes['2'] : 1;
            
            // pego o total de registros
            $select_count = "SELECT 
                                COUNT(c.id) as count
                            FROM
                                crm_accounts as c";
            $query_count = $select_count . $select_join . $where;
            $totalItems = ORM::for_table('crm_accounts')->raw_query($query_count)->find_one()->count;
            
            $paginator = new ModulePaginator('crm_accounts', $query, $filter);
            $d = $paginator->setItemsPerPage($filter['items_per_page'])
                    ->setCurrentPageNumber($page)
                    ->setTotalItems($totalItems)
                    ->run();
            
            // pego o nome do grupo
            if(isset($filter['type']) && $filter['type'] > 0)
            {
                $grupo = ORM::for_table('crm_groups')->find_one($filter['type']);
                $ui->assign('filter_grupo', $grupo->gname);
            }
            
        } elseif ($name != '') {
            $paginator = Paginator::bootstrap('crm_accounts', 'account', '%' . $name . '%');
            $d = ORM::for_table('crm_accounts')->where_like('account', '%' . $name . '%')->offset($paginator['startpoint'])->limit($paginator['limit'])->order_by_desc('id')->find_many();
        } elseif (isset($routes[2]) AND ( $routes[2]) != '' AND ( !is_numeric($routes[2]))) {
            $tags = $routes[2];
            $paginator['contents'] = '';
            $d = ORM::for_table('crm_accounts')->where_like('tags', '%' . $tags . '%')->order_by_desc('id')->find_many();
        } else {
            $paginator = Paginator::bootstrap('crm_accounts');
            $d = ORM::for_table('crm_accounts')->offset($paginator['startpoint'])->limit($paginator['limit'])->order_by_desc('id')->find_many();
        }
        
        // pego os grupos de contatos
        $grupos = ORM::for_table('crm_groups')->find_many();
        $ui->assign('grupos', $grupos);
        
        $bottomBar[] = array('type' => 'int', 'info' => 'Quantidade', 'value' => $totalItems);
        $ui->assign('bottomBar', $bottomBar);
        
        $ui->assign('filter', $filter);

        $ui->assign('d', $d);
        $ui->assign('paginator', $paginator);

        $ui->assign('xheader', $mode_css);


        $ui->assign('xfooter', $mode_js .
                '
<script type="text/javascript" src="' . $_theme . '/lib/list-contacts.js"></script>

');
        $ui->assign('jsvar', '
_L[\'are_you_sure\'] = \'' . $_L['are_you_sure'] . '\';
 ');
        $ui->display('list-contacts.tpl');

        break;

    case 'edit-address-post':
        $cid = _post('fcid');
        $d = ORM::for_table('crm_accounts')->find_one($cid);
        if ($d) {
            //atualiza a informação do contato par ao endereço
            $d->billing_address = empty(_post('billing_address')) ? 'N' : 'Y';
            $d->save();
            //salva o endereço do contato
            $address = ORM::for_table('crm_accounts_address')->where('crm_account_id', $cid)->where('type_address', 'tax_address')->find_many();

            //recebe os dados do endereço
            if (intval(_post('state'))) {
                $address[0]->state_id = _post('state');
            } else {
                $address[0]->state_id = null;
            }

            if (intval(_post('city')) > 0) {
                $address[0]->city_id = _post('city');
            } else {
                $address[0]->city_id = null;
            }
            $address[0]->zip = _post('zip');
            $address[0]->address = _post('address');
            $address[0]->neighborhood = _post('neighborhood');
            $address[0]->number = _post('number');
            $address[0]->complement = _post('complement');
            $address[0]->save();

            //salva endereço de cobrança Billing Address
            $address_c = ORM::for_table('crm_accounts_address')->where('crm_account_id', $cid)->where('type_address', 'billing_address')->find_many();
            //recebe os dados da div de endereço de cobrança
            if (intval(_post('state_c')) > 0) {
                $address_c[0]->state_id = _post('state_c');
            } else {
                $address_c[0]->state_id = null;
            }
            if (intval(_post('city_c')) > 0) {
                $address_c[0]->city_id = _post('city_c');
            } else {
                $address_c[0]->city_id = null;
            }
            $address_c[0]->zip = _post('zip_c');
            $address_c[0]->address = _post('address_c');
            $address_c[0]->neighborhood = _post('neighborhood_c');
            $address_c[0]->complement = _post('complement_c');
            $address_c[0]->number = _post('number_c');
            $address_c[0]->save();
            //_msglog('s', $_L['account_updated_successfully']);
            echo $cid;
        } else {
            echo $_L['Not found'];
        }

        break;

    case 'edit-post':

        Event::trigger('contacts/edit-post/');


        $cid = _post('fcid');
        $d = ORM::for_table('crm_accounts')->find_one($cid);
        if ($d) {

            $old_account = $d->account;
            $d->account = _post('account');
            $d->kind_of_person = _post('kind_of_person');
            $d->company = _post('company');
            $d->code = _post('code');
            $d->rg = _post('rg');
            $d->foreign_doc_identification = _post('foreign_doc_identification');
            $d->taxpayer = _post('taxpayer');
            $d->ie = _post('ie');
            $d->im = _post('im');
            $d->email = _post('email');
            $d->email_nfe = _post('email_nfe');
            $d->phone = _post('phone');
            $d->fax = _post('fax');
            $d->cell_phone = _post('cell_phone');
            $d->web_site = _post('web_site');
            $d->currency = _post('currency');
            $d->country = _post('country');
            $d->notes = _post('notes');
            $d->marital_status = _post('marital_status');
            $d->jobtitle = _post('jobtitle');
            $d->sex = _post('sex');
            if (!empty(_post('date_of_birth'))) {
                $d->date_of_birth = _post('date_of_birth');
            }
            $d->naturalness = _post('naturalidade');
            $d->father_name = _post('father_name');
            $d->father_cpf = _post('father_cpf');
            $d->mother_name = _post('mother_name');
            $d->mother_cpf = _post('mother_cpf');
            $d->crt = _post('crt');
            $d->inscription_suframa = _post('inscription_suframa');
            $d->billing_address = empty(_post('billing_address')) ? 'N' : 'Y';
            if (intval(_post('salesman_id')) > 0) {
                $d->salesman_id = _post('salesman_id');
            }
            $d->payment_condition = _post('payment_condition');
            $d->status_crm = _post('status_crm');
            if (intval(_post('segment')) > 0) {
                $d->segment_id = _post('segment');
            }
            //recebe o valor e pssa para o método de fincas formatar adequadamente para registrar no BD
            $credit = _post('credit_limit');
            $d->credit_limit = Finance::amount_fix($credit);

            $msg = '';

            if ($d->kind_of_person == 'PJ') {
                $d->cpf_cnpj = _post('cnpj');
                $cpfCnpjTipo = 'CNPJ';
                $d->country = 'Brazil';
            } else if ($d->kind_of_person == 'PF') {
                $d->cpf_cnpj = _post('cpf');
                $cpfCnpjTipo = 'CPF';
                $d->country = 'Brazil';
            } else {
                $d->cpf_cnpj = "";
            }

            if ($d->currency == '') {
                $d->currency = '0';
            }

            if (isset($_POST['tags']) AND ( $_POST['tags']) != '') {
                $tags = $_POST['tags'];
            } else {
                $tags = '';
            }

            //check if tag is already exisit
            if ($d->account == '') {
                $msg .= $_L['Account Name is required'] . ' <br>';
            }

            if ($d->email != '') {
                if (Validator::Email($d->email) == false) {
                    $msg .= $_L['Invalid Email'] . ' <br>';
                }
                $f = ORM::for_table('crm_accounts')->where('email', $d->email)
                        ->where_not_equal('id', intval($cid))
                        ->find_one();

                if ($f) {
                    $msg .= $_L['Email already exist'] . ' <br>';
                }
            }

            if ($d->email_nfe != '') {
                if (Validator::Email($d->email_nfe) == false) {
                    $msg .= $_L['Invalid Email Nfe'] . ' <br>';
                }
            }

            if ($d->kind_of_person != 'E' && $d->cpf_cnpj != '') {

                $f = ORM::for_table('crm_accounts')->where('cpf_cnpj', $d->cpf_cnpj)
                        ->where_not_equal('id', intval($cid))
                        ->find_one();
                if ($f) {
                    $msg .= $_L[$cpfCnpjTipo . ' number already exist'] . ' <br>';
                }
            }
            if ($d->kind_of_person == 'E') {
                if ($d->foreign_doc_identification != '') {
                    $f = ORM::for_table('crm_accounts')->where('foreign_doc_identification', $d->foreign_doc_identification)->find_one();
                    if ($f) {
                        $msg .= $_L['Identification Document Foreigner number already exist'] . ' <br>';
                    }
                }
            }

            $password = _post('password');

            //valida tamanho da senha
            if ($password != '') {
                if (!Validator::Length($password, 15, 5)) {
                    $msg .= $_L['Password should be between 6 to 15 characters'] . '<br>';
                }
            }


            if ($msg == '') {
                //  Tags::save($tags, 'Contacts');
                $d->tags = Arr::arr_to_str($tags);

                //others
                $d->password = $password;
                $d->fname = '';
                $d->lname = '';
                $d->cid = '0';
                $d->o = '0';
                $d->balance = '0.00';
                $d->status = 'Active';
                $d->token = '';
                $d->ts = '';
                $d->img = '';
                $d->web = '';
                $d->facebook = '';
                $d->google = '';
                $d->linkedin = '';

                //
                $d->save();
                //remove todos os grupos
                ORM::for_table('crm_accounts_groups')->where('crm_accounts_id', $cid)->delete_many();
                //salva os grupos para o Contato
                if (isset($_POST['group'])) {
                    $group = $_POST['group'];
                    if (!empty($group)) {
                        foreach ($group as $g) {
                            $dataGroup = ORM::for_table('crm_accounts_groups')->create();
                            $dataGroup->crm_accounts_id = $cid;
                            $dataGroup->crm_group_id = $g;
                            $dataGroup->save();
                        }
                    }
                }


                //salva o endereço do contato
                $address = ORM::for_table('crm_accounts_address')->where('crm_account_id', $cid)->where('type_address', 'tax_address')->find_many();
                if(count($address) == 0)
                {
                    $address[0] = ORM::for_table('crm_accounts_address')->create();
                    $address[0]->crm_account_id = $cid;
                    $address[0]->type_address = "tax_address";
                }
                
                //recebe os dados do endereço
                if (intval(_post('state'))) {
                    $address[0]->state_id = _post('state');
                } else {
                    $address[0]->state_id = null;
                }

                if (intval(_post('city')) > 0) {
                    $address[0]->city_id = _post('city');
                } else {
                    $address[0]->city_id = null;
                }
                $address[0]->zip = _post('zip');
                $address[0]->address = _post('address');
                $address[0]->neighborhood = _post('neighborhood');
                $address[0]->number = _post('number');
                $address[0]->complement = _post('complement');
                $address[0]->save();

                //salva endereço de cobrança Billing Address
                $address_c = ORM::for_table('crm_accounts_address')->where('crm_account_id', $cid)->where('type_address', 'billing_address')->find_many();
                if(count($address_c) == 0)
                {
                    $address_c[0] = ORM::for_table('crm_accounts_address')->create();
                    $address_c[0]->crm_account_id = $cid;
                    $address_c[0]->type_address = "tax_address";
                }
                
                //recebe os dados da div de endereço de cobrança
                if (intval(_post('state_c')) > 0) {
                    $address_c[0]->state_id = _post('state_c');
                } else {
                    $address_c[0]->state_id = null;
                }
                if (intval(_post('city_c')) > 0) {
                    $address_c[0]->city_id = _post('city_c');
                } else {
                    $address_c[0]->city_id = null;
                }
                $address_c[0]->zip = _post('zip_c');
                $address_c[0]->address = _post('address_c');
                $address_c[0]->neighborhood = _post('neighborhood_c');
                $address_c[0]->complement = _post('complement_c');
                $address_c[0]->number = _post('number_c');
                $address_c[0]->save();

                //remove todos antes
                ORM::for_table('crm_accounts_contacts')->where('crm_accounts_id', $cid)->delete_many();
                //se pessoa jurídica adiciona os contatos
                if ($d->kind_of_person == 'PJ') {
                    if (isset($_POST['contacts'])) {
                        $contacts = $_POST['contacts'];
                        foreach ($contacts as $c) {
                            $dadosContact = ORM::for_table('crm_accounts_contacts')->create();
                            $dadosContact->crm_accounts_id = $cid;
                            $dadosContact->crm_accounts_id_contact = $c;
                            $dadosContact->save();
                        }
                    }
                }
                //delete existing records
                $exf = ORM::for_table('crm_customfieldsvalues')->where('relid', $cid)->delete_many();
                $fs = ORM::for_table('crm_customfields')->order_by_asc('id')->find_many();
                foreach ($fs as $f) {
                    $fvalue = _post('cf' . $f['id']);
                    $fc = ORM::for_table('crm_customfieldsvalues')->create();
                    $fc->fieldid = $f['id'];
                    $fc->relid = $cid;
                    $fc->fvalue = $fvalue;
                    $fc->save();
                }

                // check account name changed

                if ($d->account != $old_account) {

                    // change invoice account
//                    $inv = ORM::for_table('sys_invoices')->where('account',$old_account);
//                    $inv->account = $account;
//                    $inv->save();

                    $sql = "update sys_invoices set account='$d->account' where account='$old_account'";

                    ORM::execute($sql);
                }

                _msglog('s', $_L['account_updated_successfully']);

                echo $cid;
            } else {
                echo $msg;
            }
        } else {
            r2(U . $myCtrl . '/list', 'e', $_L['Account_Not_Found']);
        }

        break;
    case 'delete':

        Event::trigger('contacts/delete/');


        $id = $routes['2'];
        if ($_app_stage == 'Demo') {
            r2(U . $myCtrl . '/list/', 'e', 'Sorry! Deleting Account is disabled in the demo mode.');
        }
        $d = ORM::for_table('crm_accounts')->find_one($id);
        if ($d) {
            $d->delete();
            r2(U . $myCtrl . '/list/', 's', $_L['account_delete_successful']);
        }

        break;


    case 'more':

        Event::trigger('contacts/more/');

        $cid = _post('cid');
        $d = ORM::for_table('crm_accounts')->find_one($cid);
        if ($d) {
            $ui->assign('countries', Countries::all($d['country']));
            $ui->assign('d', $d);
            $ui->display('ajax.contact-more.tpl');
        } else {
            
        }


        break;

    case 'edit-more':

        Event::trigger('contacts/edit-more/');

        $id = _post('cid');
        $d = ORM::for_table('crm_accounts')->find_one($id);
        if ($d) {
            $img = _post('picture');
            $facebook = _post('facebook');
            $google = _post('google');
            $linkedin = _post('linkedin');

            $msg = '';



            //check email already exist





            if ($msg == '') {


                $d = ORM::for_table('crm_accounts')->find_one($id);

                $d->img = $img;
                $d->facebook = $facebook;
                $d->google = $google;
                $d->linkedin = $linkedin;
                $d->save();
                echo $d->id();
            } else {
                echo $msg;
            }
        } else {
            r2(U . $myCtrl . '/list/', 'e', $_L['Account_Not_Found']);
        }


        break;


    case 'edit-notes':

        Event::trigger('contacts/edit-notes/');

        $id = _post('cid');
        $d = ORM::for_table('crm_accounts')->find_one($id);
        if ($d) {

            $notes = _post('notes');

            $msg = '';



            //check email already exist





            if ($msg == '') {


                $d = ORM::for_table('crm_accounts')->find_one($id);


                $d->notes = $notes;
                $d->save();
                echo $d->id();
            } else {
                echo $msg;
            }
        } else {
            r2(U . $myCtrl . '/list/', 'e', $_L['Account_Not_Found']);
        }


        break;

    case 'render-address':

        Event::trigger('contacts/render-address/');
        //adequado para emissao da nota, e ajuste em pedido
        $cid = _post('cid');
        if (!empty($cid)) {
            $dadosCliente = ORM::for_table('crm_accounts')->find_one($cid);
            if ($dadosCliente->billing_address == 'Y') {
                $account_address = ORM::for_table('crm_accounts_address')->where('crm_account_id', $cid)->where('type_address', 'billing_address')->find_many();
            } else {
                $account_address = ORM::for_table('crm_accounts_address')->where('crm_account_id', $cid)->where('type_address', 'tax_address')->find_many();
            }

            if (count($account_address) > 0) {
                $state = "";
                $city = "";
                if (intval($account_address[0]->state_id) >= 1) {
                    $dadosEstadoCliente = ORM::for_table('state')->find_one($account_address[0]->state_id);
                    $state = $dadosEstadoCliente->state_name;
                }
                if (intval($account_address[0]->city_id) >= 1) {
                    $dadosCidadeCliente = ORM::for_table('city')->find_one($account_address[0]->city_id);
                    $city = $dadosCidadeCliente->city_name;
                }

                $address = $account_address[0]['address'];
                $zip = $account_address[0]['zip'];
                $country = $dadosCliente['country'];
                if (empty($state) && empty($city) && empty($address) && empty($zip)) {
                    echo "";
                } else {
                    echo
                    "$address " . $account_address[0]['number'] . " " . $account_address[0]['complement'] . "
$city
$state $zip
$country
";
                }
            } else {
                echo $_L['Address not found'];
            }
        }
        break;
    case 'all-address':

        Event::trigger('contacts/render-address/');
        //adequado para emissao da nota, e ajuste em pedido
        $cid = _post('cid');
        if (!empty($cid)) {
            $dadosCliente = ORM::for_table('crm_accounts')->find_one($cid);


            $address = ORM::for_table('crm_accounts_address')
                    ->table_alias('a')
                    ->select('a.*')
                    ->select('s.state_name', 'state')
                    ->select('c.city_name', 'city')
                    ->left_outer_join('state', array('s.id', '=', 'a.state_id'), 's')
                    ->left_outer_join('city', array('c.id', '=', 'a.city_id'), 'c')
                    ->where('a.crm_account_id', $dadosCliente['id'])
                    ->order_by_asc('a.type_address')
                    ->find_many();
            $data = array();
            foreach ($address as $a) {
                if (!empty($a->state) && !empty($a->city) && !empty($a->zip)) {
                    $data[] = array(
                        'status' => 'OK',
                        'billing_address' => $dadosCliente->billing_address,
                        'type_address' => $a->type_address,
                        'address' => $a->address,
                        'number' => $a->number,
                        'complement' => $a->complement,
                        'city' => $a->city,
                        'zip' => $a->zip,
                        'state' => $a->state,
                        'country' => $dadosCliente['country'],
                    );
                } else {
                    $data[] = array(
                        'status' => '',
                        'billing_address' => '',
                        'type_address' => '',
                        'address' => '',
                        'number' => '',
                        'complement' => '',
                        'city' => '',
                        'zip' => '',
                        'state' => '',
                        'country' => '',
                    );
                }
            }
            header('Content-Type: application/json');
            echo json_encode($data);
        } else {
            echo $_L['Not found'];
        }

        break;


    case 'send_email':

        Event::trigger('contacts/send_email/');

        $msg = '';
        $cid = _post('cid');
        $d = ORM::for_table('crm_accounts')->find_one($cid);
        $email = $d['email'];
        $toname = $d['account'];
        $subject = _post('subject');
        if ($subject == '') {
            $msg .= $_L['Subject is Empty'] . ' <br>';
        }
        $message = $_POST['message'];
        if ($message == '') {
            $msg .= $_L['Message is Empty'] . ' <br>';
        }
        if ($msg == '') {
            //send email
            Notify_Email::_send($toname, $email, $subject, $message, $cid);
            echo $cid;
        } else {
            echo $msg;
        }
        break;


    case 'modal_add':

        Event::trigger('contacts/modal_add/');

        $ui->assign('countries', Countries::all($config['country'])); // may add this $config['country_code']
        //lista de campos extras
        $fs = ORM::for_table('crm_customfields')->where('ctype', 'crm')->order_by_asc('id')->find_many();
        $ui->assign('fs', $fs);
        if ($routes[2] == 'NOT_PJ') {
            $ui->assign('showPj', 'false');
        } else {
            $ui->assign('showPj', 'true');
        }
        $currencies = Model::factory('Models_Currency')->find_array();

        $ui->assign('currencies', $currencies);

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

        $ui->display('modal_add_contact.tpl');


        break;
    case 'modal_busca_cnpj':
        $ui->display('modal_find_cnpj.tpl');
        break;

    case 'modal_modal_busca_cnpj':
        $ui->display('modal_modal_find_cnpj.tpl');
        break;

    case 'set_view_mode':

        Event::trigger('contacts/set_view_mode/');

//        if(isset($routes['2']) AND ($routes['2'] != 'tbl')){
//            $mode = 'card';
//        }
//        else{
//            $mode = 'tbl';
//        }

        if (isset($routes[2]) AND ( $routes[2] != '')) {
            $mode = $routes['2'];
        } else {
            $mode = 'tbl';
        }

        $available_mode = array("tbl", "card", "search");
        if (in_array($mode, $available_mode)) {

            update_option('contact_set_view_mode', $mode);
        }

        r2(U . 'contacts/list/');

        break;



    case 'export_csv':


        $fileName = 'contacts_' . time() . '.csv';

        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header('Content-Description: File Transfer');
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename={$fileName}");
        header("Expires: 0");
        header("Pragma: public");

        $fh = @fopen('php://output', 'w');

        $headerDisplayed = false;

        // $results = ORM::for_table('crm_Accounts')->find_array();
        $results = db_find_array('crm_accounts', array('id', 'account', 'company', 'phone', 'email', 'country', 'balance', 'tags'));

        foreach ($results as $data) {
            // Add a header row if it hasn't been added yet
            if (!$headerDisplayed) {
                // Use the keys from $data as the titles
                fputcsv($fh, array_keys($data));
                $headerDisplayed = true;
            }

            // Put the data into the stream
            fputcsv($fh, $data);
        }
// Close the file
        fclose($fh);



        break;



    case 'dev_demo_data':


        // this only work with dev mode
        is_dev();





        break;

    case 'import_csv':


        $ui->assign('xheader', Asset::css(array('dropzone/dropzone')));


        $ui->assign('xfooter', Asset::js(array('dropzone/dropzone', 'contacts/import')));



        $ui->display('contacts_import.tpl');



        break;

    case 'csv_upload':

        $uploader = new Uploader();
        $uploader->setDir('application/storage/temp/');
        // $uploader->sameName(true);
        $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
        }


        break;

    case 'csv_uploaded':
        if (isset($_SESSION['uploaded'])) {

            $uploaded = $_SESSION['uploaded'];

            // estancio a classe dos Correios para pegar o endereço pelo CEP
            require('application/lib/correios/Correios.php');

            // _msglog('s',$uploaded);
//            $csvData = file_get_contents('application/storage/temp/'.$uploaded);
//            $lines = explode(PHP_EOL, $csvData);
//            $contacts = array();
//            foreach ($lines as $line) {
//                $contacts[] = str_getcsv($line);
//            }

            $csv = new parseCSV();
            $csv->auto('application/storage/temp/' . $uploaded);

            $contacts = $csv->data;



            $cn = 0;

            foreach ($contacts as $contact) {

                $data = array();
                $data['account'] = $contact['Nome ou Razão Social'];
                $data['email'] = (isset($contact['Email'])) ? $contact['Email'] : '';
                $data['phone'] = (isset($contact['Telefone'])) ? $contact['Telefone'] : '';
                $data['company'] = (isset($contact['Nome Fantasia'])) ? $contact['Nome Fantasia'] : '';

                // Pego o endereço pelo CEP
                $data_address = array();
                $data['zip'] = (isset($contact['CEP'])) ? $contact['CEP'] : '';
                if ($data['zip']) {
                    $zip = preg_replace('/\D/', '', $data['zip']);
                    $data_address = Correios::getEndereco($zip);
                    if ($data_address) {
                        //busca a cidade
                        $state = ORM::for_table('state')->select('id')
                                ->where_raw('uf_state = "' . $data_address['state'] . '"')
                                ->find_one();

                        $city_aux = str_replace('\'', '\\\'', $data_address['city']);

                        $city = ORM::for_table('city')->select('id')->select('city_name')->select('id_state')
                                        ->where_raw("city_name like '" . $city_aux . "' AND id_state = " . $state->id)->find_one();
                        //carrega os dados
                        $data_address['city_id'] = ($city) ? $city->id : '';
                        $data_address['state_id'] = ($city) ? $city->id_state : '';
                        $data_address['complement'] = (isset($contact['Endereço Complemento'])) ? $contact['Endereço Complemento'] : '';
                        $data_address['number'] = (isset($contact['Endereço Número'])) ? $contact['Endereço Número'] : '';
                        $data_address['status'] = 'SUCCESS';
                    } else {
                        //valida para as mensagens de erro
                        if (count($zip != 8)) {
                            $data_address['status'] = $_L['Could not retrieve zip code data. Reason: SEARCH AS DEFINED AS EXACT, ZIP SHOULD BE 8 DIGITS'];
                        } else {
                            //mensagem caso não tenha encontrado o cep
                            $data_address['status'] = $_L['Could not retrieve zip code data.Reason: ZIP NOT FOUND'];
                        }
                    }
                }
                $data['address'] = $data_address;
                $data['code'] = (isset($contact['Código'])) ? $contact['Código'] : '';
                $data['kind_of_person'] = (isset($contact['Pessoa Física ou Jurídica'])) ? $contact['Pessoa Física ou Jurídica'] : '';
                $data['cpf_cnpj'] = (isset($contact['CPF ou CNPJ'])) ? $contact['CPF ou CNPJ'] : '';
                $data['rg'] = (isset($contact['RG'])) ? $contact['RG'] : '';
                $data['im'] = (isset($contact['Inscrição Municipal'])) ? $contact['Inscrição Municipal'] : '';
                $data['ie'] = (isset($contact['Inscrição Estadual'])) ? $contact['Inscrição Estadual'] : '';
                $data['cell_phone'] = (isset($contact['Celular'])) ? $contact['Celular'] : '';
                $data['date_of_birth'] = (isset($contact['Data de Nascimento'])) ? $contact['Data de Nascimento'] : '';
                $data['status'] = 'Active';

                // verifico o grupo
                $data['cliente'] = (isset($contact['Cliente'])) ? $contact['Cliente'] : '';
                $data['fornecedor'] = (isset($contact['Fornecedor'])) ? $contact['Fornecedor'] : '';

                $save = Contacts::add($data);

                if (is_numeric($save)) {

                    $cn++;
                }
            }


            _msglog('s', $cn . ' Contacts Imported');

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

            _msglog('e', 'An Error Occurred while uploading the files');
        }


        break;
        
    case 'prodoctor_import':

        
        // conecto no postgres do Prodoctor
        
        @ini_set('memory_limit', '11512M');
        @ini_set('max_execution_time', 0);
        @set_time_limit(0);
                
        define('PRODOCT_BD',"host=192.168.0.200 port=5432 dbname=prodoctorplussql user=postgres password=masterkey");
        $pg_connect = pg_connect(PRODOCT_BD);
        $query = "SELECT "
                . "tp.cor, "
                . "tp.codigo, "
                . "tp.nome,"
                . "tp.datanascimento,"
                . "tp.r_logradouro,"
                . "tp.r_numero,"
                . "tp.r_complemento,"
                . "tp.r_bairro,"
                . "tp.r_cidade,"
                . "tp.r_uf,"
                . "tp.r_cep,"
                . "tp.telefone_1,"
                . "tp.telefone_2,"
                . "tp.correioeletronico,"
                . "tp.sexo,"
                . "tp.identidade,"
                . "tp.cpf,"
                . "tp.datacadastro,"
                . "tp.conveniopadrao,"
                . "tp.convenio_1,"
                . "tp.plano_1,"
                . "tp.numeromatricula_1,"
                . "tp.validade_1,"
                . "tp.titular_1,"
                . "tp.pai_nome,"
                . "tp.pai_datanascimento,"
                . "tp.mae_nome,"
                . "tp.mae_datanascimento,"
                . "tp.pendencias,"
                . "tp.observacoes,"
                . "tp.foto,"
                . "ic.nome as cidade, "
                . "ie.nome as estado, "
                . "tc.nome as convenio "
                . "FROM t_pacientes as tp "
                . "LEFT JOIN ibge_cidades as ic ON ic.codigo = tp.r_cidade "
                . "LEFT JOIN ibge_estados as ie ON ie.codigo = tp.r_uf "
                . "LEFT JOIN t_convenios as tc ON tc.codigo = tp.convenio_1 "
                . "ORDER BY tp.codigo ";
                
//                $query = "SELECT * FROM t_pacientes WHERE codigo = 20196 LIMIT 10";
//                $query = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'";
//                
//                $query = "SELECT * FROM ibge_cidades LIMIT 10";
//                $query = "SELECT * FROM t_convenios LIMIT 100";
        $pg_query       = pg_query($query);

//                $count_user = pg_num_rows($pg_query);  

        $arr_user = pg_fetch_all($pg_query);
//        var_dump($arr_user);exit;

        $cn = 0;

        foreach ($arr_user as $contact) {
            
//            echo $contact['codigo'].'<br>';exit;
            
            $d = ORM::for_table('crm_accounts')
                ->select('*')
                ->where('id', $contact['codigo'])
                ->find_one();
            
            if($d->id > 0)
            {
                continue;
            }
            
            $data = array();
            $data['account'] = $contact['nome'];
            $data['email'] = (isset($contact['correioeletronico'])) ? $contact['correioeletronico'] : '';
            $data['phone'] = (isset($contact['telefone_1'])) ? preg_replace('/\D/', '', $contact['telefone_1']) : '';

            // Pego o endereço pelo CEP
            $data_address = array();
            $data['zip'] = (isset($contact['r_cep'])) ? $contact['r_cep'] : '';
            
            $zip = preg_replace('/\D/', '', $data['zip']);

            $state = null;
            $city = null;
            if(isset($contact['r_uf']) && intval($contact['r_uf']) > 0)
            {
                $state = ORM::for_table('state')->select('id')
                        ->where_raw('code_state = "' . $contact['r_uf'] . '"')
                        ->find_one();
                
                if(isset($contact['r_cidade']) && intval($contact['r_cidade']) > 0)
                {
                    $city = ORM::for_table('city')->select('id')->select('city_name')->select('id_state')
                                ->where_raw("city_ibge = '" . $contact['r_cidade'] . "' AND id_state = " . $state->id)->find_one();
                }
            }
            
            //carrega os dados
            $data_address['city_id'] = ($city) ? $city->id : '';
            $data_address['state_id'] = ($city) ? $city->id_state : '';
            $data_address['complement'] = (isset($contact['r_complemento'])) ? $contact['r_complemento'] : '';
            $data_address['number'] = (isset($contact['r_numero'])) ? $contact['r_numero'] : '';
            $data_address['neighborhood'] = (isset($contact['r_bairro'])) ? $contact['r_bairro'] : '';
            $data_address['address'] = (isset($contact['r_logradouro'])) ? $contact['r_logradouro'] : '';
            $data_address['status'] = 'SUCCESS';
                
            
            $data['address'] = $data_address;
            
            
            $data['code'] = (isset($contact['codigo'])) ? $contact['codigo'] : '';
            
            $data['notes'] = $contact['pendencias']. (isset($contact['observacoes']) ? ' ### '.$contact['observacoes'] : '');
            
            $sexo = null;
            if(isset($contact['sexo']) && $contact['sexo'] != '')
            {
                if($contact['sexo'] == 1)
                {
                    $sexo = 'f';
                }
                elseif($contact['sexo'] == 0)
                {
                    $sexo = 'm';
                }
            }
            $data['sex'] = $sexo;
            $data['kind_of_person'] = 'PF';
            $data['cpf_cnpj'] = (isset($contact['cpf'])) ? $contact['cpf'] : '';
            $data['rg'] = (isset($contact['identidade'])) ? $contact['identidade'] : '';
            $data['cell_phone'] = (isset($contact['telefone_2'])) ? $contact['telefone_2'] : '';
            $data['date_of_birth'] = (isset($contact['datanascimento'])) ? $contact['datanascimento'] : '';
            $data['status'] = 'Active';

            // verifico o grupo
            $data['cliente'] = 1;
            $data['paciente'] = 1;
            $pacient_id = Contacts::prodoctorAdd($data);

            if (is_numeric($pacient_id)) 
            {
                // PEGO O CONVÊNIO
                if($contact['convenio'] != '' && $contact['convenio'] != 'PARTICULAR' && $contact['convenio'] != 'PARTIC UBS' && $contact['numeromatricula_1'] != '' && $contact['validade_1'] != '')
                {
                    $d = ORM::for_table('module_med_agreement')
                            ->table_alias('ma')
                            ->select('ma.*')
                            ->where('ma.agreement_company_name', $contact['convenio'])
                            ->find_one();

                    if($d->id > 0)
                    {
                        $convenio = ORM::for_table('module_med_agreement_patient')->create();
                        $convenio->module_med_agreement_id = $d->id;
                        $convenio->crm_accounts_id = $pacient_id;
                        $convenio->identification = $contact['numeromatricula_1'];
                        $convenio->expiration = $contact['validade_1'];
                        $convenio->plan = $contact['plano_1'];
                        $convenio->save();
                    }
                }
                $cn++;
            }
            
            
        }


        _msglog('s', $cn . ' Contacts Imported');

//            ob_start();
//            var_dump($contacts);
//            $result = ob_get_clean();
//
//            _msglog('s',$result);
        


        break;



    case 'groups':

        // find all groups

        $gs = ORM::for_table('crm_groups')->order_by_asc('sorder')->find_array();

        $ui->assign('gs', $gs);

        $ui->assign('xfooter', Asset::js(array('contacts/groups')));

        $ui->assign('jsvar', '
        _L[\'are_you_sure\'] = \'' . $_L['are_you_sure'] . '\';
         ');
        $ui->display('crm_groups.tpl');
        break;


    case 'add_group':

        $group_name = _post('group_name');

        if ($group_name != '') {

            //check same group already exist

            $c = ORM::for_table('crm_groups')->where('gname', $group_name)->find_one();

            if ($c) {
                ib_die($_L['A Group with same name already exist']);
            }

            $d = ORM::for_table('crm_groups')->create();
            $d->gname = $group_name;
            $d->color = '';
            $d->discount = '';
            $d->parent = '';
            $d->pid = 0;
            $d->exempt = '';
            $d->description = '';
            $d->separateinvoices = '';
            $d->sorder = 0;
            $d->c1 = '';
            $d->c2 = '';
            $d->c3 = '';
            $d->c4 = '';
            $d->c5 = '';
            $d->save();

            echo $d->id();
        } else {
            echo $_L['Group Name'] . $_L['is required'];
        }

        break;


    case 'find_by_group':

        $gid = route(2);

        if ($gid) {

            $g = ORM::for_table('crm_groups')->find_one($gid);

            if ($g) {

                $d = ORM::for_table('crm_accounts')
                                ->table_alias('c')
                                ->select('c.*')
                                ->left_outer_join('crm_accounts_groups', array('c.id', '=', 'g.crm_accounts_id'), 'g')
                                ->where('g.crm_group_id', $gid)
                                ->order_by_desc('id')->find_array();

                $ui->assign('d', $d);
                $ui->assign('gid', $gid);

                $ui->assign('xjq', ' $(".cdelete").click(function (e) {
        e.preventDefault();
        var id = this.id;
        bootbox.confirm("' . $_L['are_you_sure'] . '", function(result) {
           if(result){
               var _url = $("#_url").val();
               window.location.href = _url + "delete/crm-user/" + id + "/' . $gid . '/";
           }
        });
    });
');

                $ui->display('contacts_find_by_group.tpl');
            }
        }




        break;

    case 'group_edit':

        $id = _post('id');
        $id = str_replace('e', '', $id);
        $gname = _post('gname');
        //grupos fixos no sistema não pode editar. validação para ação


        $d = ORM::for_table('crm_groups')->find_one($id);

        if ($d) {

            if ($d->defauld) {
                _msglog('e', $_L['Fixed Group']);
                echo $_L['Fixed Group'];
            } else {
                // update all gname in contacts
                //  $o_gname = $d->gname;
                //  ORM::execute("update crm_accounts set gname='$gname' where gname='$o_gname'");

                $d->gname = $gname;

                $d->save();

                echo $d->id;
            }
        }

        break;

    case 'group_email':

        $gid = route(2);

        if ($gid) {

            // find group


            $ds = ORM::for_table('crm_accounts')->where('gid', $gid)->where_not_equal('email', '')->select('account')->select('email')->order_by_desc('id')->find_array();

            $ui->assign('ds', $ds);

            $ui->assign('xheader', Asset::css(array('s2/css/select2.min', 'sn/summernote', 'sn/summernote-bs3', 'sn/summernote-application')));




            $ui->assign('xfooter', Asset::js(array('s2/js/select2.min', 's2/js/i18n/' . lan(), 'sn/summernote.min', 'contacts/group_email')));
            $ui->display('contacts_group_email.tpl');
        }


        break;


    case 'group_email_post':


//        $recipients = array(
//            'person1@domain.com' => 'Person One',
//            'person2@domain.com' => 'Person Two',
//            // ..
//        );
//        foreach($recipients as $email => $name)
//        {
//            $mail->AddAddress($email, $name);
//        }



        $emails = $_POST['emails'];
        $subject = $_POST['subject'];
        $msg = $_POST['msg'];


        Ib_Email::bulk_email($emails, $subject, $msg, $user->username);

        echo 'Mail Sent!';


//       if(Ib_Email::bulk_email($emails,$subject,$msg,$user->username)){
//
//           echo 'Mail Sent!';
//
//       }
//
//        else{
//
//            echo 'An Error Occurred while sending email.';
//
//        }




        break;


    case 'companies':

        $ui->assign('jsvar', '
_L[\'are_you_sure\'] = \'' . $_L['are_you_sure'] . '\';
 ');

        $ui->assign('_application_menu', 'companies');
        $ui->assign('_st', $_L['Companies']);

// find all companies

        $companies = Model::factory('Models_Company')->find_array();

        $ui->assign('xheader', Asset::css(array('modal')));
        $ui->assign('xfooter', Asset::js(array('modal', 'contacts/companies')));

        $ui->assign('companies', $companies);


        $ui->display('companies.tpl');


        break;

    case 'modal_add_company':

        $id = route(2);


        $company = false;

        if ($id != '') {

            $id = str_replace('ae', '', $id);
            $id = str_replace('be', '', $id);

            $company = Model::factory('Models_Company')->find_one($id);
        }

        $val = array();

        if ($company) {
            $f_type = 'edit';
            $val['company_name'] = $company->company_name;
            $val['url'] = $company->url;
            $val['email'] = $company->email;
            $val['phone'] = $company->phone;
            $val['logo_url'] = $company->logo_url;
            $val['cid'] = $id;

//            $val[''] = $company->;
        } else {
            $f_type = 'create';
            $val['company_name'] = '';
            $val['url'] = 'http://';
            $val['email'] = '';
            $val['phone'] = '';
            $val['logo_url'] = '';
//            $val[''] = '';
        }

        $ui->assign('f_type', $f_type);
        $ui->assign('val', $val);


        $ui->display('modal_add_company.tpl');

        break;

    case 'add_company_post':


        $data = ib_posted_data();

        if ($data['f_type'] == 'edit') {

            $company = Model::factory('Models_Company')->find_one($data['cid']);

            if (!$company) {

                i_close('Company Not Found');
            }
        } else {

            $company = Model::factory('Models_Company')->create();
        }

        if ($data['company_name'] == '') {
            i_close($_L['Company Name is required']);
        }

        if (($data['email'] != '') && (!Validator::Email($data['email']))) {
            i_close($_L['Invalid Email']);
        }

        if ($data['url'] == 'http') {
            $data['url'] = '';
        }

        $company->company_name = $data['company_name'];
        $company->url = $data['url'];
        $company->email = $data['email'];
        $company->phone = $data['phone'];
        $company->logo_url = $data['logo_url'];
        $company->save();

        echo $company->id();




        break;


    case 'modal_edit_activity':

        $id = route(2);

        $id = str_replace('activity_', '', $id);

        $d = ORM::for_table('sys_activity')->find_one($id);

        if ($d) {
            $ui->assign('d', $d);
            $ui->display('modal_edit_activity.tpl');
        }





        break;


    case 'edit_activity_post':

        $edit_activity_id = _post('edit_activity_id');



        $d = ORM::for_table('sys_activity')->find_one($edit_activity_id);

        if ($d) {
            $message_text = $_POST['message_text'];
            $icon = $_POST['edit_activity_type'];
            $icon = str_replace('<a href="#"><i class="', '', $icon);
            $icon = str_replace('"></i></a>', '', $icon);
            if ($icon == '') {
                $icon = 'fa fa-check';
            }
            $d->icon = $icon;
            $d->msg = $message_text;
            $d->save();
            echo $d->id();
        }


        break;


    case 'orders':

        Event::trigger('contacts/orders/');

        $cid = _post('cid');
        $d = ORM::for_table('crm_accounts')->find_one($cid);
        if ($d) {
            $d = ORM::for_table('sys_orders')->where('crm_accounts_id', $cid)->find_array();
            $ui->assign('d', $d);
            $ui->display('contacts_orders.tpl');
        } else {
            
        }


        break;


    case 'files':

        Event::trigger('contacts/files/');

        $cid = _post('cid');

        $ui->assign('cid', $cid);

        // find all available files for this client

        $file_ids = ORM::for_table('ib_doc_rel')->where('rtype', 'contact')->where('rid', $cid)->find_array();


        $ids = array();

        foreach ($file_ids as $f) {

            $ids[] = $f['did'];
        }

        if (!empty($ids)) {

            $d = ORM::for_table('sys_documents')->where_in('id', $ids)->find_many();
        } else {
            $d = array();
        }


        // select all files

        $files = ORM::for_table('sys_documents')->find_array();

        $ui->assign('files', $files);





        $ui->assign('d', $d);

        $ui->display('contacts_files.tpl');


        break;


    case 'assign_file':

        $cid = _post('cid');

        $did = _post('did');

        // find the customer
        // check if exist

        $check = ORM::for_table('ib_doc_rel')->where('rtype', 'contact')->where('rid', $cid)->where('did', $did)->find_one();

        if ($check) {
            i_close('This file is already available for this contact.');
        }

        $d = ORM::for_table('ib_doc_rel')->create();
        $d->rtype = 'contact';
        $d->rid = $cid;
        $d->did = $did;
        $d->save();

        echo $cid;


        break;


    case 'remove_file':

        $cid = route(2);
        $did = route(3);

        $d = ORM::for_table('ib_doc_rel')->where('rtype', 'contact')->where('rid', $cid)->where('did', $did)->find_one();

        if ($d) {
            $d->delete();
        }


        r2(U . 'contacts/view/' . $cid . '/files/', 's', $_L['Data Updated']);


        break;


    case 'gen_auto_login':

        $id = route(2);

        $d = ORM::for_table('crm_accounts')->find_one($id);

        if ($d) {

            $d->autologin = Ib_Str::random_string(20) . $id . time();
            $d->save();

            r2(U . 'contacts/view/' . $id . '/summary/', 's', $_L['Created Successfully']);
        } else {
            echo 'Contact Not Found.';
        }



        break;


    case 'revoke_auto_login':
        $id = route(2);
        $d = ORM::for_table('crm_accounts')->find_one($id);
        if ($d) {

            $d->autologin = '';
            $d->save();

            r2(U . 'contacts/view/' . $id . '/summary/', 's', $_L['Data Updated']);
        } else {
            echo 'Contact Not Found.';
        }
        break;
    //chamada ajax que retorna list para o autocomplete
    case 'ajax-autocomplete-contactPF_E':
        if (!empty(_post("keyword"))) {
            $key = _post("keyword");
            $d = ORM::for_table('crm_accounts')
                    ->where_raw('(account LIKE "%' . $key . '%" OR company LIKE "%' . $key . '%"'
                            . 'OR cpf_cnpj LIKE "%' . $key . '%"'
                            . 'OR foreign_doc_identification LIKE "%' . $key . '%") and kind_of_person <>"PJ"'
                    )
                    ->find_many();
            $data = "";
            foreach ($d as $c) {
                $data[] = array(
                    'id' => $c->id,
                    'cpf_cnpj' => $c->cpf_cnpj,
                    'account' => $c->account,
                    'company' => $c->company,
                    'kinf_of_person' => $c->kind_of_person,
                    'foreign_doc_identification' => $c->foreign_doc_identification,
                );
            }

            echo json_encode(array('status' => (count($d) ? 'OK' : $_L['Account Not Found']), 'data' => $data));
        }
        break;

    //chamada ajax que retorna list para o autocomplete SALESMAN
    case 'ajax-autocomplete-salesman':
        if (!empty(_post("keyword"))) {
            $key = _post("keyword");
            //Salesman  4
            $d = ORM::for_table('crm_accounts')
                    ->table_alias('c')
                    ->select('c.*')
                    ->left_outer_join('crm_accounts_groups', array('c.id', '=', 'g.crm_accounts_id'), 'g')
                    ->where('g.crm_group_id', 4)
                    ->where_raw('(account LIKE "%' . $key . '%" OR company LIKE "%' . $key . '%"'
                            . 'OR cpf_cnpj LIKE "%' . $key . '%"'
                            . 'OR foreign_doc_identification LIKE "%' . $key . '%")'
                    )
                    ->find_many();

            $data = "";
            foreach ($d as $c) {
                $data[] = array(
                    'id' => $c->id,
                    'cpf_cnpj' => $c->cpf_cnpj,
                    'account' => $c->account,
                    'company' => $c->company,
                    'kinf_of_person' => $c->kind_of_person,
                    'foreign_doc_identification' => $c->foreign_doc_identification,
                );
            }

            echo json_encode(array('status' => (count($d) ? 'OK' : $_L['Salesman Not Found']), 'data' => $data));
        }
        break;
    //chamada ajax que retorna list para o autocomplete SALESMAN
    case 'ajax-listbygroup':
        $d = ORM::for_table('crm_accounts')
                ->table_alias('c')
                ->select('c.*')
                ->join('crm_accounts_groups', array('c.id', '=', 'ag.crm_accounts_id'), 'ag')
                ->join('crm_groups', array('g.id', '=', 'ag.crm_group_id'), 'g')
                ->where('g.gname', $routes['2'])
                ->where('g.default', 1);
        $term = _post('term');

        $d->where_any_is(array(array("c.account" => '%' . $term . '%')
                ), 'like');


        $crms = $d->find_many();

        $data = array();
        foreach ($crms as $c) {
            $data[] = array(
                'id' => $c->id,
                'name' => $c->account,
                'text' => $c->account,
                'cpf_cnpj' => $c->cpf_cnpj,
                'account' => $c->account,
                'company' => $c->company,
                'kinf_of_person' => $c->kind_of_person,
                'foreign_doc_identification' => $c->foreign_doc_identification,
                'dbo' => implode("/", array_reverse(explode("-", $c->date_of_birth))),
            );
        }

        echo json_encode($data);
        break;
        
        case 'ajax-listbytype':
        $d = ORM::for_table('crm_accounts')
                ->table_alias('c')
                ->select('c.*')
                ->where('c.kind_of_person',  $routes['2']);
        $term = _post('term');

        $d->where_any_is(array(array("c.account" => '%' . $term . '%')
                ), 'like');


        $crms = $d->find_many();

        $data = array();
        foreach ($crms as $c) {
            $data[] = array(
                'id' => $c->id,
                'name' => $c->account,
                'text' => $c->account,
                'cpf_cnpj' => $c->cpf_cnpj,
                'account' => $c->account,
                'company' => $c->company,
                'kinf_of_person' => $c->kind_of_person,
                'foreign_doc_identification' => $c->foreign_doc_identification,
            );
        }

        echo json_encode($data);
        break;
    case 'ajax-process-cnpj':
        require('application/lib/cnpj/funcoes.php');
        //recebe o cnpj e retira a mascara
        $cnpj = preg_replace('/\D/', '', _post('receita_cnpj'));
        $captcha = _post("receita_captcha");
        // pega html resposta da receita
        $getHtmlCNPJ = getHtmlCNPJ($cnpj, $captcha);
        if ($getHtmlCNPJ) {
            // volova os dados em um array
            $campos = parseHtmlCNPJ($getHtmlCNPJ);

            // verifico a Situação Cadastral da empresa
            $situacao = $campos[17];
            $city = null;
            if ($situacao == 'ATIVA') {
                //busca a cidade para alimentar o combo corretamente
                $state = ORM::for_table('state')->select('id')
                        ->where_raw('uf_state = "' . $campos[13] . '"')
                        ->find_one();

                $city_aux = str_replace('\'', '\\\'', $campos[12]);
                $city = ORM::for_table('city')->select('id')
                        ->select('city_name')
                        ->select('id_state')
                        ->where_raw('id_state = ' . $state->id . ' AND city_name like "' . $city_aux . '"')
                        //                    ->where('id_state = '.$state->id)
                        ->find_one();
            }

            $data[] = array(
                'status' => $campos['status'],
                'cnpj' => $campos[0],
                'account' => $campos[2],
                'company' => $campos[3],
                'address' => $campos[7],
                'number' => $campos[8],
                'complement' => $campos[9],
                'zip' => $campos[10],
                'neighborhood' => $campos[11],
                'city' => $campos[12],
                //verifica se encontrou a cidade
                'city_id' => ($city) ? $city->id : '',
                'state_id' => ($city) ? $city->id_state : '',
                'state' => $campos[13],
                'email' => $campos[14],
                'phone' => $campos[15],
                'situation' => $situacao
            );
            header('Content-Type: application/json');
            echo json_encode($data);
        } else {
            $data[] = array(
                'status' => 'ERRO_RECEITA',
                'msg' => 'O site da Receita Federal está inativo no momento para a realização das pesquisa. Por favor, tente mais tarde.'
            );
            header('Content-Type: application/json');
            echo json_encode($data);
        }
        break;

    case 'ajax-get-captcha':
        require('application/lib/cnpj/getcaptcha.php');
        break;

    case 'ajax-list-group':
        $contatos = ORM::for_table('crm_accounts')->select('id')->select('account')->select('company')->select('email')->order_by_asc('account')->find_many();
        // $ui->assign('c', $c);
        foreach ($contatos as $c) {
            $data[] = array(
                'id' => $c->id,
                'name' => $c->account,
                'email' => $c->email,
                'name_email' => $c->account . (empty($c->email) ? '' : " - " . $c->email)
            );
        }
        echo json_encode($data);
        break;

    case 'ajax-list':
        $contatos = ORM::for_table('crm_accounts')->select('id')->select('account')
                        ->select('company')->select('email')->select('segment_id')
                        ->select('kind_of_person')->select('cpf_cnpj')
                        ->order_by_asc('account')->find_many();
        // $ui->assign('c', $c);

        foreach ($contatos as $c) {
            $data[] = array(
                'id' => $c->id,
                'name' => $c->account,
                'email' => $c->email,
                'name_email' => $c->account . (empty($c->email) ? '' : " - " . $c->email),
                'segment_id' => $c->segment_id,
                'kind_of_person' => $c->kind_of_person,
                'cpf_cnpj' => $c->cpf_cnpj
            );
        }
        echo json_encode($data);

        break;

    default:
        echo 'action not defined';
}

Anon7 - 2022
AnonSec Team