OneCompiler

Code

107
    // Method to view booking history (US_PROG_004)
    private static void ViewBookingHistory()
    {
        if (loggedInUser == null)
        {
            Console.WriteLine("Please log in to view your booking history.");
            return;
        }

        Console.Write("Enter customer ID: ");
        if (!int.TryParse(Console.ReadLine(), out int customerId))
        {
            Console.WriteLine("Invalid customer ID.");
            return;
        }

        User customer = UserRepository.GetUserById(customerId);
        if (customer == null)
        {
            Console.WriteLine("Customer ID does not exist in the system.");
            return;
        }

        List<Booking> bookingHistory = BookingRepository.GetBookingsByUserId(customerId);
        if (bookingHistory.Count == 0)
        {
            Console.WriteLine("No booking history found for this customer.");
            return;
        }

        Console.WriteLine("\nBooking History:");
        Console.WriteLine("---------------------------------------------------------------------------------------------------");
        Console.WriteLine("Booking ID | Train Number | Booking Date    | Seat Numbers       | Fare    | Booking Status");
        Console.WriteLine("---------------------------------------------------------------------------------------------------");
        foreach (Booking booking in bookingHistory)
        {
            string seatNumbers = string.Join(",", booking.SeatNumbers);
            Console.WriteLine($"{booking.BookingID,-11} | {booking.TrainNumber,-12} | {booking.BookingDate,-16:d} | {seatNumbers,-18} | {booking.Fare,-8} | {booking.BookingStatus,-14}");
        }
        Console.WriteLine("---------------------------------------------------------------------------------------------------");
    }

    // Method to view trains sorted by departure time (US_PROG_005)
    private static void SortTrainsByDepartureTime()
    {
        Console.Write("Enter origin station: ");
        string origin = Console.ReadLine();
        Console.Write("Enter destination station: ");
        string destination = Console.ReadLine();

        // Basic input validation
        if (string.IsNullOrEmpty(origin) || string.IsNullOrEmpty(destination))
        {
            Console.WriteLine("Origin and Destination stations are required.");
            return;
        }

        List<Train> sortedTrains = TrainRepository.SearchTrains(origin, destination, DateTime.MinValue) // Pass DateTime.MinValue to get all
                                                             .OrderBy(t => t.DepartureTime)
                                                             .ToList();

        if (sortedTrains.Count == 0)
        {
            Console.WriteLine("No trains found for the given origin and destination.");
            return;
        }

        Console.WriteLine("\nTrains Sorted by Departure Time:");
        Console.WriteLine("---------------------------------------------------------------------------------------------------");
        Console.WriteLine("Train Number | Train Name       | Departure Time        | Arrival Time          | Origin    | Destination");
        Console.WriteLine("---------------------------------------------------------------------------------------------------");
        foreach (Train train in sortedTrains)
        {
            Console.WriteLine($"{train.TrainNumber,-13} | {train.TrainName,-16} | {train.DepartureTime,-24:f} | {train.ArrivalTime,-24:f} | {train.Origin,-10} | {train.Destination,-12}");
        }
        Console.WriteLine("---------------------------------------------------------------------------------------------------");
    }

    // Method to find trains with available seats (US_PROG_006)
    private static void FindTrainsWithAvailableSeats()
    {
        Console.Write("Enter origin station: ");
        string origin = Console.ReadLine();
        Console.Write("Enter destination station: ");
        string destination = Console.ReadLine();
        Console.Write("Enter number of tickets: ");
        if (!int.TryParse(Console.ReadLine(), out int numberOfTickets))
        {
            Console.WriteLine("Invalid number of tickets.");
            return;
        }

        // Basic input validation
        if (string.IsNullOrEmpty(origin) || string.IsNullOrEmpty(destination))
        {
            Console.WriteLine("Origin and Destination stations are required.");
            return;
        }

        if (numberOfTickets <= 0)
        {
            Console.WriteLine("Number of tickets must be greater than zero.");
            return;
        }

        List<Train> availableTrains = new List<Train>();
        List<Train> allTrains = TrainRepository.SearchTrains(origin, destination, DateTime.MinValue); // Get all trains first

        foreach (Train train in allTrains)
        {
            // Calculate available seats for each train
            List<Booking> existingBookings = BookingRepository.GetBookingsByTrainNumberAndDate(train.TrainNumber, DateTime.Now); // Consider bookings for today
            int bookedSeats = existingBookings.Sum(b => b.SeatNumbers.Count);
            int availableSeats = train.TotalSeats - bookedSeats;

            if (availableSeats >= numberOfTickets)
            {
                availableTrains.Add(train);
            }
        }

        if (availableTrains.Count == 0)
        {
            Console.WriteLine($"No trains found with {numberOfTickets} or more available seats for the given origin and destination.");
            return;
        }

        Console.WriteLine($"\nTrains with {numberOfTickets} or more Available Seats:");
        Console.WriteLine("---------------------------------------------------------------------------------------------------");
        Console.WriteLine("Train Number | Train Name       | Departure Time        | Arrival Time          | Origin    | Destination | Available Seats");
        Console.WriteLine("---------------------------------------------------------------------------------------------------");
        foreach (Train train in availableTrains)
        {
            List<Booking> existingBookings = BookingRepository.GetBookingsByTrainNumberAndDate(train.TrainNumber, DateTime.Now); // Consider bookings for today
            int bookedSeats = existingBookings.Sum(b => b.SeatNumbers.Count);
            int availableSeats = train.TotalSeats - bookedSeats;
            Console.WriteLine($"{train.TrainNumber,-13} | {train.TrainName,-16} | {train.DepartureTime,-24:f} | {train.ArrivalTime,-24:f} | {train.Origin,-10} | {train.Destination,-12} | {availableSeats,-15}");
        }
        Console.WriteLine("---------------------------------------------------------------------------------------------------");
    }

    // Method to dynamically allocate seats (US_PROG_007)
    private static void DynamicallyAllocateSeats(Train train, DateTime bookingDate, int numberOfPassengers)
    {
         if (train == null)
        {
            Console.WriteLine("Train not found.");
            return;
        }

        if (numberOfPassengers <= 0 || numberOfPassengers > 10)
        {
            Console.WriteLine("Number of passengers must be between 1 and 10.");
            return;
        }
         if (bookingDate.Date < DateTime.Now.Date)
        {
             Console.WriteLine("Booking date cannot be in the past.");
             return;
        }

        // Get existing bookings for the train and date to determine occupied seats
        List<Booking> existingBookings = BookingRepository.GetBookingsByTrainNumberAndDate(train.TrainNumber, bookingDate);
        List<int> occupiedSeats = new List<int>();
        foreach (var booking in existingBookings)
        {
            occupiedSeats.AddRange(booking.SeatNumbers);
        }

        // Get all available seat numbers
        List<int> allSeats = Enumerable.Range(1, train.TotalSeats).ToList();
        List<int> availableSeats = allSeats.Except(occupiedSeats).ToList();

        if (availableSeats.Count < numberOfPassengers)
        {
            Console.WriteLine("Not enough available seats to accommodate the requested number of passengers.");
            return;
        }

        List<int> allocatedSeats = new List<int>();
        // 1. Try to find adjacent seats
        for (int i = 0; i <= availableSeats.Count - numberOfPassengers; i++)
        {
            bool areAdjacent = true;
            for (int j = 0; j < numberOfPassengers; j++)
            {
                if (availableSeats[i + j] != availableSeats[i] + j)
                {
                    areAdjacent = false;
                    break;
                }
            }
            if (areAdjacent)
            {
                allocatedSeats = availableSeats.GetRange(i, numberOfPassengers);
                break;
            }
        }

        // 2. If adjacent seats not found, allocate closest available seats
        if (allocatedSeats.Count == 0)
        {
            availableSeats.Sort(); // Sort for closest
            allocatedSeats = availableSeats.Take(numberOfPassengers).ToList();
        }
         if (allocatedSeats.Count != numberOfPassengers)
        {
            Console.WriteLine("Error: Could not allocate the required number of seats.");
            return; // Or throw an exception
        }

        // Display the allocated seats to the user for confirmation
        Console.WriteLine("\nDynamically Allocated Seats:");
        Console.WriteLine(string.Join(", ", allocatedSeats));

        Console.Write("Do you want to confirm these seats? (yes/no): ");
        string confirmation = Console.ReadLine().ToLower();

        if (confirmation == "yes")
        {
            // Create a new booking with the allocated seats
             decimal fare = allocatedSeats.Count * 100;
            Booking newBooking = new Booking
            {
                CustomerID = loggedInUser.UserID, // Use the logged-in user's ID
                TrainNumber = train.TrainNumber,
                BookingDate = bookingDate,
                SeatNumbers = allocatedSeats,
                Fare = fare, // Calculate fare
                BookingStatus = "Booked"
            };

            BookingRepository.AddBooking(newBooking);
            Console.WriteLine($"Booking confirmed. Your Booking ID is {newBooking.BookingID}.");
             Console.WriteLine($"Total Fare: ${newBooking.Fare}");
        }
        else
        {
            Console.WriteLine("Seat allocation cancelled.");
        }
    }
}

}