up
This commit is contained in:
+99
-49
@@ -1,80 +1,130 @@
|
||||
<?php
|
||||
/**
|
||||
* API para eliminar un usuario
|
||||
* Versión: 1.0
|
||||
* Fecha: 12 de enero de 2026
|
||||
*/
|
||||
|
||||
header('Content-Type: application/json');
|
||||
header('Access-Control-Allow-Origin: *');
|
||||
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
|
||||
header('Access-Control-Allow-Headers: Content-Type, Authorization');
|
||||
require_once '../config/config.php';
|
||||
require_once '../classes/Database.php';
|
||||
|
||||
// Manejar preflight requests
|
||||
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
|
||||
exit(0);
|
||||
// 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 aceptar POST
|
||||
// Solo permitir POST
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
throw new Exception('Método no permitido. Use POST.');
|
||||
throw new Exception('Método no permitido');
|
||||
}
|
||||
|
||||
// Obtener datos del POST
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
$user_id = isset($input['user_id']) ? intval($input['user_id']) : 0;
|
||||
$debug = isset($_GET['debug']) && $_GET['debug'] === 'true';
|
||||
// Obtener datos del cuerpo de la petición
|
||||
$input = file_get_contents('php://input');
|
||||
$data = json_decode($input, true);
|
||||
|
||||
if ($debug) {
|
||||
error_log("=== DELETE USER DEBUG ===");
|
||||
error_log("User ID: " . $user_id);
|
||||
error_log("Input: " . json_encode($input));
|
||||
if (!$data) {
|
||||
throw new Exception('Datos inválidos');
|
||||
}
|
||||
|
||||
// Validar parámetros
|
||||
// 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');
|
||||
}
|
||||
|
||||
// Por ahora, simular eliminación exitosa
|
||||
// En el futuro, esto eliminaría el usuario de la base de datos
|
||||
if ($debug) {
|
||||
error_log("Simulando eliminación del usuario ID: " . $user_id);
|
||||
// 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');
|
||||
}
|
||||
|
||||
// Simular un pequeño delay para realismo
|
||||
usleep(500000); // 0.5 segundos
|
||||
// Iniciar transacción
|
||||
$conn = $db->getConnection();
|
||||
$conn->beginTransaction();
|
||||
|
||||
// Respuesta exitosa
|
||||
$response = [
|
||||
'success' => true,
|
||||
'message' => 'Usuario eliminado correctamente',
|
||||
'data' => [
|
||||
'deleted_user_id' => $user_id,
|
||||
'timestamp' => date('Y-m-d H:i:s')
|
||||
],
|
||||
'debug' => $debug ? [
|
||||
'timestamp' => date('Y-m-d H:i:s'),
|
||||
'simulated' => true,
|
||||
'user_id' => $user_id
|
||||
] : null
|
||||
];
|
||||
try {
|
||||
// Eliminar mensajes relacionados usando PDO
|
||||
$stmt = $conn->prepare("DELETE FROM messages WHERE user_id = ?");
|
||||
$stmt->bindValue(1, $user_id, PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
$deleted_messages = $stmt->rowCount();
|
||||
|
||||
echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
|
||||
// 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_messages_count' => $deleted_messages,
|
||||
'timestamp' => date('Y-m-d H:i:s')
|
||||
]
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
// Revertir transacción
|
||||
$conn->rollback();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
$error_response = [
|
||||
'success' => false,
|
||||
http_response_code(400);
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => $e->getMessage(),
|
||||
'debug' => $debug ? [
|
||||
'timestamp' => date('Y-m-d H:i:s'),
|
||||
'file' => __FILE__,
|
||||
'debug_info' => [
|
||||
'file' => basename(__FILE__),
|
||||
'line' => $e->getLine(),
|
||||
'trace' => $e->getTraceAsString()
|
||||
] : null
|
||||
];
|
||||
|
||||
]
|
||||
]);
|
||||
} catch (Error $e) {
|
||||
http_response_code(500);
|
||||
echo json_encode($error_response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => 'Error interno del servidor: ' . $e->getMessage(),
|
||||
'debug_info' => [
|
||||
'file' => basename(__FILE__),
|
||||
'line' => $e->getLine()
|
||||
]
|
||||
]);
|
||||
}
|
||||
?>
|
||||
Reference in New Issue
Block a user