<?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_basics_only.php";
require_once __DIR__ . "/" . "../../includes/classes/ConnectPDO.php";
require_once __DIR__ . "/" . "../../includes/classes/worktime/Worktime.php";
include_once __DIR__ . "/" . "../../includes/functions/getWorktimeProfile.php";

use includes\classes\ConnectPDO;

$conn = ConnectPDO::getInstance();
$exception = "";
$criteria = [];
$criteriaText = "";
$data = [];
$data['success'] = true;
$data['message'] = "";
$data['total'] = 0;
$uareas = explode(',', (string)$_SESSION['s_uareas']);
$terms = "";
$termsTotal = "";
$holidays = getHolidays($conn);

$isAdmin = $_SESSION['s_nivel'] == 1;
$mvpBaseDay = getConfigValue($conn, 'MVP_BASE_DAY') ?? 1;

$debugMode = false;
// $debugMode = ($_SESSION['s_usuario'] == 'flaviorib@gmail.com');


$labelsByStates = [
    1 => TRANS('STATE_OPEN_CLOSE_IN_SEARCH_RANGE'),
    2 => TRANS('STATE_OPEN_IN_SEARCH_RANGE'),
    3 => TRANS('STATE_OPEN_IN_SEARCH_RANGE_CLOSE_ANY_TIME'),
    4 => TRANS('STATE_OPEN_ANY_TIME_CLOSE_IN_SEARCH_RANGE'),
    5 => TRANS('STATE_JUST_OPEN_IN_SEARCH_RANGE')
];

/* Inicialização dos Critérios da consulta */
$criteria['client'] = TRANS('CLIENT') . ':&nbsp;' . TRANS('ALL');
$criteria['treater'] = TRANS('WORKER') . ':&nbsp;' . TRANS('ALL');
$criteria['area'] = TRANS('AREA') . ':&nbsp;' . TRANS('ALL');
$criteria['state'] = TRANS('CONTEXT') . ':&nbsp;' . TRANS('STATE_OPEN_CLOSE_IN_SEARCH_RANGE');

$post = $_POST;

$hora_inicio = ' 00:00:00';
$hora_fim = ' 23:59:59';

$data['client'] = (isset($post['client']) ? (int)$post['client'] : "");
$data['area'] = (isset($post['area']) ? (int)$post['area'] : "");

$data['treater'] = (isset($post['treater']) ? (int)$post['treater'] : "");

if (!$isAdmin) {
    $data['treater'] = $_SESSION['s_uid'];
}

$data['d_ini'] = (isset($post['d_ini']) && isValidDate($post['d_ini']) ? dateDB($post['d_ini'] . $hora_inicio) : '');
$data['d_fim'] = (isset($post['d_fim']) && isValidDate($post['d_fim']) ? dateDB($post['d_fim'] . $hora_fim) : '');


if (isset($post['current_period']) && $post['current_period'] == 1) {
    $data['treater'] = $_SESSION['s_uid'];
    $currentPeriod = getPreviousMonthsDates(1, true, $mvpBaseDay)[0];
    $data['d_ini'] = $currentPeriod['start'] . $hora_inicio;
    $data['d_fim'] = $currentPeriod['end'] . $hora_fim;

    $post['d_ini'] = dateScreen($currentPeriod['start'], 1);
    $post['d_fim'] = dateScreen($currentPeriod['end'], 1);

    /* Limpa a seção do percentual */
    $_SESSION['s_my_mvp_percentual_done'] = 0;
}


$data['state'] = (isset($post['state']) && !empty($post['state']) ? (int)$post['state'] : 1);

$data['generate_chart'] = 0;



if (empty($data['d_ini']) || empty($data['d_fim']) || ($data['d_ini'] > $data['d_fim'])) {
    $data['success'] = false;
    $data['field_id'] = "d_ini";
    $data['message'] = TRANS('MSG_CHECK_PERIOD');
    $data['message'] = message('warning', 'Ooops!', $data['message'], '', '');
    echo json_encode($data);
    return false;
}



if (!empty($data['client'])) {
    $terms .= " AND o.client = {$data['client']} ";
    $termsTotal .= $terms;
    $criteria['client'] = TRANS('CLIENT') . ':&nbsp;<b>' . getClients($conn, $data['client'])['nickname'] . '</b>';
}





