<?php
/* Copyright 2025 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
 */ session_start();

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();

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

$isAdmin = $_SESSION['s_nivel'] == 1;

$json = 0;
$json2 = 0;


?>
<!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/jquery/datetimepicker/jquery.datetimepicker.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/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/bootstrap-select/dist/css/bootstrap-select.min.css" />
    <link rel="stylesheet" type="text/css" href="../../includes/css/my_bootstrap_select.css" />
	<link rel="stylesheet" type="text/css" href="../../includes/css/estilos_custom.css" />

    <style>

        caption {
            /* caption-side: top; */
            line-height: 1.8em;
        }

        caption.title {
            caption-side: top;
            /* font-size: large; */
        }

        span.title {
            font-size: large;
        }
        .chart-container {
            position: relative;
            /* height: 100%; */
            max-width: 100%;
            margin-left: 10px;
            margin-right: 10px;
            margin-bottom: 30px;
        }

    </style>

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

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


    <div class="container-fluid">
        <h5 class="my-4"><i class="fas fa-hand-holding-usd text-secondary"></i>&nbsp;<?= TRANS('REPORT_TICKETS_MVP'); ?></h5>
        <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="ticketsInfo"  frameborder="0" style="position:absolute;top:0px;width:100%;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 (isset($_SESSION['flash']) && !empty($_SESSION['flash'])) {
            echo $_SESSION['flash'];
            $_SESSION['flash'] = '';
        }

        ?>
        <input type="hidden" name="treater" value="<?= $_SESSION['s_uid']; ?>"/>
        <div id="divResult"></div>
        <div id="msg_1" class="d-none">
            <?= message('info','', TRANS('MSG_REPORT_TICKETS_MVP'), '', '', true); ?>
        </div>
        <!-- <div id="display-buttons" class="display-buttons d-none d-print-none"></div> -->
        <div id="table" class="table-responsive"></div>
        <div class="w-100"></div>
        <div id="table_target_done" class="table-responsive"></div>

        <div class="chart-container" id="container01">
            <canvas id="performanceChart"></canvas>
        </div>
    </div>
        
    <script src="../../includes/javascript/funcoes-3.0.js"></script>
    <script src="../../includes/components/jquery/jquery.js"></script>
    <script src="../../includes/components/jquery/jquery.initialize.min.js"></script>
    <script type="text/javascript" charset="utf8" src="../../includes/components/datatables/datatables.js"></script>
    <script src="../../includes/components/jquery/datetimepicker/build/jquery.datetimepicker.full.min.js"></script>
    <script src="../../includes/components/bootstrap/js/bootstrap.bundle.js"></script>
    <script type="text/javascript" src="../../includes/components/chartjs/dist/Chart.min.js"></script>
    <script type="text/javascript" src="../../includes/components/chartjs/chartjs-plugin-colorschemes/dist/chartjs-plugin-colorschemes.js"></script>
    <script type="text/javascript" src="../../includes/components/chartjs/chartjs-plugin-datalabels/chartjs-plugin-datalabels.min.js"></script>
    
    <script src="../../includes/components/bootstrap-select/dist/js/bootstrap-select.min.js"></script>

    <script type='text/javascript'>
        $(function() {
            
            $('#modal').on('hidden.bs.modal', function(){
                $("#ticketsInfo").attr('src','');
            });

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

            setLogoSrc();

            $.ajax({
                url: './report_tickets_mvp_process.php',
                method: 'POST',
                data: {
                    action: 'my_tickets_mvp',
                    treater: $('#treater').val(),
                    current_period: 1,
                    state: 4
                },
                dataType: 'json',
            }).done(function(data) {

                if (!data.success) {
                    $('#divResult').html(data.message);
                    $('input, select, textarea').removeClass('is-invalid');
                    if (data.field_id != "") {
                        $('#' + data.field_id).focus().addClass('is-invalid');
                    }
                    $('#table').html('');
                    $('#table_target_done').html('');
                    $('#container01').empty();
                    $('#container02').empty();
                    $('#performanceChart').empty();
                    $("#idSubmit").prop("disabled", false);
                } else {
                    /* Aqui ocorrerá as chamadadas para a montagem da tabela e também para os gráficos */
                    // $('#msg_1').removeClass('d-none');
                    
                    $('#container01').empty();
                    $('#container01').append('<canvas id="performanceChart"></canvas>');
                    
                    
                    $('#display-buttons').empty().removeClass('d-none');
                    $('#display-buttons-2').empty().removeClass('d-none');
                    // $('#msg_2').removeClass('d-none');

                    
                    let table = '<table id="table_tickets_mvp" class="table table-striped table-bordered" cellspacing="0" width="100%">';
                    table += '<caption id="table_caption" class="title"><span class="title">' + data['tickets'].title + '</span><br />' + data.criteria + '</caption>';

                    table += '<thead>';
                        table += '<tr class="header table-borderless">';
                            table += '';
                            table += '<td class="line"><?= mb_strtoupper(TRANS('TICKET_NUMBER')); ?></td>';
                            table += '<td class="line"><?= mb_strtoupper(TRANS('ISSUE_TYPE')); ?></td>';
                            table += '<td class="line"><?= mb_strtoupper(TRANS('OPENING_DATE')); ?></td>';
                            table += '<td class="line"><?= mb_strtoupper(TRANS('FIRST_RESPONSE')); ?></td>';
                            table += '<td class="line"><?= mb_strtoupper(TRANS('FIELD_DATE_CLOSING')); ?></td>';
                            table += '<td class="line"><?= mb_strtoupper(TRANS('LEVEL')); ?></td>';
                            table += '<td class="line"><?= mb_strtoupper(TRANS('ISSUE_WEIGHT')); ?></td>';
                            table += '<td class="line"><?= mb_strtoupper(TRANS('UST_TASK')); ?></td>';
                        table += '</tr>';

                    table += '</thead>';
                    table += '</tbody>';
                    let totalRecords = 0;
                    for (var i in data['tickets']) {

                        if (data['tickets'][i].numero !== undefined) {
                            table += '<tr>';
                            table += '<td class="line"><span class="ticket-number" data-ticket="' + data['tickets'][i].numero + '">' + data['tickets'][i].numero + '</span></td>';
                            table += '<td class="line">' + data['tickets'][i].problema + '</td>';
                            table += '<td class="line" data-sort="' + data['tickets'][i].data_abertura + '">' + data['tickets'][i].data_abertura_br + '</td>';
                            table += '<td class="line" data-sort="' + data['tickets'][i].data_atendimento + '">' + data['tickets'][i].data_atendimento_br + '</td>';
                            table += '<td class="line" data-sort="' + data['tickets'][i].data_fechamento + '">' + data['tickets'][i].data_fechamento_br + '</td>';
                            table += '<td class="line">' + data['tickets'][i].level_name + '</td>';
                            table += '<td class="line">' + data['tickets'][i].weight + '</td>';
                            table += '<td class="line">' + data['tickets'][i].ticket_price_brl + '</td>';
                            
                            table += '</tr>';
                        }
                    }
                    table += '</tbody>';
                    table += '<tfoot>';
                        table += '<tr class="header table-borderless">';
                            table += '<td></td>';
                            table += '<td></td>';
                            table += '<td></td>';
                            table += '<td></td>';
                            table += '<td></td>';
                            table += '<td></td>';
                            table += '<td class="line">' + data['tickets'].totalWeight + '</td>';
                            table += '<td class="line">' + data['tickets'].totalPrice + '</td>';
                        table += '</tr>';
                    table += '</tfoot>';
                    table += '</table>';

                    $('#table').html(table);


                    /* Quadro mpv atingido por operadores */
                    let tablePercentualDone = '<table id="table_perncentual_done" class="table table-striped table-bordered" cellspacing="0" width="100%">';
                    tablePercentualDone += '<caption id="table_percentual_done_caption" class="title"><span class="title">' + data['tickets'].operators_title + '</span><br />' + data.criteria + '</caption>';

                    tablePercentualDone += '<thead>';
                        tablePercentualDone += '<tr class="header table-borderless">';
                            tablePercentualDone += '';
                            tablePercentualDone += '<td class="line"><?= mb_strtoupper(TRANS('MVP_TARGET')); ?></td>';
                            tablePercentualDone += '<td class="line"><?= mb_strtoupper(TRANS('WORKER')); ?></td>';
                            tablePercentualDone += '<td class="line"><?= mb_strtoupper(TRANS('UST')); ?></td>';
                            tablePercentualDone += '<td class="line"><?= mb_strtoupper(TRANS('AREA')); ?></td>';
                            tablePercentualDone += '<td class="line"><?= mb_strtoupper(TRANS('PERCENT_OF_TARGET')); ?></td>';
                        tablePercentualDone += '</tr>';

                    tablePercentualDone += '</thead>';
                    tablePercentualDone += '</tbody>';
                    let totalOperatorsRecords = 0;
                    for (var i in data['operators']) {

                        if (data['operators'][i].name !== undefined) {
                            tablePercentualDone += '<tr>';
                            tablePercentualDone += '<td class="line">' + data['operators'][i].mvp_target + '</td>';
                            tablePercentualDone += '<td class="line">' + data['operators'][i].name + '</td>';
                            tablePercentualDone += '<td class="line">' + data['operators'][i].ust_brl + '</td>';
                            tablePercentualDone += '<td class="line">' + data['operators'][i].area + '</td>';
                            tablePercentualDone += '<td class="line">' + data['operators'][i].percentual_done + '</td>';
                            
                            tablePercentualDone += '</tr>';
                        }
                    }
                    tablePercentualDone += '</tbody>';
                    tablePercentualDone += '<tfoot>';
                        tablePercentualDone += '<tr class="header table-borderless">';
                            tablePercentualDone += '<td></td>';
                            tablePercentualDone += '<td></td>';
                            tablePercentualDone += '<td class="line">' + data['tickets'].totalPrice + '</td>';
                            tablePercentualDone += '<td></td>';
                            tablePercentualDone += '<td></td>';
                        tablePercentualDone += '</tr>';
                    tablePercentualDone += '</tfoot>';
                    
                    tablePercentualDone += '</table>';

                    $('#table_target_done').html(tablePercentualDone);



                    /* Gráfico */
                    var labels = data['chart_1']['labels'];
                    var ustData = data['chart_1']['usts'];
                    var ustDataBrl = data['chart_1']['usts_brl']; // Rótulos formatados
                    var mvpTargetData = data['chart_1']['mvp_targets'];

                    // console.log("Dados de rótulos formatados (usts_brl):", ustDataBrl); // Depuração

                    var ctx = document.getElementById('performanceChart').getContext('2d');

                    Chart.plugins.register(ChartDataLabels);

                    var performanceChart = new Chart(ctx, {
                        type: 'bar',
                        data: {
                            labels: labels,
                            datasets: [
                                {
                                    label: 'UST',
                                    data: ustData,
                                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                                    borderColor: 'rgba(75, 192, 192, 1)',
                                    borderWidth: 1,
                                    type: 'bar'
                                },
                                {
                                    label: 'Meta',
                                    data: mvpTargetData,
                                    backgroundColor: 'rgba(255, 99, 132, 0.2)',
                                    borderColor: 'rgba(255, 99, 132, 1)',
                                    borderWidth: 2,
                                    type: 'line',
                                    borderDash: [5, 5],
                                    fill: false,
                                    lineTension: 0, // Torna a linha reta
                                    pointStyle: 'circle', // circle | cross | crossRot | dash | line | rect | rectRot | star | triangle
                                    pointRadius: 1, // Tamanho dos marcadores
                                    pointHoverRadius: 18 // Tamanho dos marcadores ao passar o mouse
                                }
                            ]
                        },
                        options: {
                            scales: {
                                
                                // xAxes: [{
                                //     // type: 'category', // Garante que o eixo X seja tratado como categórico
                                //     ticks: {
                                //         // userCallback: function(value, index, values) {
                                //         callback: function(value, index, values) {
                                //             console.log("Callback do eixo X chamado:", value, index, ustDataBrl[index]); // Depuração
                                //             return ustDataBrl[index]; // Exibe os rótulos formatados
                                //         }
                                //     }
                                // }],
                                yAxes: [{
                                    ticks: {
                                        beginAtZero: true,
                                        callback: function(value, index, values) {
                                            return value.toFixed(2); // Formata os valores do eixo Y com 2 casas decimais
                                        }
                                    }
                                }]
                            },

                            plugins: {
                                datalabels: {
                                    anchor: 'center', // Posiciona o rótulo no centro da coluna - center | end | start
                                    align: 'center',
                                    // color: '#000', // Cor do texto
                                    // font: {
                                    //     weight: 'bold' // Estilo da fonte
                                    // },
                                    formatter: function(value, context) {
                                        // Verifica se o valor é um número antes de formatar
                                        if (typeof value === 'number' && !isNaN(value)) {
                                            // return 'R$ ' + value.toFixed(2).replace('.', ',');
                                            return value.toFixed(2).replace('.', ',');
                                        } else {
                                            // return ''; // Retorna vazio se o valor não for um número
                                            return value.replace('.', ',');
                                        }
                                    }
                                },

                                /* Não funciona */
                                // tooltip: {
                                //     callbacks: {
                                        
                                //         label: function(context) {
                                //             var label = context.dataset.label || '';
                                        
                                //             console.log("Callback do tooltip chamado:");

                                //             if (label) {
                                //                 label += ': ';
                                //             }
                                //             label += parseFloat(context.raw).toFixed(2); // Formata os valores no tooltip com 2 casas decimais
                                //             return label;
                                //         }
                                //     }
                                // }
                            },

                            
                        }
                    });

                    $('#divResult').html('');
                    $('input, select, textarea').removeClass('is-invalid');
                    $("#idSubmit").prop("disabled", false);
                    return false;
                }
            });
				

            /* Adicionei o mutation observer em função dos elementos que são adicionados após o carregamento do DOM */
            var obs = $.initialize("#table_tickets_mvp", function() {
                
                $(function() {
                    $('[data-toggle="popover"]').popover()
                });

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

                $('.ticket-number').css('cursor', 'pointer').on('click', function() {
                    var ticket = $(this).data('ticket');
                    openTicketInfo(ticket);
                });
                
                var criterios = $('#divCriterios').text();

                // var table = $('#table_tickets_mvp').DataTable({
                var table = $('.table').DataTable({
                    
                    dom: 'lfrtBip',
                    language: {
                        url: "../../includes/components/datatables/datatables.pt-br.json",
                    },
                    order: [0, 'asc'],
                    searching: true,
                    paging: true,
                    deferRender: true,
                    "pageLength": 50,
                
                
                    buttons: [
                        {
                            extend: 'print',
                            text: '<?= TRANS('SMART_BUTTON_PRINT', '', 1) ?>',
                            title: '<?= TRANS('REPORT_TICKETS_MVP', '', 1) ?>',
                            message: $('#print-info').html(),
                            autoPrint: true,
                            footer: 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'
                            },
                            footer: true,
                        },
                        {
                            extend: 'excel',
                            text: "Excel",
                            exportOptions: {
                                columns: ':visible'
                            },
                            filename: '<?= TRANS('REPORT_TICKETS_MVP', '', 1); ?>-<?= date('d-m-Y-H:i:s'); ?>',
                        },
                        {
                            extend: 'csvHtml5',
                            text: "CSV",
                            exportOptions: {
                                columns: ':visible'
                            },

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

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

                            customize: function(doc) {
                                var criterios = $('#table_caption').text()
                                var rdoc = doc;
                                
                                var rcout = doc.content[doc.content.length - 1].table.body.length - 1;
                                doc.content.splice(0, 1);
                                
                                // console.log(doc.content)
                                // var rcout = doc.content[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('REPORT_TICKETS_MVP', '', 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;
                                doc.content[1].layout = objLayout;
                            }
                        },
                    ]
                
                });

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

        });


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

        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;
        }

    </script>
</body>

</html>