real_escape_string($nombre_columna) . "'"; $result_check = $conexion->query($sql_check); if ($result_check === false) { throw new Exception("Error verificando columna: " . $conexion->error); } if ($result_check->num_rows === 0) { // Columna no existe, agregar con ALTER TABLE $sql_alter = "ALTER TABLE gastos ADD COLUMN `$nombre_columna` DECIMAL(10,2) DEFAULT NULL"; if (!$conexion->query($sql_alter)) { throw new Exception("Error al agregar columna: " . $conexion->error); } } // Obtener el ID del registro anterior (donde Periodo_Hasta IS NULL) $sql_get_id = "SELECT ID_Gasto FROM gastos WHERE Periodo_Hasta IS NULL ORDER BY Periodo_Desde DESC LIMIT 1"; $result_id = $conexion->query($sql_get_id); $fecha_hoy = date('Y-m-d'); $id_anterior = null; if ($result_id && $result_id->num_rows > 0) { $row = $result_id->fetch_assoc(); $id_anterior = $row['ID_Gasto']; // Cerrar el período anterior $sql_update = "UPDATE gastos SET Periodo_Hasta = ? WHERE ID_Gasto = ?"; $stmt_update = $conexion->prepare($sql_update); $stmt_update->bind_param('si', $fecha_hoy, $id_anterior); if (!$stmt_update->execute()) { throw new Exception("Error actualizando período anterior: " . $stmt_update->error); } $stmt_update->close(); // Obtener todos los valores del registro anterior para reutilizarlos $sql_get_values = "SELECT * FROM gastos WHERE ID_Gasto = ?"; $stmt_get_values = $conexion->prepare($sql_get_values); $stmt_get_values->bind_param('i', $id_anterior); $stmt_get_values->execute(); $result_values = $stmt_get_values->get_result(); $valores_anteriores = $result_values->fetch_assoc(); $stmt_get_values->close(); } // Construir INSERT dinámico $columnas = ['Periodo_Desde', 'Periodo_Hasta', $nombre_columna]; $valores = [date('Y-m-d'), null, $monto]; $placeholders = ['?', '?', '?']; $tipos = 'ssd'; // Si hay datos anteriores, agregar todas las columnas existentes if (!empty($valores_anteriores)) { foreach ($valores_anteriores as $col => $val) { if (!in_array($col, ['ID_Gasto', 'Periodo_Desde', 'Periodo_Hasta', $nombre_columna])) { $columnas[] = $col; $valores[] = $val; $placeholders[] = '?'; $tipos .= 'd'; } } } $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 registro: " . $stmt_insert->error); } $nuevo_id = $stmt_insert->insert_id; $stmt_insert->close(); echo json_encode([ 'success' => true, 'message' => 'Gasto agregado correctamente', 'id_gasto' => $nuevo_id ]); } catch (Exception $e) { echo json_encode([ 'success' => false, 'message' => $e->getMessage() ]); } ?>