$limited_areas = false;
$string_area_names = "";
if (empty($data['area']) && isAreasIsolated($conn) && $_SESSION['s_nivel'] != 1) {
    /* Visibilidade isolada entre áreas para usuários não admin */
    $limited_areas = true;
    $u_areas = $_SESSION['s_uareas'];

    $terms .= " AND o.sistema IN ({$u_areas}) ";
    $termsTotal .= $terms;

    $array_areas_names = getUserAreasNames($conn, $u_areas);
    $string_area_names = implode(", ", array_filter($array_areas_names));
} elseif (!empty($data['area'])) {

    $string_area_names = getAreaInfo($conn, $data['area'])['area_name'];

    $terms .= " AND o.sistema = {$data['area']} ";
    $termsTotal .= $terms;
    $criteria['area'] = TRANS('AREA') . ':&nbsp;<b>' . $string_area_names . '</b>';
}




if (!empty($data['treater'])) {
    $terms .= " AND u.user_id = {$data['treater']} ";
    $termsTotal .= $terms;
    $criteria['treater'] = TRANS('WORKER') . ':&nbsp;<b>' . getUserInfo($conn, $data['treater'])['nome'] . '</b>';
}








$client_filter = [];


// $termsTotal = "";
$chart_title_sufix = '_chart_title';
$chart_1_prefix = 'chart_01';
$chart_2_prefix = 'chart_02';
$chart_3_prefix = 'chart_03';
$chart_4_prefix = 'chart_04';
$chart_5_prefix = 'chart_05';



/* Período */
$criteria['range'] = TRANS('RANGE_FROM_TO') . ':&nbsp;<b>' . $post['d_ini'] . ' - ' . $post['d_fim'] . '</b>';

/* Contexto */
$criteria['state'] = TRANS('CONTEXT') . ':&nbsp;<b>' . $labelsByStates[$data['state']] . '</b>';



$_SESSION['s_rep_filters']['client'] = $data['client'];
$_SESSION['s_rep_filters']['area'] = $data['area'];
$_SESSION['s_rep_filters']['state'] = $data['state'];
$_SESSION['s_rep_filters']['d_ini'] = $post['d_ini'];
$_SESSION['s_rep_filters']['d_fim'] = $post['d_fim'];



/* Montagem do texto dos critérios */
$criteriaText = implode(' | ', $criteria);
if ($limited_areas) {
    $criteriaText .= " <br />(". TRANS('RESULT_LIMITED_BY_PERMISSIONS').")";
}
$data['criteria'] = $criteriaText;
/* Final da montagem dos critérios */


$clausulesByStates = [
    1 => " AND o.data_abertura >= '{$data['d_ini']}' AND o.data_abertura <= '{$data['d_fim']}' AND 
    o.data_fechamento IS NOT NULL AND o.data_fechamento >= '{$data['d_ini']}' AND o.data_fechamento <= '{$data['d_fim']}' ",
    2 => " AND o.data_abertura >= '{$data['d_ini']}' AND o.data_abertura <= '{$data['d_fim']}' AND 
    (o.data_fechamento >= '{$data['d_fim']}' OR o.data_fechamento IS NULL) ",
    3 => " AND o.data_abertura >= '{$data['d_ini']}' AND o.data_abertura <= '{$data['d_fim']}' AND 
    o.data_fechamento IS NOT NULL ",
    4 => " AND o.data_fechamento >= '{$data['d_ini']}' AND o.data_fechamento <= '{$data['d_fim']}' ",
    5 => " AND o.data_abertura >= '{$data['d_ini']}' AND o.data_abertura <= '{$data['d_fim']}' "
];


$data['table_1'] = [];

$data['table_2'] = [];
$data['operators'] = [];

$data['tickets'] = [];
$data['chart_1'] = [];


