<?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['s_nivel'] > 1) {
    $_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/components/dompdf/vendor/autoload.php";


use includes\classes\ConnectPDO;


$conn = ConnectPDO::getInstance();

$auth = new AuthNew($_SESSION['s_logado'], $_SESSION['s_nivel'], 1);
$exception = "";
$data = [];
$data['success'] = true;

$post = $_POST;

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

$data['invoice_id'] = (isset($post['cod']) && !empty($post['cod']) ? (int)$post['cod'] : "");


if (empty($data['invoice_id'])) {
    $data['success'] = false; 
    $data['field_id'] = 'invoice_id';
    $data['message'] = message('warning', 'Ooops!', TRANS('SOME_ERROR_DONT_PROCEED'),'');
    echo json_encode($data);
    return false;
}


$authorInfo = getUserInfo($conn, $_SESSION['s_uid']);
if (empty($authorInfo)) {
    $data['success'] = false; 
    $data['message'] = message('warning', 'Ooops!', TRANS('SOME_ERROR_DONT_PROCEED') . $exception,'');
    echo json_encode($data);
    return false;
}




/* Checar se o número da invoice existe */
$sql = "SELECT * FROM invoices WHERE id = '" . $data['invoice_id'] . "' ";
$res = $conn->query($sql);
if (!$res->rowCount()) {
    $data['success'] = false; 
    $data['field_id'] = 'invoice_id';
    $data['message'] = message('warning', '', TRANS('INVALID_INVOICE_CODE'), '');
    echo json_encode($data);
    return false;
}
$invoiceInfo = $res->fetch(PDO::FETCH_ASSOC);

$invoiceInfoJson = json_encode($invoiceInfo);
// $data['contractor'] = $res->fetch(PDO::FETCH_ASSOC)['contractor_id'];
$data['contractor'] = $invoiceInfo['contractor_id'];

// if (!csrf_verify($post, $data['csrf_session_key'])) {
//     $data['success'] = false; 
//     $data['message'] = message('warning', 'Ooops!', TRANS('FORM_ALREADY_SENT'),'');

//     echo json_encode($data);
//     return false;
// }



/* Guardar o log com a fatura excluida e o usuário responsável */
$author = $_SESSION['s_uid'];
$ipAddress = getClientIP();
$actionType = "DELETE_INVOICE";

$logged = recordUserLog($conn, $author, $actionType, $invoiceInfoJson, $ipAddress);
if (!$logged) {
    $exception .= "<hr>" . $conn->errorInfo()[2];
}







// Excluir a fatura
$sql = "DELETE FROM invoices WHERE id = :invoice_id ";
try {
    $res = $conn->prepare($sql);
    $res->bindParam(':invoice_id', $data['invoice_id']);
    $res->execute();
} catch (\PDOException $e) {
    $data['success'] = false; 
    $exception .= "<hr />" .$e->getMessage();
    $data['message'] = message('warning', 'Ooops!', TRANS('SOME_ERROR_DONT_PROCEED') . $exception,'');
    echo json_encode($data);
    return false;
}

// Remover invoice_items
$sql = "DELETE FROM invoice_items WHERE invoice_id = :invoice_id ";
try {
    $res = $conn->prepare($sql);
    $res->bindParam(':invoice_id', $data['invoice_id']);
    $res->execute();
} catch (\PDOException $e) {
    $data['success'] = false; 
    $exception .= "<hr />" .$e->getMessage();
    $data['message'] = message('warning', 'Ooops!', TRANS('SOME_ERROR_DONT_PROCEED') . $exception,'');
    echo json_encode($data);
    return false;
}

// Remover do invoice_files
$sql = "DELETE FROM invoice_files WHERE invoice_id = :invoice_id ";
try {
    $res = $conn->prepare($sql);
    $res->bindParam(':invoice_id', $data['invoice_id']);
    $res->execute();
} catch (\PDOException $e) {
    $data['success'] = false; 
    $exception .= "<hr />" .$e->getMessage();
    $data['message'] = message('warning', 'Ooops!', TRANS('SOME_ERROR_DONT_PROCEED') . $exception,'');
    echo json_encode($data);
    return false;
}


$data['success'] = true; 
$data['message'] = TRANS('MSG_SUCCESSFULLY_DELETED_INVOICE');
$_SESSION['flash'] = message('success', '', $data['message'] . $exception, '');

echo json_encode($data);
// dump($return);
return true;

