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() ]); } ?>