up
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
/**
|
||||
* API para eliminar opción de menú
|
||||
* Fecha: 13 de enero de 2026
|
||||
*/
|
||||
|
||||
require_once '../config/config.php';
|
||||
require_once '../classes/Database.php';
|
||||
|
||||
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');
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
|
||||
http_response_code(200);
|
||||
exit;
|
||||
}
|
||||
|
||||
try {
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
throw new Exception('Método no permitido');
|
||||
}
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
|
||||
if (!$input) {
|
||||
throw new Exception('Datos inválidos');
|
||||
}
|
||||
|
||||
// Validar datos requeridos
|
||||
if (!isset($input['option_id'])) {
|
||||
throw new Exception('ID de opción requerido');
|
||||
}
|
||||
|
||||
$optionId = (int)$input['option_id'];
|
||||
$menuId = isset($input['menu_id']) ? (int)$input['menu_id'] : null;
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
// Verificar que la opción existe
|
||||
$option = $db->fetch("SELECT * FROM menu_options WHERE id = :id", ['id' => $optionId]);
|
||||
|
||||
if (!$option) {
|
||||
throw new Exception('Opción no encontrada');
|
||||
}
|
||||
|
||||
// Si se proporcionó menu_id, verificar que coincida
|
||||
if ($menuId !== null && $option['menu_id'] != $menuId) {
|
||||
throw new Exception('La opción no pertenece al menú especificado');
|
||||
}
|
||||
|
||||
// Eliminar la opción
|
||||
$result = $db->execute("DELETE FROM menu_options WHERE id = :id", ['id' => $optionId]);
|
||||
|
||||
if ($result > 0) {
|
||||
// Registrar en log
|
||||
error_log("Opción de menú eliminada: ID={$optionId}, Menú={$option['menu_id']}");
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => 'Opción eliminada correctamente',
|
||||
'option_id' => $optionId,
|
||||
'menu_id' => $option['menu_id']
|
||||
]);
|
||||
} else {
|
||||
throw new Exception('No se pudo eliminar la opción');
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("Error in delete_menu_option.php: " . $e->getMessage());
|
||||
http_response_code(400);
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
}
|
||||
?>
|
||||
+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()
|
||||
]
|
||||
]);
|
||||
}
|
||||
?>
|
||||
+41
-16
@@ -35,7 +35,19 @@ try {
|
||||
$db->beginTransaction();
|
||||
|
||||
try {
|
||||
// Verificar estructura de tabla antes de insertar
|
||||
// Verificar si es actualización o creación
|
||||
$isUpdate = isset($input['id']) && !empty($input['id']);
|
||||
$menuId = $isUpdate ? intval($input['id']) : null;
|
||||
|
||||
if ($isUpdate) {
|
||||
// Verificar que el menú existe
|
||||
$existingMenu = $db->fetch("SELECT id FROM menus WHERE id = ?", [$menuId]);
|
||||
if (!$existingMenu) {
|
||||
throw new Exception('Menú no encontrado para actualizar');
|
||||
}
|
||||
}
|
||||
|
||||
// Verificar estructura de tabla antes de insertar/actualizar
|
||||
$tableStructure = $db->fetchAll("DESCRIBE menus");
|
||||
$availableColumns = array_column($tableStructure, 'Field');
|
||||
|
||||
@@ -44,13 +56,14 @@ try {
|
||||
// Adaptar datos a la estructura real de la tabla
|
||||
$menuData = [];
|
||||
|
||||
// Campos básicos que deberían existir
|
||||
// La tabla usa 'name' para la clave del menú
|
||||
if (in_array('name', $availableColumns)) {
|
||||
$menuData['name'] = $input['menu_key'] ?? $input['name']; // Usar menu_key como name
|
||||
$menuData['name'] = $input['menu_key'] ?? $input['name'] ?? 'menu_' . time();
|
||||
}
|
||||
|
||||
// La tabla usa 'title' para el nombre visible del menú
|
||||
if (in_array('title', $availableColumns)) {
|
||||
$menuData['title'] = $input['name'] ?? 'Nuevo Menú'; // Usar name como title
|
||||
$menuData['title'] = $input['name'] ?? $input['title'] ?? 'Nuevo Menú';
|
||||
}
|
||||
|
||||
if (in_array('description', $availableColumns)) {
|
||||
@@ -66,28 +79,37 @@ try {
|
||||
}
|
||||
|
||||
if (in_array('is_active', $availableColumns)) {
|
||||
$menuData['is_active'] = ($input['status'] === 'active') ? 1 : 0;
|
||||
// Mapear status a is_active: 'active' -> 1, cualquier otra cosa -> 0
|
||||
$menuData['is_active'] = (($input['status'] ?? 'active') === 'active') ? 1 : 0;
|
||||
}
|
||||
|
||||
if (in_array('order_position', $availableColumns)) {
|
||||
// Obtener próxima posición
|
||||
if (in_array('order_position', $availableColumns) && !$isUpdate) {
|
||||
// Solo establecer order_position para menús nuevos
|
||||
$maxOrder = $db->fetch("SELECT COALESCE(MAX(order_position), 0) as max_order FROM menus");
|
||||
$menuData['order_position'] = ($maxOrder['max_order'] ?? 0) + 1;
|
||||
}
|
||||
|
||||
if (in_array('created_at', $availableColumns)) {
|
||||
if (in_array('created_at', $availableColumns) && !$isUpdate) {
|
||||
$menuData['created_at'] = date('Y-m-d H:i:s');
|
||||
}
|
||||
|
||||
if (in_array('updated_at', $availableColumns)) {
|
||||
$menuData['updated_at'] = date('Y-m-d H:i:s');
|
||||
}
|
||||
|
||||
|
||||
// Crear o actualizar menú
|
||||
if ($isUpdate) {
|
||||
$result = $db->update('menus', $menuData, 'id = :menu_id', ['menu_id' => $menuId]);
|
||||
if (!$result || $result->rowCount() === 0) {
|
||||
throw new Exception('No se pudo actualizar el menú');
|
||||
}
|
||||
} else {
|
||||
$menuId = $db->insert('menus', $menuData);
|
||||
|
||||
if (!$menuId) {
|
||||
throw new Exception('Error insertando menú');
|
||||
}
|
||||
}
|
||||
|
||||
// Procesar opciones si las hay
|
||||
$optionsCount = 0;
|
||||
@@ -113,19 +135,22 @@ try {
|
||||
}
|
||||
}
|
||||
|
||||
// Actualizar contador de opciones
|
||||
$db->execute("UPDATE menus SET options_count = :count WHERE id = :id", [
|
||||
'count' => $optionsCount,
|
||||
'id' => $menuId
|
||||
]);
|
||||
// Actualizar contador de opciones solo si la columna existe
|
||||
if (in_array('options_count', $availableColumns)) {
|
||||
$db->execute("UPDATE menus SET options_count = :count WHERE id = :id", [
|
||||
'count' => $optionsCount,
|
||||
'id' => $menuId
|
||||
]);
|
||||
}
|
||||
|
||||
$db->commit();
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => 'Menú guardado correctamente',
|
||||
'message' => $isUpdate ? 'Menú actualizado correctamente' : 'Menú guardado correctamente',
|
||||
'menu_id' => $menuId,
|
||||
'options_created' => $optionsCount
|
||||
'options_created' => $optionsCount,
|
||||
'action' => $isUpdate ? 'updated' : 'created'
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
/**
|
||||
* API para guardar/actualizar opción de menú
|
||||
* Fecha: 12 de enero de 2026
|
||||
*/
|
||||
|
||||
require_once '../config/config.php';
|
||||
require_once '../classes/Database.php';
|
||||
|
||||
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');
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
|
||||
http_response_code(200);
|
||||
exit;
|
||||
}
|
||||
|
||||
try {
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
throw new Exception('Método no permitido');
|
||||
}
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
|
||||
if (!$input) {
|
||||
throw new Exception('Datos inválidos');
|
||||
}
|
||||
|
||||
// Validar datos requeridos
|
||||
if (!isset($input['menu_id']) || !isset($input['option_key']) || !isset($input['option_text'])) {
|
||||
throw new Exception('Datos incompletos: se requiere menu_id, option_key y option_text');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
// Verificar que el menú existe
|
||||
$menu = $db->fetch("SELECT id FROM menus WHERE id = :id", ['id' => $input['menu_id']]);
|
||||
if (!$menu) {
|
||||
throw new Exception('Menú no encontrado');
|
||||
}
|
||||
|
||||
// Verificar estructura de tabla menu_options
|
||||
$tableStructure = $db->fetchAll("DESCRIBE menu_options");
|
||||
$availableColumns = array_column($tableStructure, 'Field');
|
||||
|
||||
// Preparar datos según estructura de tabla
|
||||
$optionData = [];
|
||||
|
||||
if (in_array('menu_id', $availableColumns)) {
|
||||
$optionData['menu_id'] = (int)$input['menu_id'];
|
||||
}
|
||||
|
||||
if (in_array('option_number', $availableColumns)) {
|
||||
$optionData['option_number'] = (int)$input['option_key'];
|
||||
}
|
||||
|
||||
if (in_array('option_key', $availableColumns)) {
|
||||
$optionData['option_key'] = $input['option_key'];
|
||||
}
|
||||
|
||||
if (in_array('text', $availableColumns)) {
|
||||
$optionData['text'] = $input['option_text'];
|
||||
}
|
||||
|
||||
if (in_array('option_text', $availableColumns)) {
|
||||
$optionData['option_text'] = $input['option_text'];
|
||||
}
|
||||
|
||||
if (in_array('action_type', $availableColumns)) {
|
||||
$optionData['action_type'] = $input['option_action'] ?? 'message';
|
||||
}
|
||||
|
||||
if (in_array('option_action', $availableColumns)) {
|
||||
$optionData['option_action'] = $input['option_action'] ?? 'message';
|
||||
}
|
||||
|
||||
if (in_array('action_value', $availableColumns)) {
|
||||
$optionData['action_value'] = $input['option_value'] ?? '';
|
||||
}
|
||||
|
||||
if (in_array('option_value', $availableColumns)) {
|
||||
$optionData['option_value'] = $input['option_value'] ?? '';
|
||||
}
|
||||
|
||||
if (in_array('is_active', $availableColumns)) {
|
||||
$optionData['is_active'] = ($input['is_active'] ?? true) ? 1 : 0;
|
||||
}
|
||||
|
||||
if (in_array('order_index', $availableColumns)) {
|
||||
// Obtener el siguiente índice de orden
|
||||
$maxOrder = $db->fetch(
|
||||
"SELECT COALESCE(MAX(order_index), 0) as max_order FROM menu_options WHERE menu_id = :menu_id",
|
||||
['menu_id' => $input['menu_id']]
|
||||
);
|
||||
$optionData['order_index'] = ($maxOrder['max_order'] ?? 0) + 1;
|
||||
}
|
||||
|
||||
if (in_array('created_at', $availableColumns)) {
|
||||
$optionData['created_at'] = date('Y-m-d H:i:s');
|
||||
}
|
||||
|
||||
// Insertar la opción
|
||||
$optionId = $db->insert('menu_options', $optionData);
|
||||
|
||||
if (!$optionId) {
|
||||
throw new Exception('Error insertando opción de menú');
|
||||
}
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => 'Opción de menú guardada correctamente',
|
||||
'option_id' => $optionId,
|
||||
'menu_id' => $input['menu_id']
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("Error in save_menu_option.php: " . $e->getMessage());
|
||||
http_response_code(400);
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
/**
|
||||
* API para actualizar opción de menú
|
||||
* Fecha: 13 de enero de 2026
|
||||
*/
|
||||
|
||||
require_once '../config/config.php';
|
||||
require_once '../classes/Database.php';
|
||||
|
||||
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');
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
|
||||
http_response_code(200);
|
||||
exit;
|
||||
}
|
||||
|
||||
try {
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
throw new Exception('Método no permitido');
|
||||
}
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
|
||||
if (!$input) {
|
||||
throw new Exception('Datos inválidos');
|
||||
}
|
||||
|
||||
// Validar datos requeridos
|
||||
if (!isset($input['option_id']) || !isset($input['option_key']) || !isset($input['option_text'])) {
|
||||
throw new Exception('Datos incompletos: se requiere option_id, option_key y option_text');
|
||||
}
|
||||
|
||||
$optionId = (int)$input['option_id'];
|
||||
$menuId = isset($input['menu_id']) ? (int)$input['menu_id'] : null;
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
// Verificar que la opción existe
|
||||
$option = $db->fetch("SELECT * FROM menu_options WHERE id = :id", ['id' => $optionId]);
|
||||
|
||||
if (!$option) {
|
||||
throw new Exception('Opción no encontrada');
|
||||
}
|
||||
|
||||
// Si se proporcionó menu_id, verificar que coincida
|
||||
if ($menuId !== null && $option['menu_id'] != $menuId) {
|
||||
throw new Exception('La opción no pertenece al menú especificado');
|
||||
}
|
||||
|
||||
// Verificar estructura de tabla menu_options
|
||||
$tableStructure = $db->fetchAll("DESCRIBE menu_options");
|
||||
$availableColumns = array_column($tableStructure, 'Field');
|
||||
|
||||
// Preparar datos según estructura de tabla
|
||||
$updateData = [];
|
||||
|
||||
if (in_array('option_number', $availableColumns)) {
|
||||
$updateData['option_number'] = (int)$input['option_key'];
|
||||
}
|
||||
|
||||
if (in_array('option_key', $availableColumns)) {
|
||||
$updateData['option_key'] = $input['option_key'];
|
||||
}
|
||||
|
||||
if (in_array('text', $availableColumns)) {
|
||||
$updateData['text'] = $input['option_text'];
|
||||
}
|
||||
|
||||
if (in_array('option_text', $availableColumns)) {
|
||||
$updateData['option_text'] = $input['option_text'];
|
||||
}
|
||||
|
||||
if (in_array('action_type', $availableColumns)) {
|
||||
$updateData['action_type'] = $input['option_action'] ?? 'message';
|
||||
}
|
||||
|
||||
if (in_array('option_action', $availableColumns)) {
|
||||
$updateData['option_action'] = $input['option_action'] ?? 'message';
|
||||
}
|
||||
|
||||
if (in_array('action_value', $availableColumns)) {
|
||||
$updateData['action_value'] = $input['option_value'] ?? '';
|
||||
}
|
||||
|
||||
if (in_array('option_value', $availableColumns)) {
|
||||
$updateData['option_value'] = $input['option_value'] ?? '';
|
||||
}
|
||||
|
||||
if (in_array('updated_at', $availableColumns)) {
|
||||
$updateData['updated_at'] = date('Y-m-d H:i:s');
|
||||
}
|
||||
|
||||
// Actualizar la opción
|
||||
$result = $db->update('menu_options', $updateData, 'id = :option_id', ['option_id' => $optionId]);
|
||||
|
||||
if ($result && $result->rowCount() >= 0) {
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => 'Opción de menú actualizada correctamente',
|
||||
'option_id' => $optionId,
|
||||
'menu_id' => $option['menu_id']
|
||||
]);
|
||||
} else {
|
||||
throw new Exception('No se pudo actualizar la opción');
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("Error in update_menu_option.php: " . $e->getMessage());
|
||||
http_response_code(400);
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
/**
|
||||
* API para actualizar 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']);
|
||||
$name = isset($data['name']) && !empty(trim($data['name'])) ? trim($data['name']) : null;
|
||||
$status = isset($data['status']) ? $data['status'] : 'active';
|
||||
|
||||
// Validar status
|
||||
$valid_statuses = ['active', 'inactive', 'blocked'];
|
||||
if (!in_array($status, $valid_statuses)) {
|
||||
$status = 'active';
|
||||
}
|
||||
|
||||
// Crear conexión a la base de datos usando el patrón Singleton
|
||||
$db = Database::getInstance();
|
||||
|
||||
// Verificar si el usuario existe
|
||||
$checkUser = $db->fetch("SELECT id FROM users WHERE id = :user_id", ['user_id' => $user_id]);
|
||||
|
||||
if (!$checkUser) {
|
||||
throw new Exception('Usuario no encontrado');
|
||||
}
|
||||
|
||||
// Actualizar usuario usando el método de la clase Database
|
||||
$updateData = [
|
||||
'name' => $name,
|
||||
'status' => $status
|
||||
];
|
||||
|
||||
$result = $db->update('users', $updateData, 'id = :user_id', ['user_id' => $user_id]);
|
||||
|
||||
if ($result === false) {
|
||||
throw new Exception('No se pudo actualizar el usuario');
|
||||
}
|
||||
|
||||
// Respuesta exitosa
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => 'Usuario actualizado correctamente',
|
||||
'user_id' => $user_id,
|
||||
'data' => [
|
||||
'name' => $name,
|
||||
'status' => $status
|
||||
]
|
||||
]);
|
||||
|
||||
} 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()
|
||||
]
|
||||
]);
|
||||
}
|
||||
?>
|
||||
+1225
-7
File diff suppressed because it is too large
Load Diff
@@ -110,7 +110,15 @@ class Database {
|
||||
}
|
||||
|
||||
public function rollback() {
|
||||
return $this->pdo->rollback();
|
||||
try {
|
||||
return $this->pdo->rollback();
|
||||
} catch (PDOException $e) {
|
||||
// Si no hay transacción activa, simplemente ignorar
|
||||
if ($e->getCode() !== 'HY000' || strpos($e->getMessage(), 'no active transaction') === false) {
|
||||
throw $e;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function execute($sql, $params = []) {
|
||||
|
||||
Reference in New Issue
Block a user