<?php session_start();
/*                        Copyright 2023 Flávio Ribeiro

         This file is part of OCOMON.

         OCOMON is free software; you can redistribute it and/or modify
         it under the terms of the GNU General Public License as published by
         the Free Software Foundation; either version 3 of the License, or
         (at your option) any later version.
         OCOMON is distributed in the hope that it will be useful,
         but WITHOUT ANY WARRANTY; without even the implied warranty of
         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
         GNU General Public License for more details.

         You should have received a copy of the GNU General Public License
         along with Foobar; if not, write to the Free Software
         Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */

if (!isset($_SESSION['s_logado']) || $_SESSION['s_logado'] == 0) {
    $_SESSION['session_expired'] = 1;
    echo "<script>top.window.location = '../../index.php'</script>";
    exit;
}

require_once __DIR__ . "/" . "../../includes/include_geral_new.inc.php";
require_once __DIR__ . "/" . "../../includes/classes/ConnectPDO.php";

use includes\classes\ConnectPDO;

$conn = ConnectPDO::getInstance();

$imgsPath = "../../includes/imgs/";

$auth = new AuthNew($_SESSION['s_logado'], $_SESSION['s_nivel'], 2, 1);

$actionUrl = "../../ocomon/geral/get_full_tickets_table.php";

/* Campos customizados */
$custom_fields_full = getCustomFields($conn, null, 'ocorrencias');
$custom_fields_classes = [];
foreach ($custom_fields_full as $cfield) {
    $custom_fields_classes[] = $cfield['field_name'];
}
$custom_fields_classes_text = implode(",", $custom_fields_classes);


?>
<!DOCTYPE html>
<html lang="pt-BR">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="../../includes/css/estilos.css" />
    <link rel="stylesheet" type="text/css" href="../../includes/components/bootstrap/custom.css" />
    <link rel="stylesheet" type="text/css" href="../../includes/components/fontawesome/css/all.min.css" />
    <link rel="stylesheet" type="text/css" href="../../includes/components/datatables/datatables.min.css" />
    <link rel="stylesheet" type="text/css" href="../../includes/css/my_datatables.css" />
    <link rel="stylesheet" type="text/css" href="../../includes/css/switch_radio.css" />
	<link rel="stylesheet" type="text/css" href="../../includes/css/estilos_custom.css" />
	<link rel="stylesheet" type="text/css" href="../../includes/css/my_datatables_child_rows.css" />
    <link rel="stylesheet" type="text/css" href="../../includes/components/suneditor/node_modules/suneditor/dist/css/suneditor.min.css" />
	<link rel="stylesheet" type="text/css" href="../../includes/components/suneditor/node_modules/suneditor/src/assets/css/suneditor-contents.css" />


    <title><?= APP_NAME; ?>&nbsp;<?= VERSAO; ?></title>

    <style>
        pre {
            white-space: pre-wrap;
            word-wrap: break-word;
            overflow-wrap: break-word;
            word-break: break-all;
            font-size: 11px;
            font-family: FreeSans, sans-serif;
            line-height: 1.5em;
        }

        .bt-expand:before {
            font-family: "Font Awesome\ 5 Free";
            content: "\f078";
            font-weight: 900;
            font-size: 16px;
        }

        .bt-collapse:before {
            font-family: "Font Awesome\ 5 Free";
            content: "\f077";
            font-weight: 900;
            font-size: 16px;
        }

        p.textarea {
			border: 1px solid #ccc;
			font-size: 14px;
			padding: 8px;
			width: 100%;
		}

    </style>

</head>

