<?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'], 1, 1);


$post = (isset($_POST) && !empty($_POST) ? $_POST : '');

if (!isset($post['numero'])) {
    exit();
}

// var_dump($post); exit;

$config = getConfig($conn);
$exception = "";
$numero = (int) $post['numero'];
$user = (int) $_SESSION['s_uid'];
$now = date("Y-m-d H:i:s");
$entry = TRANS('TXTAREA_IN_ATTEND_BY') . ' ' . $_SESSION['s_usuario'];
$data['success'] = true;
$data['message'] = "";


$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['ticket_weight'] = (isset($post['ticket_weight']) && !empty($post['ticket_weight']) ? floatval($post['ticket_weight']) : null);


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


$row = getTicketData($conn, $numero);
if (!count($row)) {
    $data['success'] = false;
    $data['message'] = message('danger', '', TRANS('NO_RECORDS_FOUND'), '');
    echo json_encode($data);
    return false;
}






//Checa se já existe algum registro de log - caso não existir grava o estado atual
$firstLog = firstLog($conn, $numero, 'NULL', 1);



/* Para pegar o estado da ocorrência antes da atualização e permitir a gravação do log de modificações com recordLog() */
/* Array para a funcao recordLog */
$arrayBeforePost = [];
$arrayBeforePost['prob_cod'] = $row['problema'];



$sql = "UPDATE ocorrencias 
            SET 
                problema = :problema,
                complexity_factor = :complexity_factor,
                impact_factor = :impact_factor,
                deflator_factor = :deflator_factor
            WHERE numero = '{$numero}'";

try {

    $res = $conn->prepare($sql);
    $res->bindParam(':problema', $data['issue_type'], 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->execute();


} catch (Exception $e) {
    $exception .= '<hr>' .$e->getMessage();
    $data['success'] = false;
    $data['message'] = message('danger', '', TRANS('MSG_ERR_DATA_UPDATE') . $exception, '');
    echo json_encode($data);
    return false;
}

/* Array para a função recordLog */
$afterPost = [];
$afterPost['problema'] = $data['issue_type'];


/* Função que grava o registro de alterações do chamado */
$recordLog = recordLog($conn, $numero, $arrayBeforePost, $afterPost, 1);


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


