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

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

use includes\classes\ConnectPDO;

$conn = ConnectPDO::getInstance();
$auth = new AuthNew($_SESSION['s_logado'], $_SESSION['s_nivel'], 2, 1);
$now = date("Y-m-d H:i:s");
$data = [];
$data['success'] = true;
$data['message'] = "";
$data['author'] = $_SESSION['s_uid'];

$exception = "";

$post = (isset($_POST) && !empty($_POST) ? $_POST : '');
if (!isset($post['ticket'])) {
    exit();
}

$data['ticket'] = (int)$post['ticket'];
$data['operator'] = (isset($post['operator']) && !empty($post['operator']) ? (int)$post['operator'] : null);
$data['issue_type'] = (isset($post['issue_type']) && !empty($post['issue_type']) ? (int)$post['issue_type'] : null);
$data['complexity_factor'] = (isset($post['complexity_factor']) && !empty($post['complexity_factor']) ? (int)$post['complexity_factor'] : null);
$data['impact_factor'] = (isset($post['impact_factor']) && !empty($post['impact_factor']) ? (int)$post['impact_factor'] : null);
$data['deflator_factor'] = (isset($post['deflator_factor']) && !empty($post['deflator_factor']) ? (int)$post['deflator_factor'] : null);

$data['entry'] = TRANS('UPDATE_THROUGH_SUB_TICKET_LIST');
$data['entry_privated'] = 0;

if (empty($data['operator'])) {
    $data['success'] = false;
    $data['message'] = message('warning', '', TRANS('MSG_EMPTY_DATA'), '');
    $data['field_id'] = "current_sub_operator_" . $data['ticket'];
    echo json_encode($data);
    return false;
}

if (empty($data['issue_type'])) {
    $data['success'] = false;
    $data['message'] = message('warning', '', TRANS('MSG_EMPTY_DATA'), '');
    $data['field_id'] = "current_sub_issue_type_" . $data['ticket'];
    echo json_encode($data);
    return false;
}

if (empty($data['complexity_factor'])) {
    $data['success'] = false;
    $data['message'] = message('warning', '', TRANS('MSG_EMPTY_DATA'), '');
    $data['field_id'] = "current_sub_complexity_factor_" . $data['ticket'];
    echo json_encode($data);
    return false;
}

if (empty($data['impact_factor'])) {
    $data['success'] = false;
    $data['message'] = message('warning', '', TRANS('MSG_EMPTY_DATA'), '');
    $data['field_id'] = "current_sub_impact_factor_" . $data['ticket'];
    echo json_encode($data);
    return false;
}

if (empty($data['deflator_factor'])) {
    $data['success'] = false;
    $data['message'] = message('warning', '', TRANS('MSG_EMPTY_DATA'), '');
    $data['field_id'] = "current_sub_deflator_factor_" . $data['ticket'];
    echo json_encode($data);
    return false;
}

/* Insere o primeiro registro de log caso não exista - chamados anteriores a versao 3.0 */
$firstLog = firstLog($conn, $data['ticket']);

/* Para pegar o estado da ocorrência antes da atualização e permitir a gravação do log de modificações */
$arrayBeforePost = [];
if (!empty($data['ticket'])) {
    $qryfull = $QRY["ocorrencias_full_ini"]." WHERE o.numero = {$data['ticket']} ";
    $execfull = $conn->query($qryfull);
    $arrayBeforePost = $execfull->fetch();
}

/* A área de atendimento do sub-chamado dependerá do tipo de solicitação selecionado */
$areaToOpen = [];
$arrayAreaDynamic = getAreaInDynamicMode($conn, $data['issue_type'], $_SESSION['s_area'], $_SESSION['s_uareas']);
$areaToOpen = $arrayAreaDynamic['area_receiver'];
$data['area_to_open'] = $areaToOpen[0];


$sql = "UPDATE ocorrencias SET 
            `operador` = :operator,
            `problema` = :issue_type,
            `instituicao` = :area_to_open,
            `complexity_factor` = :complexity_factor,
            `impact_factor` = :impact_factor,
            `deflator_factor` = :deflator_factor
        WHERE 
            numero = :ticket
        ";
try {
    $res = $conn->prepare($sql);
    $res->bindParam(':operator', $data['operator'], PDO::PARAM_INT);
    $res->bindParam(':issue_type', $data['issue_type'], PDO::PARAM_INT);
    $res->bindParam(':area_to_open', $data['area_to_open'], PDO::PARAM_INT);
    $res->bindParam(':complexity_factor', $data['complexity_factor'], PDO::PARAM_INT);
    $res->bindParam(':impact_factor', $data['impact_factor'], PDO::PARAM_INT);
    $res->bindParam(':deflator_factor', $data['deflator_factor'], PDO::PARAM_INT);
    $res->bindParam(':ticket', $data['ticket'], PDO::PARAM_INT);
    $res->execute();

    $rowCount = $res->rowCount();
    
    if ($rowCount == 0) {
        $data['success'] = true;
        $data['message'] = message('info', '', TRANS('NO_INFORMATION_MODIFIED') . $exception, '');
        echo json_encode($data);
        return true;
    }


    /* Array para a função recordLog */
    $afterPost = [];
    // $afterPost['area'] = $data['sistema'];
    $afterPost['problema'] = $data['issue_type'];
    $afterPost['area'] = $data['area_to_open'];
    $afterPost['operador'] = $data['operator'];
    
    $operationType = 1;

    /* Função que grava o registro de alterações do chamado */
    $recordLog = recordLog($conn, $data['ticket'], $arrayBeforePost, $afterPost, $operationType);


    
    $sqlEntry = "INSERT INTO assentamentos 
        (
            ocorrencia, assentamento, created_at, responsavel, asset_privated, tipo_assentamento
        )
        VALUES 
        (
            :numero,
            :entry,
            :created_at,
            :logged,
            :privated,
            1
        )";

        try {
            $res = $conn->prepare($sqlEntry);
            $res->bindParam(':numero', $data['ticket'], PDO::PARAM_INT);
            $res->bindParam(':entry', $data['entry'], PDO::PARAM_STR);
            $res->bindParam(':created_at', $now, PDO::PARAM_STR);
            $res->bindParam(':logged', $data['author'], PDO::PARAM_INT);
            $res->bindParam(':privated', $data['entry_privated'], PDO::PARAM_INT);
            $res->execute();

            $notice_id = $conn->lastInsertId();
            if (!$data['entry_privated'] && $_SESSION['s_uid'] != $arrayBeforePost['aberto_por_cod']) {
                setUserTicketNotice($conn, 'assentamentos', $notice_id);
            }

        } catch (Exception $e) {
            $exception .= "<hr>" . $e->getMessage();
        }

}
catch (Exception $e) {
    $data['success'] = false;
    $data['message'] = message('warning', '', $e->getMessage(), '');
    echo json_encode($data);
    return false;
}



$data['success'] = true;
$data['message'] = message('success', '', TRANS('MSG_SUCCESS_EDIT') . $exception, '');
echo json_encode($data);
return true;
