126 lines
4.9 KiB
PHP
126 lines
4.9 KiB
PHP
<?php
|
|
require_once 'conexion.php';
|
|
header('Content-Type: application/json');
|
|
|
|
try {
|
|
$data = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!isset($data['columna_actual']) || !isset($data['columna_nueva']) || !isset($data['monto'])) {
|
|
throw new Exception("Datos incompletos");
|
|
}
|
|
|
|
$columna_actual = trim($data['columna_actual']);
|
|
$columna_nueva = trim($data['columna_nueva']);
|
|
$monto = floatval($data['monto']);
|
|
$fecha_hoy = date('Y-m-d'); // Necesitamos la fecha de hoy para los periodos
|
|
|
|
// Validar datos
|
|
if (empty($columna_actual) || empty($columna_nueva) || $monto < 0) {
|
|
throw new Exception("Datos inválidos");
|
|
}
|
|
|
|
// Convertir nuevo nombre a formato de columna
|
|
$nombre_columna = strtolower(str_replace(' ', '_', $columna_nueva));
|
|
|
|
// Validar que sea un nombre válido para columna SQL
|
|
if (!preg_match('/^[a-z_][a-z0-9_]*$/', $nombre_columna)) {
|
|
throw new Exception("Nombre de gasto inválido");
|
|
}
|
|
|
|
// Si el nombre cambió, renombrar la columna primero
|
|
if (strtolower(str_replace(' ', '_', $columna_actual)) !== $nombre_columna) {
|
|
$columna_actual_formatted = strtolower(str_replace(' ', '_', $columna_actual));
|
|
|
|
// Verificar que la columna actual existe
|
|
$sql_check = "SHOW COLUMNS FROM gastos LIKE '" . $conexion->real_escape_string($columna_actual_formatted) . "'";
|
|
$result_check = $conexion->query($sql_check);
|
|
|
|
if ($result_check === false || $result_check->num_rows === 0) {
|
|
throw new Exception("La columna de gasto no existe: " . $conexion->error);
|
|
}
|
|
|
|
// Renombrar columna (Nota: esto cambia el nombre también en los registros históricos)
|
|
$sql_rename = "ALTER TABLE gastos CHANGE COLUMN `$columna_actual_formatted` `$nombre_columna` DECIMAL(10,2)";
|
|
|
|
if (!$conexion->query($sql_rename)) {
|
|
throw new Exception("Error al renombrar columna: " . $conexion->error);
|
|
}
|
|
} else {
|
|
$nombre_columna = strtolower(str_replace(' ', '_', $columna_actual));
|
|
}
|
|
|
|
// Obtener el registro actual COMPLETO
|
|
$sql_get_actual = "SELECT * FROM gastos WHERE Periodo_Hasta IS NULL ORDER BY Periodo_Desde DESC LIMIT 1";
|
|
$result_actual = $conexion->query($sql_get_actual);
|
|
|
|
if ($result_actual && $result_actual->num_rows > 0) {
|
|
$valores_anteriores = $result_actual->fetch_assoc();
|
|
$id_gasto_actual = $valores_anteriores['ID_Gasto'];
|
|
|
|
// 1. Cerrar el periodo actual poniendo la fecha de hoy
|
|
$sql_update = "UPDATE gastos SET Periodo_Hasta = ? WHERE ID_Gasto = ?";
|
|
$stmt_update = $conexion->prepare($sql_update);
|
|
$stmt_update->bind_param('si', $fecha_hoy, $id_gasto_actual);
|
|
|
|
if (!$stmt_update->execute()) {
|
|
throw new Exception("Error cerrando periodo anterior: " . $stmt_update->error);
|
|
}
|
|
$stmt_update->close();
|
|
|
|
// 2. Preparar el nuevo registro (INSERT)
|
|
$columnas = ['Periodo_Desde', 'Periodo_Hasta'];
|
|
$valores = [$fecha_hoy, null];
|
|
$placeholders = ['?', '?'];
|
|
$tipos = 'ss';
|
|
|
|
// Recorrer los valores del registro que acabamos de cerrar
|
|
foreach ($valores_anteriores as $col => $val) {
|
|
// Ignorar las columnas de control
|
|
if (in_array($col, ['ID_Gasto', 'Periodo_Desde', 'Periodo_Hasta'])) {
|
|
continue;
|
|
}
|
|
|
|
$columnas[] = "`$col`"; // Usamos backticks por seguridad en los nombres
|
|
|
|
// Si es la columna que estamos editando, guardamos el NUEVO monto. Si no, arrastramos el viejo.
|
|
if ($col === $nombre_columna) {
|
|
$valores[] = $monto;
|
|
} else {
|
|
$valores[] = floatval($val);
|
|
}
|
|
|
|
$placeholders[] = '?';
|
|
$tipos .= 'd';
|
|
}
|
|
|
|
// 3. Insertar la nueva "versión" de los gastos
|
|
$sql_insert = "INSERT INTO gastos (" . implode(', ', $columnas) . ") VALUES (" . implode(', ', $placeholders) . ")";
|
|
$stmt_insert = $conexion->prepare($sql_insert);
|
|
|
|
if (!$stmt_insert) {
|
|
throw new Exception("Error preparando INSERT: " . $conexion->error);
|
|
}
|
|
|
|
$stmt_insert->bind_param($tipos, ...$valores);
|
|
|
|
if (!$stmt_insert->execute()) {
|
|
throw new Exception("Error insertando el nuevo periodo: " . $stmt_insert->error);
|
|
}
|
|
|
|
$stmt_insert->close();
|
|
} else {
|
|
throw new Exception("No hay un periodo de gastos activo para editar.");
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Gasto editado y nuevo periodo registrado correctamente'
|
|
]);
|
|
|
|
} catch (Exception $e) {
|
|
echo json_encode([
|
|
'success' => false,
|
|
'message' => $e->getMessage()
|
|
]);
|
|
}
|
|
?>
|