query($sql_get_actual); if ($result_actual && $result_actual->num_rows > 0) { $row_actual = $result_actual->fetch_assoc(); $id_gasto_actual = $row_actual['ID_Gasto']; // Actualizar el Periodo_Hasta del registro actual con la fecha actual $sql_update = "UPDATE gastos SET Periodo_Hasta = ? WHERE ID_Gasto = ?"; $stmt_update = $conexion->prepare($sql_update); if (!$stmt_update) { throw new Exception("Error preparando UPDATE: " . $conexion->error); } $stmt_update->bind_param('si', $fecha_hoy, $id_gasto_actual); if (!$stmt_update->execute()) { throw new Exception("Error actualizando perĂ­odo anterior: " . $stmt_update->error); } $stmt_update->close(); // Obtener todos los valores del registro que acaba de cerrarse $sql_get_values = "SELECT * FROM gastos WHERE ID_Gasto = ?"; $stmt_get_values = $conexion->prepare($sql_get_values); $stmt_get_values->bind_param('i', $id_gasto_actual); $stmt_get_values->execute(); $result_values = $stmt_get_values->get_result(); $valores_anteriores = $result_values->fetch_assoc(); $stmt_get_values->close(); } else { $valores_anteriores = null; } // Construir INSERT dinĂ¡mico $columnas = ['Periodo_Desde', 'Periodo_Hasta']; $valores = [$fecha_hoy, null]; $placeholders = ['?', '?']; $tipos = 'ss'; // Agregar columnas de gastos del request foreach ($gastos as $col => $val) { $columnas[] = $col; $valores[] = floatval($val); $placeholders[] = '?'; $tipos .= 'd'; } // Agregar columnas restantes del registro anterior (si existen) if (!empty($valores_anteriores)) { foreach ($valores_anteriores as $col => $val) { if (!in_array($col, ['ID_Gasto', 'Periodo_Desde', 'Periodo_Hasta']) && !isset($gastos[$col])) { $columnas[] = $col; $valores[] = floatval($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' => 'Gastos guardados correctamente', 'id_gasto' => $nuevo_id ]); } catch (Exception $e) { echo json_encode([ 'success' => false, 'message' => $e->getMessage() ]); } ?>