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

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/lrsys/www/lrsys_apps/leo/application/plugins/module_helpdesk/controllers/TicketController.php
<?php

include_once "Controller.php";
include_once __DIR__ . "/../models/TicketModel.php";
include_once __DIR__ . "/../assets/libs/Helper.php";
include_once __DIR__ . "/../assets/libs/StatusOS.php";

class TicketController extends Controller {

    protected $id;
    protected $model;
    protected $client_id;

    /** @var Helper $helper */
    protected $helper;

    /** @var StatusOS $statusHelper */
    protected $statusHelper;

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

        $this->helper = new Helper($_L);
        $this->statusHelper = new StatusOS($_L);

        $this->ui->assign('_title', $this->_L['module_helpdesk ticket'] . ' - ' . $this->config['CompanyName']);
        $this->ui->assign('_st', $_L['module_helpdesk']);
        $this->ui->assign('helper', $this->helper);

        $this->model = new TicketModel();

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

    public function listAll($csv = false) {

        $filter = array();
        $filter['items_per_page'] = 10;
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            if (_post("clear") == 1) {
                $_SESSION['module_helpdesk/ticket/listAll']['cache'] = array();
            } else {
                $_SESSION['filter_helpdesk_responsible_id'] = isset($_POST['responsible_id']) ? $_POST['responsible_id'] : '';
                $_SESSION['filter_helpdesk_status'] = _post('status');
                $_SESSION['filter_helpdesk_sla'] = _post('sla');
                $_SESSION['filter_helpdesk_client_id'] = isset($_POST['client_id']) ? $_POST['client_id'] : '';
                $_SESSION['filter_helpdesk_search'] = _post('search');
                $_SESSION['filter_helpdesk_period'] = _post('period');
                if ($_SESSION['filter_helpdesk_period'] == 'interval') {
                    $_SESSION['filter_helpdesk_period_ini'] = _postDate('period_ini');
                    $_SESSION['filter_helpdesk_period_end'] = _postDate('period_end');
                } else {
                    $_SESSION['filter_helpdesk_period_ini'] = '';
                    $_SESSION['filter_helpdesk_period_end'] = '';
                }

                $filter['items_per_page'] = filter_var(_post('items_per_page'), FILTER_SANITIZE_STRING);
            }
        } else {
            if ($i = array_search('items_per_page', $this->routes))
                $filter['items_per_page'] = filter_var($this->routes[$i + 1], FILTER_SANITIZE_STRING);

            if (!isset($_SESSION['filter_helpdesk_responsible_id'])) {
                $user = User::_info();
                $_SESSION['filter_helpdesk_responsible_id'] = $user->id;
            }
        }
        if (!isset($_SESSION['module_helpdesk/ticket/listAll']['cache'])) {
            $_SESSION['module_helpdesk/ticket/listAll']['cache'] = array();
        }

        if (isset($_SESSION['filter_helpdesk_responsible_id'])) {
            $filter['responsible_id'] = $_SESSION['filter_helpdesk_responsible_id'];
        } else {
            $filter['responsible_id'] = '';
        }
        if (isset($_SESSION['filter_helpdesk_client_id'])) {
            $filter['client_id'] = $_SESSION['filter_helpdesk_client_id'];
        } else {
            $filter['client_id'] = '';
        }
        if (isset($_SESSION['filter_helpdesk_search'])) {
            $filter['search'] = $_SESSION['filter_helpdesk_search'];
        } else {
            $filter['search'] = '';
        }

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

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

        if (isset($_SESSION['filter_helpdesk_period'])) {
            $filter['period'] = $_SESSION['filter_helpdesk_period'];
        } else {
            $filter['period'] = '';
        }
        if (isset($_SESSION['filter_helpdesk_period_ini'])) {
            $filter['period_ini'] = $_SESSION['filter_helpdesk_period_ini'];
        } else {
            $filter['period_ini'] = '';
        }
        if (isset($_SESSION['filter_helpdesk_period_end'])) {
            $filter['period_end'] = $_SESSION['filter_helpdesk_period_end'];
        } else {
            $filter['period_end'] = '';
        }


        $sql = 'Select t.*,'
                . 'ca.account as client_account, '
                . '(select group_concat(s.description ) from sys_items s JOIN module_helpdesk_tickets_products sub_p ON ( sub_p.product_id=s.id) where   sub_p.module_helpdesk_tickets_id=t.id) as desc_product, '
                . '(select group_concat(s.id ) from sys_items s JOIN module_helpdesk_tickets_products sub_p ON ( sub_p.product_id=s.id) where   sub_p.module_helpdesk_tickets_id=t.id) as ids_product, '
                . '(select ic.name from sys_items_category ic JOIN module_helpdesk_tickets_products sub_p ON ( sub_p.product_cat_id=ic.id) where   sub_p.module_helpdesk_tickets_id=t.id LIMIT 1) as product_cat, '
                . 'cat.title as desc_category, '
                . 'resp.account as responsible_name, '
                . 'resp.email as responsible_email, '
                . 'req.fullname as requester_name, '
                . 'req.username as requester_email, '
                . 'pri.name as prioridade, '
                . 'type.name as treatment_type ';

        $from = ' from module_helpdesk_tickets t'
                . ' LEFT JOIN module_helpdesk_tickets_cat cat ON(t.module_helpdesk_tickets_cat_id=cat.id)'
                . ' LEFT JOIN crm_accounts ca ON(t.client_id=ca.id)'
                . ' LEFT JOIN crm_accounts resp ON(t.responsible_id=resp.id)'
                . ' LEFT JOIN sys_users req ON(t.requester_id=req.id)'
                . ' LEFT JOIN module_helpdesk_tickets_priority pri ON(t.module_helpdesk_tickets_priority_id=pri.id)'
                . ' LEFT JOIN module_helpdesk_tickets_treatment_type type ON(t.module_helpdesk_tickets_treatment_type_id=type.id)'
                . " WHERE (t.deleted_at IS NULL OR t.deleted_at =0)  ";
        $where = "";
        // Filtro por períodos
        if (isset($filter['period']) && $filter['period'] != '') {
            if ($filter['period'] == 'all')
//                $where .= " AND t.created_at IS NOT NULL";
                if ($filter['period'] == 'day')
                    $where .= " AND  t.created_at = '" . date('Y-m-d') . "'";
            if ($filter['period'] == 'week')
                $where .= " AND WEEK( t.created_at) = WEEK('" . date('Y-m-d') . "')";
            if ($filter['period'] == 'month')
                $where .= " AND MONTH( t.created_at) = MONTH('" . date('Y-m-d') . "')";
            if ($filter['period'] == 'interval') {
                if ($filter['period_ini'] != '') {
                    $where .= " AND DATE(t.created_at) >= '" . $filter['period_ini'] . "'";
                }

                if ($filter['period_end'] != '') {
                    $where .= " AND DATE(t.created_at) <= '" . $filter['period_end'] . "'";
                }
            }
        }

        if (isset($filter['client_id']) && $filter['client_id'] != '') {
            //$where .= " AND l.client_id IN (" . implode(',', $filter['client_id']) . ")";
//            $options = "";
//            foreach ($filter['client_id'] as $c) {
//                $c = ORM::for_table('crm_accounts')->find_one($c);
//                if (count($c) > 0) {
//                    $options .= '<option value="' . $c->id . '" selected >' . $c->account . '</option>';
//                }
//            }
            $where .= " AND t.client_id IN (" . $filter['client_id'] . ")";
//            $options = "";
//            foreach ($filter['client_id'] as $c) {
            $c = ORM::for_table('crm_accounts')->find_one($filter['client_id']);
//                if (count($c) > 0) {
            $options = '<option value="' . $c->id . '" selected >' . $c->account . '</option>';
//                }
//            }
            $this->ui->assign('account', $options);
        } else {
            $this->ui->assign('account', false);
        }

        // verifido se é um cliente que está acessando
        if ($this->client_id > 0) {
            $where .= " AND t.client_id ='" . $this->client_id . "'";
        }

