130 lines
3.6 KiB
PHP
130 lines
3.6 KiB
PHP
<?php
|
|
/**
|
|
* API para eliminar un usuario
|
|
* Fecha: 12 de enero de 2026
|
|
*/
|
|
|
|
require_once '../config/config.php';
|
|
require_once '../classes/Database.php';
|
|
|
|
// Suprimir errores para obtener JSON limpio
|
|
error_reporting(E_ERROR | E_PARSE);
|
|
|
|
// Modo debug: desactivar autenticación si existe el parámetro debug
|
|
$debugMode = isset($_GET['debug']) && $_GET['debug'] === 'true';
|
|
|
|
if (!$debugMode) {
|
|
requireAuthentication();
|
|
}
|
|
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
header('Access-Control-Allow-Origin: *');
|
|
header('Access-Control-Allow-Methods: POST, OPTIONS');
|
|
header('Access-Control-Allow-Headers: Content-Type');
|
|
|
|
// Manejar OPTIONS request
|
|
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
|
|
http_response_code(200);
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
// Solo permitir POST
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
throw new Exception('Método no permitido');
|
|
}
|
|
|
|
// Obtener datos del cuerpo de la petición
|
|
$input = file_get_contents('php://input');
|
|
$data = json_decode($input, true);
|
|
|
|
if (!$data) {
|
|
throw new Exception('Datos inválidos');
|
|
}
|
|
|
|
// Validar datos requeridos
|
|
if (!isset($data['user_id']) || empty($data['user_id'])) {
|
|
throw new Exception('ID de usuario requerido');
|
|
}
|
|
|
|
$user_id = intval($data['user_id']);
|
|
|
|
if ($user_id <= 0) {
|
|
throw new Exception('ID de usuario inválido');
|
|
}
|
|
|
|
// Crear conexión a la base de datos usando el patrón Singleton
|
|
$db = Database::getInstance();
|
|
|
|
// Verificar si el usuario existe y obtener sus datos
|
|
$user_data = $db->fetch("SELECT id, name, phone_number FROM users WHERE id = :user_id", ['user_id' => $user_id]);
|
|
|
|
if (!$user_data) {
|
|
throw new Exception('Usuario no encontrado');
|
|
}
|
|
|
|
// Iniciar transacción
|
|
$conn = $db->getConnection();
|
|
$conn->beginTransaction();
|
|
|
|
try {
|
|
// Eliminar mensajes relacionados usando PDO
|
|
$stmt = $conn->prepare("DELETE FROM conversations WHERE user_id = ?");
|
|
$stmt->bindValue(1, $user_id, PDO::PARAM_INT);
|
|
$stmt->execute();
|
|
$deleted_conversations = $stmt->rowCount();
|
|
|
|
// Eliminar el usuario
|
|
$stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
|
|
$stmt->bindValue(1, $user_id, PDO::PARAM_INT);
|
|
$stmt->execute();
|
|
|
|
if ($stmt->rowCount() === 0) {
|
|
throw new Exception('No se pudo eliminar el usuario');
|
|
}
|
|
|
|
// Confirmar transacción
|
|
$conn->commit();
|
|
|
|
// Respuesta exitosa
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Usuario eliminado correctamente',
|
|
'data' => [
|
|
'deleted_user_id' => $user_id,
|
|
'deleted_user_name' => $user_data['name'],
|
|
'deleted_user_phone' => $user_data['phone_number'],
|
|
'deleted_conversations_count' => $deleted_conversations,
|
|
'timestamp' => date('Y-m-d H:i:s')
|
|
]
|
|
]);
|
|
|
|
} catch (Exception $e) {
|
|
// Revertir transacción
|
|
$conn->rollback();
|
|
throw $e;
|
|
}
|
|
|
|
} catch (Exception $e) {
|
|
http_response_code(400);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'error' => $e->getMessage(),
|
|
'debug_info' => [
|
|
'file' => basename(__FILE__),
|
|
'line' => $e->getLine(),
|
|
'trace' => $e->getTraceAsString()
|
|
]
|
|
]);
|
|
} catch (Error $e) {
|
|
http_response_code(500);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'error' => 'Error interno del servidor: ' . $e->getMessage(),
|
|
'debug_info' => [
|
|
'file' => basename(__FILE__),
|
|
'line' => $e->getLine()
|
|
]
|
|
]);
|
|
}
|
|
?>
|