<?php
require '../../conexao/conexao.php';
require_once '../../conexao/logs.php';
session_start();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirectToUsuarios();
}

$id_pessoa = filter_input(INPUT_POST, 'id_pessoa', FILTER_VALIDATE_INT);
$id_usuario = filter_input(INPUT_POST, 'id_usuario', FILTER_VALIDATE_INT);

if (!$id_pessoa || !$id_usuario) {
    redirectToUsuarios();
}

$connectionmysql->begin_transaction();
try {
    $stmt_perfil = $connectionmysql->prepare('DELETE FROM perfil_usuario WHERE id_usuario = ?');
    $stmt_perfil->bind_param('i', $id_usuario);
    $stmt_perfil->execute();

    $stmt_usuario = $connectionmysql->prepare('DELETE FROM usuario WHERE id_usuario = ?');
    $stmt_usuario->bind_param('i', $id_usuario);
    $stmt_usuario->execute();

    $stmt_pessoa = $connectionmysql->prepare('DELETE FROM pessoa WHERE id_pessoa = ?');
    $stmt_pessoa->bind_param('i', $id_pessoa);
    $stmt_pessoa->execute();

    $connectionmysql->commit();
} catch (Throwable $exception) {
    $connectionmysql->rollback();
    error_log('Erro ao excluir usuário: ' . $exception->getMessage());
    redirectToUsuarios();
}

$_SESSION['log_acao'] = 'excluir';
redirectToUsuarios('usuarios.php?status=sucesso');

function redirectToUsuarios(string $base = 'usuarios.php')
{
    $filtros = isset($_SESSION['filtros']) ? http_build_query($_SESSION['filtros']) : '';
    $location = $base;
    if ($filtros !== '') {
        $location .= (strpos($location, '?') === false ? '?' : '&') . $filtros;
    }
    header("Location: $location");
    exit;
}
