Primer commit del sistema separado falta mejorar mucho
This commit is contained in:
138
discord/api/templates/edit.php
Executable file
138
discord/api/templates/edit.php
Executable file
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
/**
|
||||
* API de Plantillas de Discord - Editar
|
||||
* REFRACTORIZADO para usar la tabla `comandos_discord`
|
||||
*/
|
||||
|
||||
header('Content-Type: application/json');
|
||||
|
||||
require_once __DIR__ . '/../../../shared/utils/helpers.php';
|
||||
require_once __DIR__ . '/../../../shared/auth/jwt.php';
|
||||
require_once __DIR__ . '/../../../shared/database/connection.php';
|
||||
|
||||
ini_set('display_errors', 0);
|
||||
error_reporting(E_ALL);
|
||||
|
||||
try {
|
||||
$userData = JWTAuth::requireAuth();
|
||||
} catch (Exception $e) {
|
||||
http_response_code(401);
|
||||
echo json_encode(['success' => false, 'error' => 'Acceso no autorizado.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
if (!hasPermission('manage_templates', 'discord')) {
|
||||
http_response_code(403);
|
||||
echo json_encode(['success' => false, 'error' => 'No tienes permiso para editar plantillas de Discord.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
http_response_code(405);
|
||||
echo json_encode(['success' => false, 'error' => 'Método no permitido.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$data = json_decode(file_get_contents('php://input'), true);
|
||||
$plantilla_id = $data['id'] ?? null;
|
||||
$nombre = trim($data['nombre'] ?? '');
|
||||
$comando = ltrim(trim($data['comando'] ?? ''), '#/');
|
||||
$contenido = $data['contenido'] ?? '';
|
||||
|
||||
if (!$plantilla_id || !is_numeric($plantilla_id)) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['success' => false, 'error' => 'ID de plantilla inválido.']);
|
||||
exit;
|
||||
}
|
||||
if (empty($nombre) || empty($contenido)) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['success' => false, 'error' => 'El nombre y el contenido son obligatorios.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$db = getDB();
|
||||
try {
|
||||
logToFile('discord/templates.log', "Iniciando edición de plantilla (ID: {$plantilla_id}). Comando recibido: {$comando}", 'INFO');
|
||||
$db->beginTransaction();
|
||||
|
||||
// 1. Verificar que la plantilla existe y el usuario tiene permiso
|
||||
$stmt = $db->prepare("SELECT usuario_id FROM plantillas_discord WHERE id = ?");
|
||||
$stmt->execute([$plantilla_id]);
|
||||
$plantillaExistente = $stmt->fetch();
|
||||
|
||||
if (!$plantillaExistente) {
|
||||
throw new Exception('Plantilla no encontrada.', 404);
|
||||
}
|
||||
if ($userData->rol !== 'Admin' && $plantillaExistente['usuario_id'] != $userData->userId) {
|
||||
throw new Exception('No tiene permisos para editar esta plantilla.', 403);
|
||||
}
|
||||
|
||||
// 2. Actualizar la plantilla en sí (nombre y contenido)
|
||||
$stmt = $db->prepare("
|
||||
UPDATE plantillas_discord
|
||||
SET nombre = ?, contenido = ?, fecha_modificacion = NOW()
|
||||
WHERE id = ?
|
||||
");
|
||||
$stmt->execute([$nombre, $contenido, $plantilla_id]);
|
||||
|
||||
// 3. Gestionar el comando en la tabla `comandos_discord`
|
||||
// Primero, obtener el comando actual si existe
|
||||
$stmt = $db->prepare("SELECT id, comando FROM comandos_discord WHERE plantilla_id = ?");
|
||||
$stmt->execute([$plantilla_id]);
|
||||
$comandoExistente = $stmt->fetch();
|
||||
|
||||
logToFile('discord/templates.log', "Comando existente para plantilla {$plantilla_id}: " . ($comandoExistente ? json_encode($comandoExistente) : 'Ninguno'), 'INFO');
|
||||
|
||||
|
||||
// Antes de insertar/actualizar, verificar si el nuevo nombre de comando ya está en uso por OTRA plantilla
|
||||
if (!empty($comando)) {
|
||||
$stmt = $db->prepare("SELECT id FROM comandos_discord WHERE comando = ? AND plantilla_id != ?");
|
||||
$stmt->execute([$comando, $plantilla_id]);
|
||||
if ($stmt->fetch()) {
|
||||
throw new Exception('Ya existe otro comando con ese nombre.', 409);
|
||||
}
|
||||
}
|
||||
|
||||
// Lógica de casos
|
||||
if (!empty($comando) && $comandoExistente) {
|
||||
// Caso: El comando se está modificando
|
||||
if ($comando !== $comandoExistente['comando']) {
|
||||
logToFile('discord/templates.log', "Modificando comando existente para plantilla {$plantilla_id}. De: {$comandoExistente['comando']} a: {$comando}", 'INFO');
|
||||
$stmt = $db->prepare("UPDATE comandos_discord SET comando = ?, descripcion = ? WHERE id = ?");
|
||||
$stmt->execute([$comando, $nombre, $comandoExistente['id']]);
|
||||
} else {
|
||||
logToFile('discord/templates.log', "Comando existente no modificado para plantilla {$plantilla_id}. Valor: {$comando}", 'INFO');
|
||||
}
|
||||
} elseif (!empty($comando) && !$comandoExistente) {
|
||||
// Caso: Se está añadiendo un comando nuevo
|
||||
logToFile('discord/templates.log', "Añadiendo nuevo comando para plantilla {$plantilla_id}. Comando: {$comando}", 'INFO');
|
||||
$stmt = $db->prepare("INSERT INTO comandos_discord (comando, descripcion, plantilla_id) VALUES (?, ?, ?)");
|
||||
$stmt->execute([$comando, $nombre, $plantilla_id]);
|
||||
} elseif (empty($comando) && $comandoExistente) {
|
||||
// Caso: Se está eliminando el comando
|
||||
logToFile('discord/templates.log', "Eliminando comando existente para plantilla {$plantilla_id}. Comando: {$comandoExistente['comando']}", 'INFO');
|
||||
$stmt = $db->prepare("DELETE FROM comandos_discord WHERE id = ?");
|
||||
$stmt->execute([$comandoExistente['id']]);
|
||||
} else {
|
||||
logToFile('discord/templates.log', "No se gestionó comando para plantilla {$plantilla_id}. Comando recibido: {$comando}, Existente: " . ($comandoExistente ? $comandoExistente['comando'] : 'Ninguno'), 'INFO');
|
||||
}
|
||||
// Si no hay comando nuevo y no había uno existente, no se hace nada.
|
||||
|
||||
$db->commit();
|
||||
|
||||
logToFile('discord/templates.log', "Edición de plantilla completada (ID: {$plantilla_id}).", 'INFO');
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => 'Plantilla actualizada correctamente.'
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
if ($db->inTransaction()) {
|
||||
$db->rollBack();
|
||||
}
|
||||
$code = $e->getCode() >= 400 ? $e->getCode() : 500;
|
||||
http_response_code($code);
|
||||
logToFile('discord/templates.log', 'ERROR: Error editando plantilla (ID: ' . ($plantilla_id ?? 'N/A') . '): ' . $e->getMessage(), 'ERROR');
|
||||
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
|
||||
}
|
||||
Reference in New Issue
Block a user