<body>
    <div class="container">
        <div id="idLoad" class="loading" style="display:none"></div>
    </div>

    <div class="container-fluid">

        <div class="modal" id="modal" tabindex="-1" style="z-index:9001!important">
            <div class="modal-dialog modal-xl">
                <div class="modal-content">
                    <div id="divDetails" style="position:relative">
                        <iframe id="ticketInfo"  frameborder="0" style="position:absolute;top:0px;width:95%;height:100vh;"></iframe>
                    </div>
                </div>
            </div>
        </div>

        <input type="hidden" name="report-mainlogo" class="report-mainlogo" id="report-mainlogo"/>
        <input type="hidden" name="logo-base64" id="logo-base64"/>
        <?php

            if (empty($_GET)) {
                echo message ('warning', 'Ooops!', TRANS('INFO_MISSING_TO_PROCEED'), '', '', 1);
                return;
            }

            $dataGet = json_encode($_GET);

            if (isset($_SESSION['flash']) && !empty($_SESSION['flash'])) {
                echo $_SESSION['flash'];
                $_SESSION['flash'] = '';
            }
        ?>
    </div>

    <div id="print-info" class="d-none">&nbsp;</div>
    <input type="hidden" name="custom_fields_classes_text" id="custom_fields_classes_text" value="<?= $custom_fields_classes_text; ?>">
    <input type="hidden" name="header_ticket_full_description" id="header_ticket_full_description" value="<?= TRANS('TICKET_FULL_DESCRIPTION'); ?>">

    <div class="container-fluid">
        <div id="divTicketsList">
        </div>
    </div>

    <script src="../../includes/javascript/funcoes-3.0.js"></script>
    <script src="../../includes/components/jquery/jquery.js"></script>
    <script type="text/javascript" charset="utf8" src="../../includes/components/datatables/datatables.js"></script>
    <script src="../../includes/components/jquery/jquery.initialize.min.js"></script>
    <script src="../../includes/components/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="./js/smart_search_columns.js"></script>
    <script src="../../includes/components/suneditor/node_modules/suneditor/dist/suneditor.min.js"></script>
    <script src="../../includes/components/suneditor/node_modules/suneditor/src/lang/pt_br.js"></script>
	<script src="../../includes/javascript/format_bar.js"></script>

    <script>
        $(function() {


            let hiddenColunsCookie = getCookie('oc_cf_hidden_columns');
            let hiddenColunsCookieArray = hiddenColunsCookie.split(',');
            let customFieldsClassesText = $('#custom_fields_classes_text').val();
            let customFieldsClassesArray = customFieldsClassesText.split(',');

            var allColumns = reportAllColumns
            .concat(customFieldsClassesArray);
            
            var defaultHiddenColumns = hiddenColunsCookieArray

            if (defaultHiddenColumns == null || defaultHiddenColumns.length == 0 || defaultHiddenColumns == '') {
                defaultHiddenColumns = reportDefaultHiddenColumns.concat(customFieldsClassesArray);
            }

            let columnsOrderCookie = getCookie('oc_cf_columns_order');
            let colunsOrderCookieArray = columnsOrderCookie.split(',');
            var defaultColumnsOrder = colunsOrderCookieArray;

            $(function() {
                $('[data-toggle="popover"]').popover()
            });

            $('.popover-dismiss').popover({
                trigger: 'focus'
            });

            var loading = $(".loading");
            $(document).ajaxStart(function() {
                loading.show();
            });

            $(document).ajaxStop(function() {
                loading.hide();
            });

            setLogoSrc();

            $.ajax({
                url: '<?= $actionUrl;?>',
                method: 'POST',
                data: <?= $dataGet; ?> /* dados via get */,
            }).done(function(response) {
                $('#divTicketsList').html(response);
            });

            /* Adicionei o mutation observer em função dos elementos que são adicionados após o carregamento do DOM */
            var obs2 = $.initialize("#table_info", function() {
                $('#table_info').html($('#table_info_hidden').html());
                $('#print-info').html($('#table_info').html());
                
                /* Collumn resize */
                var pressed = false;
                var start = undefined;
                var startX, startWidth;

                $("table td").mousedown(function(e) {
                    start = $(this);
                    pressed = true;
                    startX = e.pageX;
                    startWidth = $(this).width();
                    $(start).addClass("resizing");
                });

                $(document).mousemove(function(e) {
                    if (pressed) {
                        $(start).width(startWidth + (e.pageX - startX));
                    }
                });

                $(document).mouseup(function() {
                    if (pressed) {
                        $(start).removeClass("resizing");
                        pressed = false;
                    }
                });
                /* end Collumn resize */

            }, {
                target: document.getElementById('divTicketsList')
            }); /* o target limita o scopo do mutate observer */



            /* Adicionei o mutation observer em função dos elementos que são adicionados após o carregamento do DOM */
            var obs = $.initialize("#table_tickets_queue", function() {
                
                var criterios = $('#divCriterios').text();

                function setTitles() {
                    var buttons = $( 'a.buttons-columnVisibility' );
                    buttons.each(function( index ) {
                        var tooltip =  $( this ).text() ;
                        $( this ).attr( 'title', tooltip );
                    });
                }
                
                var table = $('#table_tickets_queue').DataTable({

                    searching: false,
                    info: false,
                    paging: true,
                    // pageLength: 10,
                    deferRender: true,
                    // fixedHeader: true,
                    // scrollX: 300, /* para funcionar a coluna fixa */
                    // fixedColumns: true,
                    columnDefs: [
                        {
                            targets: 'details-control',
                            className: 'dt-control',
                            orderable: false,
                            // data: null,
                            // defaultContent: '<i class="fas fa-plus-circle text-primary" title="Clique para expandir"></i>'
                        },
                        
                        {
                            targets: defaultHiddenColumns,
                            visible: false,
                        },
                        {
                            targets: reportNotOrderable,
                            orderable: false,
                            searchable: false,
                        },
                        {
                            targets: reportNotSearchable,
                            searchable: false,
                        },
                    ],

                    colReorder: {
                        iFixedColumns: 1,
                        order : defaultColumnsOrder,
                    },

                    "language": {
                        "url": "../../includes/components/datatables/datatables.pt-br.json"
                    },

                });

                new $.fn.dataTable.Buttons(table,{
                    
                    buttons: [
                        {
                            extend: 'print',
                            text: '<?= TRANS('SMART_BUTTON_PRINT', '', 1)?>',
                            title: '<?= TRANS('SMART_CUSTOM_REPORT_TITLE', '', 1)?>',
                            // message: 'Relatório de Ocorrências',
                            message: $('#print-info').html(),
                            autoPrint: true,

                            customize: function(win) {
                                $(win.document.body).find('table').addClass('display').css('font-size', '10px');
                                $(win.document.body).find('tr:nth-child(odd) td').each(function(index) {
                                    $(this).css('background-color', '#f9f9f9');
                                });
                                $(win.document.body).find('h1').css('text-align', 'center');
                            },
                            exportOptions: {
                                columns: ':visible'
                            },

                        },
                        {
                            extend: 'copyHtml5',
                            text: '<?= TRANS('SMART_BUTTON_COPY', '', 1)?>',
                            exportOptions: {
                                columns: ':visible'
                            }
                        },
                        {
                            extend: 'excel',
                            text: "Excel",
                            exportOptions: {
                                columns: ':visible'
                            },
                            filename: '<?= TRANS('SMART_CUSTOM_REPORT_FILE_NAME', '', 1);?>-<?= date('d-m-Y-H:i:s');?>',
                        },
                        {
                            extend: 'csvHtml5',
                            text: "CVS",
                            exportOptions: {
                                columns: ':visible'
                            },

                            filename: '<?= TRANS('SMART_CUSTOM_REPORT_FILE_NAME', '', 1);?>-<?= date('d-m-Y-H:i:s');?>',
                        },
                        {
                            extend: 'pdfHtml5',
                            text: "PDF",

                            exportOptions: {
                                columns: ':visible',
                            },
                            title: '<?= TRANS('SMART_CUSTOM_REPORT_TITLE', '', 1);?>',
                            filename: '<?= TRANS('SMART_CUSTOM_REPORT_FILE_NAME', '', 1);?>-<?= date('d-m-Y-H:i:s');?>',
                            orientation: 'landscape',
                            pageSize: 'A4',

                            customize: function(doc) {
                                var criterios = $('#divCriterios').text()
                                var rdoc = doc;
                                var rcout = doc.content[doc.content.length - 1].table.body.length - 1;
                                doc.content.splice(0, 1);
                                var now = new Date();
                                var jsDate = now.getDate() + '/' + (now.getMonth() + 1) + '/' + now.getFullYear() + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
                                doc.pageMargins = [30, 70, 30, 30];
                                doc.defaultStyle.fontSize = 8;
                                doc.styles.tableHeader.fontSize = 9;

                                doc['header'] = (function(page, pages) {
                                    return {
                                        columns: [
                                            {
                                                margin: [20, 10, 0, 0],
                                                image: getLogoSrc(),
                                                width: getLogoWidth()
                                            } ,
                                            {
                                                table: {
                                                    widths: ['100%'],
                                                    headerRows: 0,
                                                    body: [
                                                        [{
                                                            text: '<?= TRANS('SMART_CUSTOM_REPORT_TITLE', '', 1); ?>',
                                                            alignment: 'center',
                                                            
                                                            fontSize: 14,
                                                            bold: true,
                                                            margin: [0, 20, 0, 0]
                                                            
                                                        }],
                                                    ]
                                                },
                                                layout: 'noBorders',
                                                margin: 10,
                                            }
                                        ],
                                        
                                    }
                                });

                                doc['footer'] = (function(page, pages) {
                                    return {
                                        columns: [{
                                                alignment: 'left',
                                                text: ['Criado em: ', {
                                                    text: jsDate.toString()
                                                }]
                                            },
                                            {
                                                alignment: 'center',
                                                text: 'Total ' + rcout.toString() + ' linhas'
                                            },
                                            {
                                                alignment: 'right',
                                                text: ['página ', {
                                                    text: page.toString()
                                                }, ' de ', {
                                                    text: pages.toString()
                                                }]
                                            }
                                        ],
                                        margin: 10
                                    }
                                });

                                var objLayout = {};
                                objLayout['hLineWidth'] = function(i) {
                                    return .8;
                                };
                                objLayout['vLineWidth'] = function(i) {
                                    return .5;
                                };
                                objLayout['hLineColor'] = function(i) {
                                    return '#aaa';
                                };
                                objLayout['vLineColor'] = function(i) {
                                    return '#aaa';
                                };
                                objLayout['paddingLeft'] = function(i) {
                                    return 5;
                                };
                                objLayout['paddingRight'] = function(i) {
                                    return 35;
                                };
                                doc.content[doc.content.length - 1].layout = objLayout;

                            }

                        },
                        {
                            extend: 'colvis',
                            text: '<?= TRANS('SMART_BUTTON_MANAGE_COLLUMNS', '', 1)?>',
                            // className: 'btn btn-primary',
                            // columns: ':gt(0)'
                            collectionLayout: 'dropdown four-column',
                        },
                        {
                            text: '<?= TRANS('REMEMBER_VISIBLE_COLUMNS', '', 1) ?>',
                            attr: {
                                title: '<?= TRANS('REMEMBER_VISIBLE_COLUMNS', '', 1) ?>',
                                id: 'customButton'
                            },
                        },
                        {
                            text: '&nbsp;<?= TRANS('EXPAND_ALL_DESCRIPTIONS', '', 1) ?>',
                            attr: {
                                title: '<?= TRANS('EXPAND_ALL_DESCRIPTIONS', '', 1) ?>',
                                id: 'expandAllChildRowsButton',
                                class: 'bt-expand btn btn-primary'
                            },
                        },
                        {
                            text: '&nbsp;<?= TRANS('COLLAPSE_ALL_DESCRIPTIONS', '', 1) ?>',
                            attr: {
                                title: '<?= TRANS('COLLAPSE_ALL_DESCRIPTIONS', '', 1) ?>',
                                id: 'collapseAllChildRowsButton',
                                class: 'bt-collapse btn btn-primary'
                            },
                        }
                    ]
                });

                // ===== EVENT LISTENER PARA EXPANDIR/RECOLHER =====
                $('#table_tickets_queue tbody').on('click', 'td.dt-control', function() {
                    var tr = $(this).closest('tr');
                    var row = table.row(tr);
                    var icon = $(this).find('i');

                    if (row.child.isShown()) {
                        // RECOLHER A CHILD ROW
                        row.child.hide();
                        tr.removeClass('shown');
                        icon.removeClass('fa-minus-circle text-danger')
                            .addClass('fa-plus-circle text-primary')
                            .attr('title', 'Clique para expandir');
                        
                        // console.log('Child row recolhida para ticket #' + $(row.node()).data('id'));
                    } else {
                        // EXPANDIR A CHILD ROW
                        row.child(formatChildRow(row)).show();
                        tr.addClass('shown');
                        icon.removeClass('fa-plus-circle text-primary')
                            .addClass('fa-minus-circle text-danger')
                            .attr('title', 'Clique para recolher');


                        if ($('#display_' + $(row.node()).data('id')).length == 0) {
                            displayContent($('#display_' + $(row.node()).data('id')));
                            $('#suneditor_display_' + $(row.node()).data('id')).addClass('se-only-display');
                        }
                        

                        // console.log('Child row expandida para ticket #' + $(row.node()).data('id'));
                    }
                });

                table.buttons().container()
                    .appendTo($('.display-buttons:eq(0)', table.table().container()));

                table.on( 'buttons-action', function ( e, buttonApi, dataTable, node, config ) {
                    setTitles();
                });


            }, {
                target: document.getElementById('divTicketsList')
            }); /* o target limita o scopo do mutate observer */


            /* Observando o gerenciamento de colunas*/
            var obsColvis = $.initialize("#table_tickets_queue", function() {

                var table2 = $('#table_tickets_queue').DataTable();

                $('#customButton').on('click', function(){
                    defaultHiddenColumns = getHiddenColumns(table2, allColumns);

                    defaultColumnsOrder = getColumnsOrder(table2);
                });

                $('#expandAllChildRowsButton').on('click', function(){
                    expandAllChildRows(table2);
                });
                $('#collapseAllChildRowsButton').on('click', function(){
                    collapseAllChildRows(table2);
                });

            }, {
                target: document.getElementById('divTicketsList')
            }); /* o target limita o scopo do mutate observer */

        });


        function getHiddenColumns(table, columnsClasses) {
            // console.log(table.column('.aberto_por').visible() === true ? 'visible' : 'not visible');
            let hiddenColumns = []

            for (let i in columnsClasses) {
                // console.log(columnsClasses[i]);
                // console.log(table.column('.' + columnsClasses[i]).visible() === true ? columnsClasses[i] + ' visible' : columnsClasses[i] + ' not visible');
                if (table.column('.' + columnsClasses[i]).visible() !== true) {
                    hiddenColumns.push(columnsClasses[i]) 
                }
            }

            /* Fazer um ajax para gravar cookies com o array de colunas ocultas - Esse array deve ser consultado 
            toda a vez que o datatables for carregado */
            $.ajax({
                url: 'set_cookie_recent_columns.php',
                type: 'POST',
                data: {
                    columnsClasses: hiddenColumns,
                    app: 'cardTickets'
                },
                success: function(data) {
                    // console.log(data);
                }
            });

            defaultHiddenColumns = hiddenColumns;
            return hiddenColumns;
        }

        function getColumnsOrder(table) {
            let columnsOrder = []

            columnsOrder = table.colReorder.order();

            $.ajax({
                url: 'set_cookie_columns_order.php',
                type: 'POST',
                data: {
                    columnsOrder: columnsOrder,
                    app: 'cardTickets'
                },
                success: function(data) {
                    // console.log(data);
                }
            });

            defaultColumnsOrder = columnsOrder;
            return columnsOrder;
        }


        function openTicketInfo(ticket) {
            let location = 'ticket_show.php?numero=' + ticket;
            // $("#divDetails").load(location);
            $("#ticketInfo").attr('src',location)
            $('#modal').modal();

			// popup_alerta_wide(location);
        }

        function getLogoSrc() {
            return $('#logo-base64').val() ?? '';
        }

        function setLogoSrc() {

            let logoName = $('#report-mainlogo').css('background-image');

            if (logoName == 'none') {
                return;
            }
            logoName = logoName.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')
            logoName = logoName.split('/').pop();

            $.ajax({
                url: './get_reports_logo.php',
                method: 'POST',
                data: {
                    'logo_name': logoName
                },
                dataType: 'json',
            }).done(function(data) {

                if (!data.success) {
                    return;
                }
                $('#logo-base64').val(data.logo);
            });
        }

        function getLogoWidth() {
            let logoWidth = $('#report-mainlogo').width() ?? 150;
            return logoWidth;
        }

        function formatChildRow(row) {
            let tr = $(row.node()); // Obtém o elemento <tr> do DOM
            let description = tr.data('description');
            let ticket = tr.data('id');

            // Se os dados estiverem disponíveis diretamente no objeto de dados da linha,
            // você pode acessá-los assim (assumindo que 'description' e 'id' são nomes de colunas ou propriedades dos dados da linha):
            // let rowData = row.data();
            // let description = rowData.description; // ou rowData[INDEX_DA_COLUNA_DESCRIPTION]
            // let ticket = rowData.id; // ou rowData[INDEX_DA_COLUNA_ID]

            // '<i class="fas fa-file-alt text-primary me-2"></i> ' +

            return '<div class="child-row-content">' +
                '<div class="description-title">' + 
                $('#header_ticket_full_description').val() +
                + ticket +
                '</div>' +
                '<div class="description-box" id="display_'+ ticket +'">' +
                description +
                '</div>' +
                '</div>';
        }

        function tooggleChildRows(table) {
            table.rows().every(function() {
                // 'this' aqui já é a instância da linha (DataTables row object)
                var row = this; 
                var tr = $(row.node()); // Obtém o elemento <tr> diretamente da instância da linha
                var icon = tr.find('td.dt-control i');

                if (!row.child.isShown()) {
                    // Expande a child row, passando a instância da linha para formatChildRow
                    row.child(formatChildRow(row)).show();
                    tr.addClass('shown');
                    icon.removeClass('fa-plus-circle text-primary')
                        .addClass('fa-minus-circle text-danger')
                        .attr('title', 'Clique para recolher');
                } else {
                    row.child.hide();
                    tr.removeClass('shown');
                    icon.removeClass('fa-minus-circle text-danger')
                        .addClass('fa-plus-circle text-primary')
                        .attr('title', 'Clique para expandir');
                }
            });
        }

        function expandAllChildRows(table) {
            table.rows().every(function() {
                // 'this' aqui já é a instância da linha (DataTables row object)

                // var rowData = this.data();
                // console.log(rowData);



                var row = this; 
                var tr = $(row.node()); // Obtém o elemento <tr> diretamente da instância da linha
                var icon = tr.find('td.dt-control i');
                row.child(formatChildRow(row)).show();
                tr.addClass('shown');
                icon.removeClass('fa-plus-circle text-primary')
                    .addClass('fa-minus-circle text-danger')
                    .attr('title', 'Clique para recolher');
            });
        }

        function collapseAllChildRows(table) {
            table.rows().every(function() {
                // 'this' aqui já é a instância da linha (DataTables row object)
                var row = this; 
                var tr = $(row.node()); // Obtém o elemento <tr> diretamente da instância da linha
                var icon = tr.find('td.dt-control i');
                row.child.hide();
                tr.removeClass('shown');
                icon.removeClass('fa-minus-circle text-danger')
                    .addClass('fa-plus-circle text-primary')
                    .attr('title', 'Clique para expandir');
            });
        }


    </script>
</body>

</html>