$sql = "SELECT 
            o.numero,
            o.data_abertura,
            o.data_atendimento,
            o.data_fechamento,
            o.operador,
            u.nome,
            COALESCE (u.mvp_target, 0) AS mvp_target,
            p.problema,
            COALESCE (p.weight, '-') AS weight,
            COALESCE (tl.name, '-') AS level_name,
            COALESCE(tp.unit_price * p.weight, 0) AS ticket_price,
            COALESCE(tp.unit_price, 0) AS unit_price
        FROM
            ocorrencias o
            LEFT JOIN
                problemas p ON o.problema = p.prob_id
            LEFT JOIN
                tech_levels tl ON tl.id = p.tech_level
            LEFT JOIN
                tech_prices tp ON tp.id = (
                SELECT 
                    COALESCE(
                        (
                            SELECT MAX(id) 
                            FROM tech_prices 
                            WHERE tech_level_id = p.tech_level AND
                                vigence_since <= o.data_abertura
                        ),
                        (
                            SELECT MIN(id) 
                            FROM tech_prices 
                            WHERE tech_level_id = p.tech_level
                        )
                    )
            ),
            usuarios u
        WHERE
            o.operador = u.user_id
            {$terms}
            {$clausulesByStates[$data['state']]}
        ";

    try {
        $res = $conn->prepare($sql);
        $res->execute();
        if ($res->rowCount()) {
            $data['table_1'] = $res->fetchAll();
        }
    } catch (PDOException $e) {
        $data['success'] = false;
        $data['message'] = message('warning', 'Ooops!', $e->getMessage(),'');
        echo json_encode($data);
        return false;
    }


    if (count($data['table_1']) == 0) {
        $data['success'] = false;
        $data['message'] = message('warning', 'Ooops!', TRANS('NO_RECORDS_FOUND') . $exception,'');
        echo json_encode($data);
        return false;
    }


    foreach ($data['table_1'] as $row) {
        if (is_array($row) && array_key_exists('numero', $row)) {
            /* Utilizar a chave 'numero' como chave */
            $data['tickets'][$row['numero']] = $row;
            $data['tickets'][$row['numero']]['data_abertura_br'] = dateScreen($row['data_abertura']);
            $data['tickets'][$row['numero']]['data_atendimento_br'] = dateScreen($row['data_atendimento']);
            $data['tickets'][$row['numero']]['data_fechamento_br'] = dateScreen($row['data_fechamento']);
            $data['tickets'][$row['numero']]['ticket_price_brl_old'] = priceScreen($row['ticket_price']);
            
            $ticketWeight = getTicketWeight($conn, $row['numero']) ?? 1;
            $row['ticket_price'] = $ticketWeight * $row['unit_price'];
            
            $data['tickets'][$row['numero']]['weight'] = $ticketWeight;
            $data['tickets'][$row['numero']]['ticket_price'] = $ticketWeight * $row['unit_price'];
            $data['tickets'][$row['numero']]['ticket_price_brl'] = priceScreen($ticketWeight * $row['unit_price']);


            if (array_key_exists($row['operador'], $data['operators'])) {
                /* Atualiza o operador */
                $data['operators'][$row['operador']]['ust'] += $row['ticket_price'];
                $data['operators'][$row['operador']]['ust_brl'] = priceScreen($data['operators'][$row['operador']]['ust']);

            } else {
                /* Inicializa o operador */
                $data['operators'][$row['operador']] = [
                        'ust' => $row['ticket_price'],
                        'ust_brl' => priceScreen($row['ticket_price']),
                        'name' => $row['nome'],
                        'area' => getMainAreaNameFromUserId($conn, $row['operador']),
                        'mvp_target' => $row['mvp_target']
                ];
            }
        }
    }

    /* Calcular o percentual de atingido */
    foreach ($data['operators'] as &$item) {
        // Certifique-se de que 'ust' e 'mvp_target' sejam números
        $ust = (float)$item['ust'];
        $mvp_target = (float)$item['mvp_target'];
    
        // Evitar divisão por zero
        if ($mvp_target == 0) {
            $item['percentual_done'] = 0;
        } else {
            // ($ust / $mvp_target) * 100
            $item['percentual_done'] = number_format(($ust / $mvp_target) * 100, 2, ',', '.') . '%';
        }
    }
    unset($item); 

    if (isset($post['current_period']) && $post['current_period'] == 1) {
        $_SESSION['s_my_mvp_percentual_done'] = $data['operators'][$_SESSION['s_uid']]['percentual_done'];
    }


    // Arrays para os dados do gráfico
    $labels = [];
    $ustData = [];
    $mvpTargetData = [];

    foreach ($data['operators'] as $item) {
        $data['chart_1']['labels'][] = $item['name'];
        /* LImitar o ust a duas casas decimais */
        $data['chart_1']['usts_brl'][] = 'R$' . number_format($item['ust'], 2, ',', '.');
        // $data['chart_1']['usts'][] = $item['ust'];
        $data['chart_1']['usts'][] = number_format($item['ust'], 2);

        $data['chart_1']['mvp_targets'][] = $item['mvp_target'];
    }


    $data['tickets']['title'] = TRANS('REPORT_TICKETS_MVP');
    $data['tickets']['operators_title'] = TRANS('SUM_BY_WORKER');
    $data['tickets']['totalPrice'] = priceScreen(array_sum(array_column($data['tickets'], 'ticket_price')));
    $data['tickets']['totalWeight'] = array_sum(array_column($data['tickets'], 'weight'));


    if ($debugMode) {
        var_dump($data['table_1']);
        var_dump($data['tickets']);
        var_dump($data['operators']);
        var_dump($data['chart_1']);
        exit;
    }


echo json_encode($data);

return true;