        if (isset($filter['responsible_id']) && $filter['responsible_id'] != '') {
            $where .= " AND t.responsible_id=" . intval($filter['responsible_id']);
            $this->ui->assign('responsible', ORM::for_table('crm_accounts')->find_one(intval($filter['responsible_id'])));
        } else {
            $this->ui->assign('responsible', false);
        }
        if (isset($filter['status']) && $filter['status'] != '' && $filter['status'] != 'all') {
            $where .= " AND t.status='" . ($filter['status'] . "'");
        }

        if (isset($filter['search']) && $filter['search'] != '') {
            $where .= " AND (ca.account LIKE '%" . $filter['search'] . "%' 
			OR t.id LIKE '%" . $filter['search'] . "%' 
			)";
        }


        if ($filter['items_per_page'] != 'all')
            $filter['items_per_page'] = ($filter['items_per_page'] > 0) ? $filter['items_per_page'] : 10;

        if ($csv) {
            $filter['items_per_page'] = 'all';
        }
        $sql .= $from . $where . ' order by  t.created_at DESC ';



        // verifico se é pra filtrar pelos atrasados
        if (isset($filter['sla']) && $filter['sla'] != '' && $filter['sla'] != 'all') {
            $filter['items_per_page'] = 'all';
            $page = 1;
            $paginator = new ModulePaginator('module_helpdesk_tickets', $sql, $filter);
            $records = $paginator->setItemsPerPage($filter['items_per_page'])
                    ->setCurrentPageNumber($page)
                    ->run();
            $recordsTotal = $paginator->setItemsPerPage('all')->run();
        } else {
            $page = isset($this->routes['3']) ? $this->routes['3'] : 1;
            $paginator = new ModulePaginator('module_helpdesk_tickets', $sql, $filter);
            $records = $paginator->setItemsPerPage($filter['items_per_page'])
                    ->setCurrentPageNumber($page)
                    ->run();
            $recordsTotal = $paginator->setItemsPerPage('all')->run();
        }


        // SELECT PARA GRÁFICO
        $ticketsQtyLate = 0;
        $ticketsQtyCritical = 0;
        $graph['date'] = array();
        $graph['qty'] = array();
        foreach (array_reverse($recordsTotal) as $a) {
            if (isset($graph['qty'][date('Y-m-d', strtotime($a['created_at']))])) {
                $graph['qty'][date('Y-m-d', strtotime($a['created_at']))] ++;
            } else {

                $graph['qty'][date('Y-m-d', strtotime($a['created_at']))] = 1;
            }



            switch ($a['status']) {
                case 'Open':
                    if (isset($graph['qty_open'][date('Y-m-d', strtotime($a['created_at']))])) {
                        $graph['qty_open'][date('Y-m-d', strtotime($a['created_at']))] ++;
                    } else {
                        $graph['qty_open'][date('Y-m-d', strtotime($a['created_at']))] = 1;
                    }
                    break;
                case 'Atendence':
                    if (isset($graph['qty_atendence'][date('Y-m-d', strtotime($a['created_at']))])) {
                        $graph['qty_atendence'][date('Y-m-d', strtotime($a['created_at']))] ++;
                    } else {
                        $graph['qty_atendence'][date('Y-m-d', strtotime($a['created_at']))] = 1;
                    }
                    break;
                case 'Closed':
                    if (isset($graph['qty_closed'][date('Y-m-d', strtotime($a['created_at']))])) {
                        $graph['qty_closed'][date('Y-m-d', strtotime($a['created_at']))] ++;
                    } else {
                        $graph['qty_closed'][date('Y-m-d', strtotime($a['created_at']))] = 1;
                    }
                    break;
            }


            // SLA
            // Verifico o SLA
            $sql_sla = "Select t.*
                    from module_helpdesk_sla t
                    LEFT JOIN module_helpdesk_sla_products prod ON(prod.module_helpdesk_sla_id=t.id AND prod.product_id IN (" . $a['ids_product'] . "))
                    WHERE t.module_helpdesk_tickets_cat_id = " . $a['module_helpdesk_tickets_cat_id'] . " AND 
                    t.module_helpdesk_tickets_treatment_type_id = " . $a['module_helpdesk_tickets_treatment_type_id'] . " AND t.client_id = " . $a['client_id']
                    . " ORDER BY id DESC";
            $sla = ORM::for_table('module_helpdesk_sla')
                            ->raw_query($sql_sla)->find_one();



//            $earlier = new DateTime("2020-12-17");
//            $later = new DateTime();
////            $earlier = $later->add(new DateInterval('P31D'));
//            $diff = $later->diff($earlier);
//            var_dump($diff);exit;


            $sla_2 = null;
            $sla_2_late = false;
            $sla_2_critical = false;
            if ($a['begin_at']) {
//                $sla_2 = $this->helper->transformSlaInt($a['begin_at']);
                if ($a['closed_at']) {
                    $sla_2 = $this->helper->transformSlaInt($a['begin_at'], $a['closed_at']);
                } else {
                    $sla_2 = $this->helper->transformSlaInt($a['begin_at']);
                }

                if (isset($sla->sla2) && $sla_2 > $sla->sla2) {
                    $sla_2_late = true;
                    if ($sla_2 - $sla->sla2 > 5) {
                        $sla_2_critical = true;
                        $ticketsQtyCritical++;
                    } else {
                        $ticketsQtyLate++;
                    }
                }
            }

            $sla_1_late = false;
            $sla_1_critical = false;

            if ($a['begin_at']) {
                $sla_1 = $this->helper->transformSlaInt($a['created_at'], $a['begin_at']);
            } else {
                $sla_1 = $this->helper->transformSlaInt($a['created_at']);
            }

            if (isset($sla->sla1) && $sla_1 > $sla->sla1) {
                $sla_1_late = true;
                if ($sla_1 - $sla->sla1 > 5) {
                    $sla_1_critical = true;
                    if ($a['begin_at'] == null) {
                        $ticketsQtyCritical++;
                    }
                } else {
                    if ($a['begin_at'] == null) {
                        $ticketsQtyLate++;
                    }
                }
            }

            // Seto as variáveis do SLA
            $index = 0;
            foreach ($records as $rec) {
                if ($rec['id'] == $a['id']) {
                    $records[$index]['sla_1'] = $sla_1;
                    $records[$index]['sla_2'] = $sla_2;
                    $records[$index]['sla_1_late'] = $sla_1_late;
                    $records[$index]['sla_2_late'] = $sla_2_late;
                    $records[$index]['sla_1_critical'] = $sla_1_critical;
                    $records[$index]['sla_2_critical'] = $sla_2_critical;
                    if (!$csv) {
//                        $formdata = ORM::for_table('module_helpdesk_form_data')->select_expr(" count(ticket_id) as total")->where('ticket_id', $rec['id'])->find_many()->limit(1);
//                        $records[$index]['form_data'] = $formdata[0]->total;
//                        $records[$index]['form_view'] = $this->viewModal($rec['id']);
                    }

                    // verifico se é pra filtrar pelos atrasados
                    if (isset($filter['sla']) && $filter['sla'] != '' && $filter['sla'] != 'all') {
                        if ($a['begin_at'] == null && $sla_1_late == false) {
                            unset($records[$index]);
                        } elseif ($a['begin_at'] && $sla_2_late === false) {
                            unset($records[$index]);
                        }

                        if ($filter['sla'] == 'critical') {
                            if ($a['begin_at'] == null && $sla_1_critical == false) {
                                unset($records[$index]);
                            } elseif ($a['begin_at'] && $sla_2_critical === false) {
                                unset($records[$index]);
                            }
                        }
                    }
                }
                $index++;
            }
        }

        if ($csv == true) {
            return $records;
        }
        foreach ($records as $key => $rec) {
            $formdata = ORM::for_table('module_helpdesk_form_data')->select_expr(" count(ticket_id) as total")->where('ticket_id', $rec['id'])->find_many()->limit(1);
            $records[$key]['form_data'] = $formdata[0]->total;
//         
        }




        $css_arr = array(
            's2/css/select2.min',
            'dp/dist/datepicker.min',
            'modal',
            'sweetalert/sweetalert',
            'dropzone/dropzone',
            'dp/dist/datepicker.min',
            'ibilling/clockpicker/clockpicker',
            '/../../../application/plugins/module_helpdesk/assets/css/default');

        $js_arr = array(
            's2/js/select2.min',
            'dp/dist/datepicker.min',
            'modal',
            'sweetalert/sweetalert',
            'dp/dist/datepicker.min',
            'ibilling/clockpicker/clockpicker',
            'dashboard/graph', 'chart/echarts.min',
            '/../../../application/plugins/module_helpdesk/assets/js/ticket-list',
            '/../../../application/plugins/module_helpdesk/assets/js/online',
            '/../../../application/plugins/module_helpdesk/assets/js/ticket-list-form'
        );

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

        $this->ui->assign('showFilters', true);
        $this->ui->assign('cacheList', $_SESSION['module_helpdesk/ticket/listAll']['cache']);


        $tickets = ORM::for_table('module_helpdesk_tickets')->raw_query("Select count(*) as total " . $from . $where)->find_array();
        $ticketsOpen = ORM::for_table('module_helpdesk_tickets')->raw_query("Select count(*) as total  " . $from . $where . " AND t.status='Open'")->find_array();
        $ticketsAtendence = ORM::for_table('module_helpdesk_tickets')->raw_query("Select count(*) as total  " . $from . $where . " AND t.status='Atendence'")->find_array();

        $bottomBar = array(
            array('type' => 'int', 'info' => $this->_L['module_helpdesk Ticket_Qty_late'], 'value' => ($ticketsQtyLate)),
            array('type' => 'int', 'info' => $this->_L['module_helpdesk Ticket_Qty_critical'], 'value' => ($ticketsQtyCritical)),
            array('type' => 'int', 'info' => $this->_L['module_helpdesk Ticket_Qty_open'], 'value' => ($ticketsOpen[0]['total'])),
            array('type' => 'int', 'info' => $this->_L['module_helpdesk Ticket_Qty_atendence'], 'value' => ($ticketsAtendence[0]['total'])),
            array('type' => 'int', 'info' => $this->_L['module_helpdesk Ticket_Qty'], 'value' => ($tickets[0]['total']))
        );
        $this->ui->assign('bottomBar', $bottomBar);



        $forms = ORM::for_table("module_forms_forms")->where('status', 1)->find_many();
        $opt = '<option></option>';
        if (count($forms) > 0) {
            foreach ($forms as $f) {
                $opt .= '<option value="' . $f->id . '"> ' . $f->title . "</option>";
            }
        }
        // Gráficos
        $jsvar = '
            
        _L[\'module_helpdesk ticket form\'] = \'' . $this->_L['module_helpdesk ticket form'] . '\';
            
        _L[\'Data View\'] = \'' . $this->_L['Data View'] . '\';
        _L[\'Refresh\'] = \'' . $this->_L['Refresh'] . '\';
        _L[\'Reset\'] = \'' . $this->_L['Reset'] . '\';
        _L[\'Cancel\'] = \'' . $this->_L['Cancel'] . '\';
        _L[\'Yes\'] = \'' . $this->_L['Yes'] . '\';
        _L[\'No\'] = \'' . $this->_L['No'] . '\';
        _L[\'Save as Image\'] = \'' . $this->_L['Save as Image'] . '\';
        _L[\'Click to Save\'] = \'' . $this->_L['Click to Save'] . '\';
        _L[\'Average\'] = \'' . $this->_L['Average'] . '\';
        _L[\'Line\'] = \'' . $this->_L['Line'] . '\';
        _L[\'Bar\'] = \'' . $this->_L['Bar'] . '\';
        _L[\'module_helpdesk msg acept ticket\']= \'' . $this->_L['module_helpdesk msg acept ticket'] . '\';
        _L[\'module_helpdesk ticket form select\']= \'' . $this->_L['module_helpdesk ticket form select'] . '\';
        opt_form_select=\'' . $opt . '\';
        _L[\'form required\']=\'' . $this->_L['module_helpdesk ticket form select'] . $this->_L['is required'] . '\';
        ';
        $this->ui->assign('jsvar', $jsvar
                . showGraph($this->_L['module_helpdesk Ticket_Qty'], $this->_L['module_helpdesk Ticket_Qty'] . "/dia", "graph_qty", $graph['qty'], $graph['date']));


        $this->ui->assign('formatDateHour', $this->config['df'] . " H:i:s");
        $this->ui->assign('filter', $filter);
        $this->ui->assign('records', $records);
        $this->ui->assign('paginator', $paginator);
        $this->ui->assign('_st', $this->_L['module_helpdesk list ticket']);
        $this->ui->assign('_include', 'ticket/list');
        $this->ui->display('wrapper.tpl');
    }

    public function addCacheTicket() {
        $_SESSION['module_helpdesk/ticket/listAll']['cache'][] = _post("id");
        echo 1;
    }

    public function add() {
//
        $js_arr = array(
            '/../../../application/plugins/module_helpdesk/assets/js/ticket-form',
            'redactor/redactor.min', 's2/js/select2.min', 's2/js/i18n/' . lan(), 'dropzone/dropzone'
        );
        $css_arr = array('s2/css/select2.min', 'redactor/redactor', 'dropzone/dropzone'
        );
        $this->ui->assign('attachs', '');

        $user = null;
        if (!$this->client_id) {
            $user = User::_info();
        }


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

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

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


        $attachNote = ORM::for_table('module_helpdesk_tickets_type_attachment')->where('user_id', $user->id)->where_null('module_helpdesk_tickets_id')->find_many();

        $attNote = "";
        $attachsNote = "";
        if (count($attachNote) > 0) {

            foreach ($attachNote as $i) {

                //temporario 100 o tamanho
                $attNote .= ' {id:"' . $i->id . '", name: "' . $i->name . '", size: 100,url:"' . APP_URL . '/application/plugins/module_helpdesk/uploads/tickets/type_atendence/' . $i->src . '" },';
                $attachsNote .= "," . $i->id;
            }
        } else {
            $attNote = "";
        }
        $this->ui->assign('attachsNotes', substr($attachsNote, 1));


        // Pego os formulários disponíveis
        $forms = ORM::for_table("module_forms_forms")->where('status', 1)->find_many();
        $this->ui->assign('forms', $forms);

        $assets_css = Asset::css($css_arr);
        $assets_js = Asset::js($js_arr);
        $this->ui->assign('xheader', $assets_css);
        $this->ui->assign('xfooter', $assets_js);
        $this->ui->assign('jsvar', '
        _L[\'are_you_sure\'] = \'' . $this->_L['are_you_sure'] . '\';
        _L[\'Save\'] = \'' . $this->_L['Save'] . '\';
        _L[\'OK\'] = \'' . $this->_L['OK'] . '\';
        _L[\'Remove\'] = \'' . $this->_L['Remove'] . '\';
        _L[\'Cancel\'] = \'' . $this->_L['Cancel'] . '\';
        _L[\'Select\'] = \'' . $this->_L['Select'] . '\'; 
   _L[\'View\'] = \'' . $this->_L['View'] . '\'; 
        _L[\'module_helpdesk Delete Attach?\'] = \'' . $this->_L['module_helpdesk Delete Attach?'] . '\';

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



        $this->ui->assign('typeForm', 'window');
        $this->ui->assign('ticket', (object) array("title" => "",
                    'id' => "",
                    'form_id' => "",
                    'default' => "0",
                    'description' => "",
                    'status' => "Open",
                    'product_cat_id' => '',
                    'product_id' => '',
                    'client_id' => '',
                    'treatment_type_local' => '',
        ));
        $this->ui->assign('_st', $this->_L['module_helpdesk ticket']);
        $this->ui->assign('_include', 'ticket/' . __FUNCTION__);
        $this->ui->display('wrapper.tpl');
    }

    public function add_offline() {
//
        $this->ui->assign('attachs', '');

        $user = null;
        if (!$this->client_id) {
            $user = User::_info();
        }
        // Pego os formulários disponíveis
        $forms = ORM::for_table("module_forms_forms")->where('status', 1)->find_many();
        $this->ui->assign('forms', $forms);


        $d = ORM::for_table('crm_accounts')
                ->table_alias('c')
                ->select('c.*');
        $d->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', 'customer')
                ->where('g.default', 1)->order_by_asc('c.account');
        $clien = $d->find_many();
        $this->ui->assign('client', $clien);

//        $d = ORM::for_table('crm_accounts')
//                ->table_alias('c')
//                ->select('c.*');
//        $d->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', 'Employee')
//                ->where('g.default', 1)->order_by_asc('c.account');
//        $respo = $d->find_many();
//        $this->ui->assign('responsible', $respo);

        $this->ui->assign('responsible_id', $user->id);


        $d = ORM::for_table('module_helpdesk_tickets_priority')
                        ->table_alias('p')->order_by_asc('p.name')->find_many();

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

        $d = ORM::for_table('module_helpdesk_tickets_cat')
                        ->table_alias('s')->order_by_asc('s.title')->find_many();
        $this->ui->assign('cat', $d);



        $all = ProductCategory::all();
        foreach ($all as $s) {

            // PACTH HEXAGON
            // Pega apenas as categorias o Pai "FORM"
            if (!$s['parent']) {
                continue;
            }
            $data[] = array(
                'id' => $s['id'],
                'name' => $s['name'], //verifica se são os dados pre cadastrados que são traduzidos
                'parent' => $s['parent'],
                'name_parent' => $s['name_parent']
            );
        }
        $this->ui->assign('category', $data);


        $d = ORM::for_table('module_helpdesk_tickets_treatment_type')
                        ->table_alias('s')->order_by_asc('s.name')->find_many();

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


        $d = ORM::for_table('sys_items')
                        ->table_alias('i')
                        ->select('i.*')
                        ->left_outer_join('sys_items_category', array('is.id', '=', 'i.category_id'), 'is')
                        ->order_by_asc('i.description')->find_many();
        $cat = array();
        $this->ui->assign('products', $d);
//        if (count($d) > 0) {
//            foreach ($d as $p) {
//                if (!isset($cat[$p->category_id])) {
//                    $cat[$p->category_id] = "";
//                }
//                $cat[$p->category_id] .= "<option value='" . $p->id . "'> (" . $p->id . ") " . $p->description . "</option>";
//            }
//        }

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

    /**
     * Insert add to type diary
     */
    public function postOfflineForm() {
        try {

            $data = $_POST;
            $msg = '';
            $ticket = $this->model->createTicket($data);
            header('Content-Type: application/json');

            if ($ticket->id > 0) {
                echo json_encode(array('status' => 'OK', 'msg' => '', 'id' => $ticket->id));
            } else {
                echo json_encode(array('status' => 'OK', 'msg' => 'Erro, ticket não salvo', 'id' => ''));
            }
        } catch (Exception $e) {
            
        }
    }

    public function post() {
        try {

            if ($this->client_id > 0) {
                $_POST['client_id'] = $this->client_id;
            }

            $data = $_POST;
            $msg = '';



            if (empty(_post('client_id'))) {
                $msg .= $this->_L['Customer'] . $this->_L['is required'];
            }

            if (empty(_post('status'))) {
                $msg .= $this->_L['Status'] . $this->_L['is required'];
            }
            if (empty(_post('module_helpdesk_tickets_priority_id'))) {
                $msg .= $this->_L['module_helpdesk priority'] . $this->_L['is required'];
            }
            if (empty(_post('module_helpdesk_tickets_cat_id'))) {
                $msg .= $this->_L['module_helpdesk ticket category'] . $this->_L['is required'];
            }
            if (empty(_post('module_helpdesk_tickets_treatment_type_id'))) {
                $msg .= $this->_L['module_helpdesk type'] . $this->_L['is required'];
            }
            if (empty(_post('product_cat_id'))) {
                $msg .= $this->_L['Category'] . $this->_L['is required'];
            }

//            if (empty(_post('form_id'))) {
//                $msg .= $this->_L['module_helpdesk ticket form select'] . $this->_L['is required'];
//            }

            if (!isset($_POST['product_id'])) {
                $msg .= $this->_L['module_helpdesk product'] . $this->_L['is required'];
            }
            if (empty(_post('description'))) {
                $msg .= $this->_L['module_helpdesk description'] . $this->_L['is required'];
            }



            if (empty($msg)) {
                if (isset($data['id']) && $data['id'] > 0) {
                    $ticket = $this->model->getOne($data['id']);

                    if ($ticket->status == 'Closed') {
                        $msg = $this->_L['module_helpdesk closed msg'];
                        echo json_encode(array('status' => 'ERRO', 'msg' => $msg, 'id' => ''));
                        exit();
                    }
                    $ticket = $this->model->updateTicket($data, $ticket);
                    _notify($this->_L['module_helpdesk ticket'] . " " . $this->_L['Edited Successfull'], 's');
                } else {
                    $ticket = $this->model->createTicket($data);
                    _notify($this->_L['module_helpdesk ticket'] . " " . $this->_L['Add Successfull'], 's');
                }



                // envio email para responsável
                // FALTA ASSUNTO E TEXTO PARA EMAIL
                $_L = $this->_L;
                $_c = $this->config;
                $client = ORM::for_table('crm_accounts')->find_one($ticket->client_id);

                $responsible = ORM::for_table('crm_accounts')->find_one($ticket->responsible_id);

                $register = ORM::for_table('sys_users')->find_one($ticket->requester_id);

                $priority_ticket = ORM::for_table('module_helpdesk_tickets_priority')->find_one($ticket->module_helpdesk_tickets_priority_id);

                $cat_ticket = ORM::for_table('module_helpdesk_tickets_cat')->find_one($ticket->module_helpdesk_tickets_cat_id);

                $type_ticket = ORM::for_table('module_helpdesk_tickets_treatment_type')->find_one($ticket->module_helpdesk_tickets_treatment_type_id);

                $products = $this->model->getProducts($ticket);
                if (count($products) > 0) {
                    $category = ORM::for_table('sys_items_category')->find_one($products[0]->product_cat_id);
                } else {
                    $category = "";
                }
                $tpl = 'application/plugins/module_helpdesk/assets/libs/email_ticket.php';

                ob_start();

                require $tpl;

                $html = ob_get_contents();

                ob_end_clean();



                if (@$responsible->email) {
                    Notify_Email::_send($responsible->account, $responsible->email, 'HELP DESK HEXAGON | Você tem um novo Ticket', $html);
                }

                if (@$register->username) {
                    Notify_Email::_send($register->fullname, $register->username, 'HELP DESK HEXAGON | Você tem um novo Ticket', $html);
                }


                echo json_encode(array('status' => 'OK', 'msg' => '', 'id' => $ticket->id));



//                $e = ORM::for_table('sys_email_templates')->where('tplname', 'Admin:Password Change Request')->find_one();
//
//                $subject = new Template($e['subject']);
//                $subject->set('business_name', 'lr');
//                $subj = $subject->output();
//                $message = new Template($e['message']);
//                $message->set('name', 'Leonardo teste');
//                $message->set('business_name', 'lr2');
//                $message->set('password_reset_link', U . 'fdsa');
//                $message->set('username', 'leolopesramos@me.com');
//                $message->set('ip_address', $_SERVER["REMOTE_ADDR"]);
//                $message_o = $message->output();
//                var_dump($message_o);exit;
//                Notify_Email::_send('Leonaro Lopes','leolopesramos@me.com', 'fasdfasd', 'dsafdsa');
            } else {
                echo json_encode(array('status' => 'ERRO', 'msg' => $msg, 'id' => ''));
            }
        } catch (Exception $ex) {
            echo json_encode(array('status' => 'ERRO', 'msg' => $ex->getMessage(), 'id' => ''));
            exit();
        }
    }

    /**
     * Insert add to type diaryvo
     */
    public function form_post() {
        try {

            if ($this->client_id > 0) {
                $_POST['client_id'] = $this->client_id;
            }

            $data = $_POST;
            $msg = '';
            if (!empty($data['ticket_id_offline'])) {
                $ti = ORM::for_table('module_helpdesk_tickets')->where("id_offline", $data['ticket_id_offline'])->find_many();
                if (count($ti) > 0) {
                    $data['ticket_id'] = $ti[0]->id;
                } else {
                    header('Content-Type: application/json');
                    echo json_encode(array('status' => 'ERRO SAVE', 'msg' => "Ticket ainda não enviado", 'id' => ''));
                    exit();
                }
            }

            $save = $this->model->saveFormData($data);

            if ($save) {


                $ticket = $this->model->getOne($data['ticket_id']);
                $ticket->status = 'Closed';
                $ticket->closed_at = date('Y-m-d H:i:s');
                $ticket->save();


                // envio email para responsável
                // FALTA ASSUNTO E TEXTO PARA EMAIL
                $_L = $this->_L;
                $_c = $this->config;
                $client = ORM::for_table('crm_accounts')->find_one($ticket->client_id);

                $responsible = ORM::for_table('crm_accounts')->find_one($ticket->responsible_id);

                $register = ORM::for_table('sys_users')->find_one($ticket->requester_id);

                $priority_ticket = ORM::for_table('module_helpdesk_tickets_priority')->find_one($ticket->module_helpdesk_tickets_priority_id);

                $cat_ticket = ORM::for_table('module_helpdesk_tickets_cat')->find_one($ticket->module_helpdesk_tickets_cat_id);

                $type_ticket = ORM::for_table('module_helpdesk_tickets_treatment_type')->find_one($ticket->module_helpdesk_tickets_treatment_type_id);

                $products = $this->model->getProducts($ticket);
                if (count($products) > 0) {
                    $category = ORM::for_table('sys_items_category')->find_one($products[0]->product_cat_id);
                } else {
                    $category = "";
                }
                $tpl = 'application/plugins/module_helpdesk/assets/libs/email_ticket.php';

                ob_start();

                require $tpl;

                $html = ob_get_contents();


                ob_end_clean();

                if (@$responsible->email) {
                    Notify_Email::_send($responsible->account, $responsible->email, 'HELP DESK HEXAGON | Ticket editado', $html);
                }

                if (@$register->username) {
                    Notify_Email::_send($register->fullname, $register->username, 'HELP DESK HEXAGON | Ticket editado', $html);
                }


                _notify(" Ficha " . $this->_L['Add Successfull'], 's');
                header('Content-Type: application/json');
                echo json_encode(array('status' => 'OK', 'msg' => 'CADASTRADO  COM SUCESSO'));
                exit;
            } else {
                header('Content-Type: application/json');
                echo json_encode(array('status' => 'ERRO SAVE', 'msg' => $msg, 'id' => ''));
                exit();
            }
        } catch (Exception $ex) {
            header('Content-Type: application/json');
            echo json_encode(array('status' => 'ERRO', 'msg' => $ex->getMessage(), 'id' => ''));
            exit();
        }
    }

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

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

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

        if (!$ticket) {
            die($this->_L['Not_Found']);
        }
        if ($ticket->deleted_at != null) {
            die($this->_L['Not_Found']);
        }

        $js_arr = array(
            '/../../../application/plugins/module_helpdesk/assets/js/ticket-form',
            'redactor/redactor.min', 's2/js/select2.min', 's2/js/i18n/' . lan(), 'dropzone/dropzone'
        );
        $css_arr = array('s2/css/select2.min', 'redactor/redactor', 'dropzone/dropzone'
        );
        $this->ui->assign('attachs', '');

        $attach = ORM::for_table('module_helpdesk_tickets_attach')->where('module_helpdesk_tickets_id', $ticket->id)->find_many();

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

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

        $attachNote = ORM::for_table('module_helpdesk_tickets_type_attachment')->where('module_helpdesk_tickets_id', $ticket->id)->find_many();

        $attNote = "";
        $attachsNote = "";
        if (count($attachNote) > 0) {

            foreach ($attachNote as $i) {

                //temporario 100 o tamanho
                $attNote .= ' {id:"' . $i->id . '", name: "' . $i->name . '", size: 100,url:"' . APP_URL . '/application/plugins/module_helpdesk/uploads/tickets/type_atendence/' . $i->src . '" },';
                $attachsNote .= "," . $i->id;
            }
        } else {
            $attNote = "";
        }
        $this->ui->assign('attachsNotes', substr($attachsNote, 1));
        // Pego os formulários disponíveis
        $forms = ORM::for_table("module_forms_forms")->where('status', 1)->find_many();
        $this->ui->assign('forms', $forms);

        $assets_css = Asset::css($css_arr);
        $assets_js = Asset::js($js_arr);
        $this->ui->assign('xheader', $assets_css);
        $this->ui->assign('xfooter', $assets_js);
        $this->ui->assign('jsvar', '
        _L[\'are_you_sure\'] = \'' . $this->_L['are_you_sure'] . '\';
        _L[\'Save\'] = \'' . $this->_L['Save'] . '\';
        _L[\'OK\'] = \'' . $this->_L['OK'] . '\';
        _L[\'Remove\'] = \'' . $this->_L['Remove'] . '\';
        _L[\'Cancel\'] = \'' . $this->_L['Cancel'] . '\';
        _L[\'Select\'] = \'' . $this->_L['Select'] . '\'; 
   _L[\'View\'] = \'' . $this->_L['View'] . '\'; 
        _L[\'module_helpdesk Delete Attach?\'] = \'' . $this->_L['module_helpdesk Delete Attach?'] . '\';

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

        $client = ORM::for_table('crm_accounts')->find_one($ticket->client_id);
        $this->ui->assign('client', $client);


        $requester = ORM::for_table('crm_accounts')->find_one($ticket->responsible_id);
        $this->ui->assign('responsible', $requester);

        $requester = ORM::for_table('module_helpdesk_tickets_priority')->find_one($ticket->module_helpdesk_tickets_priority_id);
        $this->ui->assign('priority_ticket', $requester);


        $requester = ORM::for_table('module_helpdesk_tickets_cat')->find_one($ticket->module_helpdesk_tickets_cat_id);
        $this->ui->assign('cat_ticket', $requester);


        $requester = ORM::for_table('module_helpdesk_tickets_treatment_type')->find_one($ticket->module_helpdesk_tickets_treatment_type_id);
        $this->ui->assign('type_ticket', $requester);


        $prods = $this->model->getProducts($ticket);
        $this->ui->assign('products', $prods);
        if (count($prods) > 0) {
            $ticket->product_cat_id = $prods[0]->product_cat_id;
        }

        $this->ui->assign('ticket', $ticket);
        $this->ui->assign('typeForm', 'window');
        $this->ui->assign('_st', $this->_L['module_helpdesk ticket']);
        $this->ui->assign('_include', 'ticket/add');
        $this->ui->display('wrapper.tpl');
    }

    private function viewModal($id, $idForm = "") {
        $ui2 = new Smarty();
        $ib_theme = $this->config['theme'];

        $ui2->setTemplateDir('ui/theme/' . $ib_theme . '/');
        $ui2->setCompileDir('ui/compiled/');
        $ui2->setConfigDir('ui/conf/');
        $ui2->setCacheDir('ui/cache/');
        $ui2->assign('_L', $this->_L);
        $ui2->assign('_pd', 'application/plugins/' . $this->dir);
        $ui2->assign('app_url', APP_URL . '/');
        $ui2->assign('_c', $this->config);


        if (($this->config['url_rewrite']) == '1') {
            $ui2->assign('_url', APP_URL . '/');
            $ui2->assign('base_url', APP_URL . '/');
        } else {
            $ui2->assign('_url', APP_URL . '/?ng=');
            $ui2->assign('base_url', APP_URL . '/?ng=');
        }

        if (empty($idForm)) {
            $ticket = $this->model->getOne($id);
//            $ui2->assign('formId', "f" . $id);
            $ui2->assign('formId', "");
            if (!$ticket) {
                return ($this->_L['Not_Found']);
            }
            if ($ticket->deleted_at != null) {
                return ($this->_L['Not_Found']);
            }
        } else {
            $ticket = (object) array("id" => 0, "form_id" => $idForm, 'created_at' => date("Y-m-d H:i:s"));
            $ui2->assign('formId', "");
        }

        $attach = ORM::for_table('module_helpdesk_tickets_attach')->where('module_helpdesk_tickets_id', $ticket->id)->find_many();

        if (count($attach) > 0) {
            $ui2->assign('attachs', $attach);
        } else {
            $ui2->assign('attachs', "");
        }


        $attachNote = ORM::for_table('module_helpdesk_tickets_type_attachment')->where('module_helpdesk_tickets_id', $ticket->id)->find_many();
        if (count($attachNote) > 0) {
            $ui2->assign('attachsNote', $attachNote);
        } else {
            $ui2->assign('attachsNote', "");
        }

        // Pego os formulários disponíveis
        $forms = ORM::for_table("module_forms_forms")->where('status', 1)->find_many();
        $ui2->assign('forms', $forms);

        $ticket_form = null;
        if ($ticket->form_id) {
            $ticket_form = ORM::for_table("module_forms_forms")->find_one($ticket->form_id);

            // Busca as questões do formulário
            $questions = ORM::for_table('module_forms_questions')
                    ->table_alias('q')
                    ->select('q.id')
                    ->select('q.type_id')
                    ->select('q.question')
                    ->select('q.sorder')
                    ->select_expr('(SELECT COUNT(quest.id) FROM module_forms_questions quest WHERE q.id = quest.parent_id)', 'has_child')
                    ->join('module_forms_questions_forms', 'q.id = qf.question_id', 'qf')
                    ->join('module_forms_forms', 'qf.form_id = f.id', 'f')
                    ->where('qf.form_id', $ticket->form_id)
                    ->where_null('q.parent_id')
                    ->order_by_asc('sorder')
                    ->find_many();
            $ui2->assign('questions', $questions);

            // Busca as questões filhas (Grupo de questões)
            $child_questions = ORM::for_table('module_forms_questions')
                    ->table_alias('q')
                    ->select('q.id')
                    ->select('q.description')
                    ->select('q.parent_id')
                    ->select('q.type_id')
                    ->select('q.question')
                    ->select('q.sorder')
                    ->select('t.alias')
                    ->select('q.range_value')
                    ->join('module_forms_questions_forms', 'q.id = qf.question_id', 'qf')
                    ->join('module_forms_forms', 'qf.form_id = f.id', 'f')
                    ->join('module_forms_types', array('q.type_id', '=', 't.id'), 't')
                    ->where('qf.form_id', $ticket->form_id)
                    ->where_not_null('q.parent_id')
                    ->order_by_asc('sorder')
                    ->find_many();

            $count_question = 0;
            foreach ($child_questions as $question) {
                $options = ORM::for_table('module_forms_choices')->where('question_id', $question->id)->find_many();

                $child_questions[$count_question]->options = $options;
                $count_question++;
            }
            $ui2->assign('child_questions', $child_questions);

            $ui2->assign('ticket_form', $ticket_form);

            $form_data = ORM::for_table('module_helpdesk_form_data')->where('ticket_id', $ticket->id)->find_many();
//        var_dump($form_data[0]);exit;
            //tratamento no back para separar os dados  
            $answerCheck = array();
            if (count($form_data) > 0) {
                foreach ($form_data as $key => $f) {
                    if ($f->question_type == 'module_helpdesk_components') {

                        $tam1 = strripos($f->value, ')');
                        $part1 = substr($f->value, 0, $tam1);
                        $partFinal = strrchr($f->value, '| QTD:');
                        $f->component = trim(str_replace("(", "", $part1));
                        $f->qtd = str_replace("| QTD:", "", $partFinal);
                    } elseif ($f->question_type == 'checkbox') {
                        $field = explode(" | ", $f->field);
                        if (isset($answerCheck[$f->question_id])) {
                            unset($form_data[$key]); //remove o valor da data form
                        }
                        $answerCheck[$f->question_id][@$field[1]]['value'] = $f->value;
                        $answerCheck[$f->question_id][@$field[1]]['value_desc'] = $f->value == 1 ? $this->_L['Yes'] : $this->_L['No'];
                        $answerCheck[$f->question_id][@$field[1]]['field'] = @$field[0];
                        $answerCheck[$f->question_id][@$field[1]]['question_id'] = @$field[1];
                        $answerCheck[$f->question_id][@$field[1]]['name'] = @$field[2];
                    } else if ($f->question_type == 'bollean') {
                        $f->value = $f->value == 'Y' ? $this->_L['Yes'] : $this->_L['No'];
                    }
                }
            }

            $ui2->assign('form_data', $form_data);
            $ui2->assign('form_data_answer_check', $answerCheck);


            if (empty($idForm)) {
                $client = ORM::for_table('crm_accounts')->find_one($ticket->client_id);
                $ui2->assign('client', $client);


                $requester = ORM::for_table('crm_accounts')->find_one($ticket->responsible_id);
                $ui2->assign('responsible', $requester);

                $requester = ORM::for_table('sys_users')->find_one($ticket->requester_id);
                $ui2->assign('register', $requester);

                $requester = ORM::for_table('module_helpdesk_tickets_priority')->find_one($ticket->module_helpdesk_tickets_priority_id);
                $ui2->assign('priority_ticket', $requester);


                $requester = ORM::for_table('module_helpdesk_tickets_cat')->find_one($ticket->module_helpdesk_tickets_cat_id);
                $ui2->assign('cat_ticket', $requester);


                $requester = ORM::for_table('module_helpdesk_tickets_treatment_type')->find_one($ticket->module_helpdesk_tickets_treatment_type_id);
                $ui2->assign('type_ticket', $requester);



                $prods = $this->model->getProducts($ticket);
                $ui2->assign('products', $prods);
                if (count($prods) > 0) {
                    $requester = ORM::for_table('sys_items_category')->find_one($prods[0]->product_cat_id);
                    $ui2->assign('category', $requester);
                } else {
                    $ui2->assign('category', '');
                }
                $ui2->assign('newTypeModel', false);
            } else {
                $ui2->assign('newTypeModel', true);
            }
            $ui2->assign('ticket', $ticket);
            $ui2->assign('typeForm', 'modal');
            $ui2->assign('_st', $this->_L['module_helpdesk view ticket']);
            $ui2->assign('helper', $this->helper);
            if (count($form_data) > 0) {
                $ui2->assign('_include', 'ticket/view_edit_modal');
            } else {
                $ui2->assign('_include', 'ticket/view_modal');
            }
            return str_replace("'", "\'", $ui2->fetch('wrapper_clean.tpl'));
        } else {
            return "";
        }
    }

    public function view() {

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

        $view_type = isset($this->routes[4]) ? $this->routes[4] : null;

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

        if ($this->client_id > 0) {
            if ($ticket->client_id != $this->client_id) {
                r2(U . 'client/module_helpdesk/ticket/listall', 'e', $this->_L['Not Permited']);
            }
        }
        if (!$ticket) {
            die($this->_L['Not_Found']);
        }
        if ($ticket->deleted_at != null) {
            die($this->_L['Not_Found']);
        }


        $attach = ORM::for_table('module_helpdesk_tickets_attach')->where('module_helpdesk_tickets_id', $ticket->id)->find_many();

        if (count($attach) > 0) {
            $this->ui->assign('attachs', $attach);
        } else {
            $this->ui->assign('attachs', "");
        }


        $attachNote = ORM::for_table('module_helpdesk_tickets_type_attachment')->where('module_helpdesk_tickets_id', $ticket->id)->find_many();
        if (count($attachNote) > 0) {
            $this->ui->assign('attachsNote', $attachNote);
        } else {
            $this->ui->assign('attachsNote', "");
        }

        // Pego os formulários disponíveis
        $forms = ORM::for_table("module_forms_forms")->where('status', 1)->find_many();
        $this->ui->assign('forms', $forms);

        $ticket_form = null;
        if ($ticket->form_id) {
            $ticket_form = ORM::for_table("module_forms_forms")->find_one($ticket->form_id);

            // Busca as questões do formulário
            $questions = ORM::for_table('module_forms_questions')
                    ->table_alias('q')
                    ->select('q.id')
                    ->select('q.type_id')
                    ->select('q.question')
                    ->select('q.sorder')
                    ->select_expr('(SELECT COUNT(quest.id) FROM module_forms_questions quest WHERE q.id = quest.parent_id)', 'has_child')
                    ->join('module_forms_questions_forms', 'q.id = qf.question_id', 'qf')
                    ->join('module_forms_forms', 'qf.form_id = f.id', 'f')
                    ->where('qf.form_id', $ticket->form_id)
                    ->where_null('q.parent_id')
                    ->order_by_asc('sorder')
                    ->find_many();
            $this->ui->assign('questions', $questions);

            // Busca as questões filhas (Grupo de questões)
            $child_questions = ORM::for_table('module_forms_questions')
                    ->table_alias('q')
                    ->select('q.id')
                    ->select('q.description')
                    ->select('q.parent_id')
                    ->select('q.type_id')
                    ->select('q.question')
                    ->select('q.sorder')
                    ->select('t.alias')
                    ->select('q.range_value')
                    ->join('module_forms_questions_forms', 'q.id = qf.question_id', 'qf')
                    ->join('module_forms_forms', 'qf.form_id = f.id', 'f')
                    ->join('module_forms_types', array('q.type_id', '=', 't.id'), 't')
                    ->where('qf.form_id', $ticket->form_id)
                    ->where_not_null('q.parent_id')
                    ->order_by_asc('sorder')
                    ->find_many();

            $count_question = 0;
            foreach ($child_questions as $question) {
                $options = ORM::for_table('module_forms_choices')->where('question_id', $question->id)->find_many();

                $child_questions[$count_question]->options = $options;
                $count_question++;
            }
            $this->ui->assign('child_questions', $child_questions);
        }
        $this->ui->assign('ticket_form', $ticket_form);

        $form_data = ORM::for_table('module_helpdesk_form_data')->where('ticket_id', $ticket->id)->find_many();
//        var_dump($form_data[0]);exit;
        //tratamento no back para separar os dados  
        $answerCheck = array();
        if (count($form_data) > 0) {
            foreach ($form_data as $key => $f) {
                if ($f->question_type == 'module_helpdesk_components') {

                    $tam1 = strripos($f->value, ')');
                    $part1 = substr($f->value, 0, $tam1);
                    $partFinal = strrchr($f->value, '| QTD:');
                    $f->component = trim(str_replace("(", "", $part1));
                    $f->qtd = str_replace("| QTD:", "", $partFinal);
                } elseif ($f->question_type == 'checkbox') {
                    $field = explode(" | ", $f->field);
                    if (isset($answerCheck[$f->question_id])) {
                        unset($form_data[$key]); //remove o valor da data form
                    }
                    $answerCheck[$f->question_id][@$field[1]]['value'] = $f->value;
                    $answerCheck[$f->question_id][@$field[1]]['value_desc'] = $f->value == 1 ? $this->_L['Yes'] : $this->_L['No'];
                    $answerCheck[$f->question_id][@$field[1]]['field'] = @$field[0];
                    $answerCheck[$f->question_id][@$field[1]]['question_id'] = @$field[1];
                    $answerCheck[$f->question_id][@$field[1]]['name'] = @$field[2];
                } else if ($f->question_type == 'bollean') {
                    $f->value = $f->value == 'Y' ? $this->_L['Yes'] : $this->_L['No'];
                }
            }
        }

        $this->ui->assign('form_data', $form_data);
        $this->ui->assign('form_data_answer_check', $answerCheck);


        $client = ORM::for_table('crm_accounts')->find_one($ticket->client_id);
        $this->ui->assign('client', $client);


        $requester = ORM::for_table('crm_accounts')->find_one($ticket->responsible_id);
        $this->ui->assign('responsible', $requester);

        $requester = ORM::for_table('sys_users')->find_one($ticket->requester_id);
        $this->ui->assign('register', $requester);

        $requester = ORM::for_table('module_helpdesk_tickets_priority')->find_one($ticket->module_helpdesk_tickets_priority_id);
        $this->ui->assign('priority_ticket', $requester);


        $requester = ORM::for_table('module_helpdesk_tickets_cat')->find_one($ticket->module_helpdesk_tickets_cat_id);
        $this->ui->assign('cat_ticket', $requester);


        $requester = ORM::for_table('module_helpdesk_tickets_treatment_type')->find_one($ticket->module_helpdesk_tickets_treatment_type_id);
        $this->ui->assign('type_ticket', $requester);



        $prods = $this->model->getProducts($ticket);
        $this->ui->assign('products', $prods);
        if (count($prods) > 0) {
            $requester = ORM::for_table('sys_items_category')->find_one($prods[0]->product_cat_id);
            $this->ui->assign('category', $requester);
        } else {
            $this->ui->assign('category', '');
        }


        $css_arr = array('sweetalert/sweetalert',
            'dp/dist/datepicker.min',
            'ibilling/clockpicker/clockpicker'
        );
        $js_arr = array(
            '/../../../application/plugins/module_helpdesk/assets/js/ticket-view',
            'sweetalert/sweetalert',
            'dp/dist/datepicker.min',
            'ibilling/clockpicker/clockpicker');
        $assets_css = Asset::css($css_arr);
        $assets_js = Asset::js($js_arr);
        $this->ui->assign('xheader', $assets_css);
        $this->ui->assign('xfooter', $assets_js);

        $this->ui->assign('jsvar', '
            _L[\'module_helpdesk msg form offline\'] = \'' . $this->_L['module_helpdesk msg form offline'] . '\';'
        );



        $this->ui->assign('ticket', $ticket);
        $this->ui->assign('typeForm', 'window');
        $this->ui->assign('_st', $this->_L['module_helpdesk view ticket']);

        if ($view_type == 'pdf') {

            define('_MPDF_PATH', 'application/lib/mpdf/');

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

            $pdf_c = '';
            $ib_w_font = 'dejavusanscondensed';
            if ($config['pdf_font'] == 'default') {
                $pdf_c = 'c';
                $ib_w_font = 'Helvetica';
            }
            $mpdf = new mPDF($pdf_c, 'A4', '', '', 20, 15, 15, 25, 10, 10);
            //            $mpdf->SetProtection(array('print'));
            $mpdf->SetTitle($config['CompanyName'] . ' Invoice');
            $mpdf->SetAuthor($config['CompanyName']);
            $mpdf->SetWatermarkText(ib_lan_get_line($d['status']));
            $mpdf->showWatermarkText = true;
            $mpdf->watermark_font = $ib_w_font;
            $mpdf->watermarkTextAlpha = 0.1;
            $mpdf->SetDisplayMode('fullpage');

            if ($config['pdf_font'] == 'AdobeCJK') {
                $mpdf->useAdobeCJK = true;
                $mpdf->autoScriptToLang = true;
                $mpdf->autoLangToFont = true;
            }
            $pdf_tpl = 'application/plugins/module_helpdesk/assets/libs/pdf-x2.php';

            Event::trigger('invoices/before_pdf_render/', array($id));

            ob_start();

            require $pdf_tpl;

            $html = ob_get_contents();

            ob_end_clean();

            $mpdf->WriteHTML($html);

            if ($r_type == 'dl') {
                $mpdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'D'); # D
            } elseif ($r_type == 'inline') {
                $mpdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'I'); # D
            } elseif ($r_type == 'store') {

                $mpdf->Output('application/storage/temp/Invoice_' . $in . '.pdf', 'F'); # D
            } else {
                $mpdf->Output(date('Y-m-d') . _raid(4) . '.pdf', 'I'); # D
            }
        } elseif (count($form_data) > 0) {
            $this->ui->assign('_include', 'ticket/view_edit');
            $this->ui->display('wrapper.tpl');
        } else {
            $this->ui->assign('_include', 'ticket/view');
            $this->ui->display('wrapper.tpl');
        }
    }

    public function delete() {
        $type = $this->model->getOne(_post('id'));

        $this->model->deleteTicket($type);
        r2(U . 'module_helpdesk/ticket/listall', 's', $this->_L['delete_successful']);
    }

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

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

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

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

        echo json_encode($a);
    }

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

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

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

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

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

        echo json_encode($a);
    }

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

    public static function addSingnature($ticket_id, $file, $type = "singnature") {
        $dir = 'application/plugins/module_helpdesk/uploads/tickets/form/' . $ticket_id . '/' . $type;
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
        $img = $file;
        $img = str_replace('data:image/png;base64,', '', $img);
        $img = str_replace(' ', '+', $img);
        $data = base64_decode($img);
        $file = uniqid() . '.png';
        $success = file_put_contents($dir . '/' . $file, $data);
        if ($success) {
            return $file;
        } else {
            return false;
        }
    }

    public static function addAttachBase64($ticket_id, $file, $name, $type = "attach") {
        if (empty($file)) {
            return "";
        }
        $dir = 'application/plugins/module_helpdesk/uploads/tickets/form/' . $ticket_id . '/' . $type;
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
        $base_to_php = explode(',', $file);
        // the 2nd item in the base_to_php array contains the content of the image
        $data = base64_decode($base_to_php[1]);

        $ext = explode(".", $name);

        $file = uniqid() . '.' . $ext[count($ext) - 1];
        $success = file_put_contents($dir . '/' . $file, $data);
        if ($success) {
            return $file;
        } else {
            return "";
        }
    }

    public static function add_attach_form($ticket_id, $file, $type = null) {
        $uploader = new Uploader();
        $dir = 'application/plugins/module_helpdesk/uploads/tickets/form/' . $ticket_id . '/' . $type . "/";

        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
        $uploader->setDir($dir);
        $uploader->sameName(false);
        $uploader->setExtensions(array('jpg', 'jpeg', 'png', 'gif', 'pdf'));
        $uploader->setMaxSize(5);
        if ($uploader->uploadFile($file)) {
            $uploaded = $uploader->getUploadName();
            $file_name = $uploaded;
            return $file_name;
        } else {//upload failed
            return false;
        }
    }

    public function writeCSV($filename, $headings, $data) {

        //Use tab as field separator
        $newTab = "\t";
        $newLine = "\n";

        $fputcsv = count($headings) ? '"' . implode('"' . $newTab . '"', $headings) . '"' . $newLine : '';

        // Loop over the * to export
        if (!empty($data)) {
            foreach ($data as $item) {
                $fputcsv .= '"' . implode('"' . $newTab . '"', $item) . '"' . $newLine;
            }
        }

        //Convert CSV to UTF-16
        $encoded_csv = mb_convert_encoding(mb_strtoupper($fputcsv), 'UTF-16LE', 'UTF-8');
//        var_dump($data);exit;
//        $encoded_csv = str_replace("<br />", "\n", $encoded_csv);
        // Output CSV-specific headers
        header('Set-Cookie: fileDownload=true; path=/'); //This cookie is needed in order to trigger the success window.
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private", false);
        header("Content-Type: application/octet-stream");
        header("Content-Disposition: attachment; filename=\"$filename.csv\";");
        header("Content-Transfer-Encoding: binary");
        header('Content-Length: ' . strlen($encoded_csv));
        echo chr(255) . chr(254) . $encoded_csv; //php array convert to csv/excel

        exit;
    }

    public function getForms() {
        if (!empty($this->routes[3])) {
            echo '<script>';
            echo "formView[" . $this->routes[3] . "]=" . json_encode($this->viewModal($this->routes[3])) . ";";
            echo '</script>';
        }
    }

    public function getTypeForms() {
        $forms = ORM::for_table("module_forms_forms")->where('status', 1)->find_many();
        echo '<script>';
        echo ' var formatOSStatus=[];';
        echo " formatOSStatus['Atendence']='" . $this->helper->formatOSStatus('Atendence') . "';";
        echo " formatOSStatus['Closed']='" . $this->helper->formatOSStatus('Closed') . "';";
        echo " formatOSStatus['Open']='" . $this->helper->formatOSStatus('Open') . "';";

        if (count($forms)) {
            foreach ($forms as $f) {
//                  echo $this->viewModal(0, $f->id); die();
                echo " formTypeView[" . $f->id . "]=" . json_encode($this->viewModal(0, $f->id)) . ";";
            }
        }
        echo '</script>';
    }

    public function getForm() {
        echo $this->viewModal($this->routes[3]);
    }

    public function schedulingExportCsv() {
        $fileName = 'tickets_' . time();

        $results = array();

        $records = $this->listAll(true);

//        print_r($records);exit;

        foreach ($records as $record) {

            // trato o tipo de atendimento
            switch ($record['treatment_type']) {
                case 'module_helpdesk type remote':
                    $tipo_atendimento = 'Remoto';
                    break;
                case 'module_helpdesk type presential':
                    $tipo_atendimento = 'Presencial';
                    break;
                case 'module_helpdesk send equipament':
                    $tipo_atendimento = 'Envio e Conserto de equipamento';
                    break;
                default :
                    $tipo_atendimento = $record['treatment_type'];
                    break;
            }

            // trato a prioridade
            switch ($record['prioridade']) {
                case 'module_helpdesk priority Functional':
                    $prioridade = 'Funcional';
                    break;
                case 'module_helpdesk priority Partially stopped':
                    $prioridade = 'Parcialmente parado';
                    break;
                case 'module_helpdesk priority Stopped':
                    $prioridade = 'Parado';
                    break;
                default :
                    $prioridade = $record['prioridade'];
                    break;
            }

            $results[] = array(
                'ID' => $record['id'],
                'CRIADO EM' => $record['created_at'],
                'INICIO DO ATENDIMENTO' => $record['begin_at'],
                'FINALIZADO EM' => $record['closed_at'],
                'CLIENTE' => $record['client_account'],
                'STATUS' => $record['status'],
                'OBS' => strip_tags($record['description']),
                'RESPONSÁVEL' => $record['responsible_name'],
                'ATENDIMENTO' => $tipo_atendimento,
                'PRODUTO' => $record['desc_product'],
                'CATEGORIA DE CHAMADO' => $record['desc_category'],
                'CATEGORIA' => $record['product_cat'],
                'SOLICITANTE' => $record['requester_name'],
                'EMAIL SOLICITANTE' => $record['requester_email'],
                'PRIORIDADE' => $prioridade,
                'LOCAL DO ATENDIMENTO' => $record['treatment_type_local'],
                'SLA1' => $this->helper->transformSla($record['created_at'], $record['begin_at']),
                'SLA2' => $this->helper->transformSla($record['begin_at'], $record['closed_at'])
            );
        }
        $this->writeCSV($fileName, array_keys($results[0]), $results);
    }

}

function showGraph($title, $description, $identificador, $valueSeries, $listDay, $showBackground = false, $color = "#2196f3") {
    global $_L;
    $series = "{
                    name:'" . $title . "',
                    type:'line',    
                    smooth:true,
                    color: [
                    '" . $color . "'
                    ]," .
            ($showBackground ? "itemStyle: {normal: {areaStyle: {type: 'default'}}}," : "")
            . " data:[" . implode(",", $valueSeries) . "]
                }";

    return " $(function() { var " . $identificador . "_opt =  {
            title : {
                text:'" . $description . "',
                subtext: ''
            },
            tooltip : {
                trigger: 'axis'
            },
             legend: {
                data:['" . $title . "']
            },
            toolbox: {
                show : true,
                feature : {
                    mark : {show: true},
                    dataView : {show: true, readOnly: false, title : _L['Data View'],
                        lang: [_L['Data View'], _L['Cancel'], _L['Reset']] },
                    magicType : {show: true, title : {
                        line : 'Line',
                        bar : 'Bar',
                        stack : 'Stack',
                        tiled : 'Tiled',
                        force: 'Force',
                        chord: 'Chord',
                        pie: 'Pie',
                        funnel: 'Funnel'
                    }, type: ['line', 'bar', 'stack', 'tiled']},
                    restore : {show: true, title : 'Reset'},
                    saveAsImage : {show: true, title : _L['Save as Image'],
                        type : 'png',
                        lang : [_L['Click to Save']]}
                }
            },
            calculable : true,
            xAxis : [
                {
                    type : 'category',
                    boundaryGap : false,
                    data :[" . implode(",", $listDay) . "]
                }
            ],
            yAxis : [
                {
                    type : 'value'
                }
            ],
            series :
                    [
                " . $series . "
            ]
        };
        var " . $identificador . " = echarts.init(document.getElementById('" . $identificador . "'));
        " . $identificador . ".setOption(" . $identificador . "_opt);
    });";
}

Anon7 - 2022
AnonSec Team