Untitled

 avatar
unknown
plain_text
5 months ago
48 kB
6
Indexable
import java.util.ArrayList;
import java.util.List;

public class Facility {
    private String name;
    private double pricePerHour;
    private List<Reservation> reservations; // A list of reservations for this facility

    // Constructor
    public Facility(String name, double pricePerHour) {
        this.name = name;
        this.pricePerHour = pricePerHour;
        this.reservations = new ArrayList<>();
    }

    public String getName() {
        return name;
    }

    public double getPricePerHour() {
        return pricePerHour;
    }

    // Method to get the list of reservations for this facility
    public List<Reservation> getReservations() {
        return reservations;
    }

    // Method to add a reservation and handle conflicts
    public String addReservation(Reservation reservation) {
        // Check for conflicts with existing reservations
        for (Reservation existingReservation : reservations) {
            if (existingReservation.conflictsWith(reservation)) {
                return "The facility is not available at the selected time.";
            }
        }

        // Add the reservation to the list
        reservations.add(reservation);
        return "Reservation confirmed for " + reservation.getEventName() + " on " + reservation.getDate() +
                " at " + reservation.getTime() + ".";
    }

    // Method to display the facility's schedule
    public String displaySchedule() {
        StringBuilder schedule = new StringBuilder(name + " Schedule:\n");
        for (Reservation reservation : reservations) {
            schedule.append(reservation.toString()).append("\n");
        }
        return schedule.toString();
    }

    // Method to cancel a reservation based on ID and user
    public boolean cancelReservation(int reservationId, User user) {
        for (Reservation reservation : reservations) {
            if (reservation.getId() == reservationId && reservation.getReservedBy().equals(user.getUsername())) {
                reservations.remove(reservation);
                return true;
            }
        }
        return false;
    }
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class LoginForm {
    private JTextField emailField;
    private JPasswordField passwordField;
    private JTextField usernameField; // Used for registration only
    private JLabel usernameLabel; // Label for the username field (for registration only)
    private JLabel toggleLabel; // Label to show "Already have an account?"
    private JButton loginButton;
    private JButton toggleButton;
    private SportsComplex complex;
    private User currentUser;
    private boolean isLoginMode = true; // Default mode is login

    public LoginForm() {
        complex = new SportsComplex();
        createAndShowGUI();
    }

    private void createAndShowGUI() {
        // Set up the frame
        JFrame frame = new JFrame("Login/SignUp Form");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);

        // Set layout manager for better control
        frame.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5); // Padding around components
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // Add the logo at the top
        ImageIcon logoIcon = new ImageIcon("logo.png"); // Replace with your image path
        JLabel logoLabel = new JLabel(logoIcon);
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2; // Span across two columns
        gbc.anchor = GridBagConstraints.CENTER; // Center the label
        frame.add(logoLabel, gbc);

        // Add "PlaySafe" text below the logo
        JLabel titleLabel = new JLabel("PlaySafe", JLabel.CENTER);
        titleLabel.setFont(new Font("Ubuntu Mono", Font.BOLD, 24)); // Set font size and style
        titleLabel.setForeground(Color.BLACK); // Set text color
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 2; // Span across two columns
        gbc.anchor = GridBagConstraints.CENTER; // Center the label
        frame.add(titleLabel, gbc);

        // Create the text fields and buttons
        emailField = new JTextField(15);
        passwordField = new JPasswordField(15);
        usernameField = new JTextField(15); // Username for registration only
        usernameLabel = new JLabel("Username:"); // Username label
        usernameField.setVisible(false); // Initially hidden for login mode

        loginButton = createStyledButton("Login");
        toggleButton = createStyledButton("Sign Up");

        // Create the toggle label (for registration link)
        toggleLabel = new JLabel("Don't have an account?");

        // Add Email label and field
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 1; // Reset to single column
        frame.add(new JLabel("Email:"), gbc);
        gbc.gridx = 1;
        frame.add(emailField, gbc);

        // Add Password label and field
        gbc.gridx = 0;
        gbc.gridy = 3;
        frame.add(new JLabel("Password:"), gbc);
        gbc.gridx = 1;
        frame.add(passwordField, gbc);

        // Add Username label and field (hidden for login)
        gbc.gridx = 0;
        gbc.gridy = 4;
        frame.add(usernameLabel, gbc);
        gbc.gridx = 1;
        frame.add(usernameField, gbc);

        // Add Login button
        gbc.gridx = 0;
        gbc.gridy = 5;
        gbc.gridwidth = 2;
        frame.add(loginButton, gbc);

        // Add the toggle label ("Don't have an account?")
        gbc.gridx = 0;
        gbc.gridy = 6;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER; // Center the label
        frame.add(toggleLabel, gbc);

        // Add Toggle button
        gbc.gridx = 0;
        gbc.gridy = 7;
        gbc.gridwidth = 2;
        frame.add(toggleButton, gbc);

        // Action listener for the login/register button
        loginButton.addActionListener(e -> {
            if (isLoginMode) {
                login(frame);  // Perform login
            } else {
                register(frame);  // Perform registration
            }
        });

        // Action listener for the toggle button
        toggleButton.addActionListener(e -> toggleMode(frame));

        // Make the frame visible
        frame.setVisible(true);
    }

    // Helper method to create styled buttons with hover effect
    private JButton createStyledButton(String text) {
        JButton button = new JButton(text);
        button.setPreferredSize(new Dimension(150, 30));
        button.setBackground(Color.WHITE); // Set background color to white
        button.setForeground(Color.BLACK); // Set text color to black
        button.setFocusPainted(false); // Remove the focus outline on the button
        button.setBorder(BorderFactory.createLineBorder(Color.BLACK)); // Add a black border to the button
        button.setFont(new Font("Arial", Font.BOLD, 14)); // Set font style and size

        // Add hover effect by changing background and border color when the mouse enters/exits
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                button.setBackground(Color.LIGHT_GRAY); // Change to light gray on hover
                button.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY)); // Darken the border on hover
            }

            @Override
            public void mouseExited(MouseEvent e) {
                button.setBackground(Color.WHITE); // Revert to white when not hovering
                button.setBorder(BorderFactory.createLineBorder(Color.BLACK)); // Revert to black border
            }
        });

        return button;
    }

    private void toggleMode(JFrame frame) {
        if (isLoginMode) {
            // Switch to register mode
            isLoginMode = false;
            loginButton.setText("Sign Up");  // Change button to "Register"
            toggleButton.setText("Login");  // Change toggle button
            toggleLabel.setText("Already have an account?"); // Set label for login
            usernameLabel.setVisible(true); // Show username label for registration
            usernameField.setVisible(true); // Show username field for registration
        } else {
            // Switch to login mode
            isLoginMode = true;
            loginButton.setText("Login");  // Change button to "Login"
            toggleButton.setText("Sign Up");  // Change toggle button
            toggleLabel.setText("Don't have an account?"); // Set label for registration
            usernameLabel.setVisible(false); // Hide username label for login
            usernameField.setVisible(false); // Hide username field for login
        }
        frame.revalidate(); // Revalidate the frame to update the layout
        frame.repaint();    // Repaint the frame to reflect changes
    }

    private void login(JFrame frame) {
        // Get login credentials
        String email = emailField.getText();
        String password = new String(passwordField.getPassword());

        // Attempt login
        currentUser = complex.logIn(email, password);
        if (currentUser != null) {
            frame.dispose(); // Close the login frame
            JOptionPane.showMessageDialog(null, "Log in successful");
            new Main(currentUser, complex); // Proceed to main page
        } else {
            JOptionPane.showMessageDialog(frame, "Invalid email or password."); // Display error
        }
    }

    private void register(JFrame frame) {
        // Get registration details
        String email = emailField.getText();
        String password = new String(passwordField.getPassword());
        String username = usernameField.getText();

        // Validate registration input
        if (email.isEmpty() || password.isEmpty() || username.isEmpty()) {
            JOptionPane.showMessageDialog(frame, "All fields are required.");
            return;
        }

        // Attempt registration
        String registrationMessage = complex.signIn(email, password, username);
        if (registrationMessage.equals("Sign in successful.")) {
            JOptionPane.showMessageDialog(frame, "Registration successful. You can now log in.");
            toggleMode(frame); // Switch back to login mode after successful registration
        } else {
            JOptionPane.showMessageDialog(frame, registrationMessage); // Display the appropriate error message
        }
    }

    public static void main(String[] args) {
        new LoginForm();
    }
}

import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

class Main {
    private User currentUser; // Currently logged-in user
    private SportsComplex complex; // Instance of SportsComplex

    public Main(User user, SportsComplex complex) {
        this.currentUser = user; // Assign the current user
        this.complex = complex; // Assign the SportsComplex instance
        createAndShowGUI(); // Create and display the main page
    }

    private void createAndShowGUI() {
        // Set up the main frame
        JFrame frame = new JFrame("Main Page");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 400);
        frame.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 10, 5, 10); // Padding around components

        // Set background color of the frame to white
        frame.getContentPane().setBackground(Color.WHITE);

        // Add Welcome Label
        JLabel welcomeLabel = new JLabel("Hi! " + currentUser.getUsername() + ", Welcome to PlaySafe");
        welcomeLabel.setFont(new Font("Arial", Font.BOLD, 20));
        welcomeLabel.setForeground(Color.BLACK); // Set the welcome text to black
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2; // Span across both columns
        frame.add(welcomeLabel, gbc);

        // Create buttons for various actions
        JButton checkAvailabilityButton = createStyledButton("Check Facility Availability", Color.BLACK);
        JButton viewPricingButton = createStyledButton("View Facility Pricing", Color.BLACK);
        JButton createBookingButton = createStyledButton("Create a Booking", Color.BLACK);
        JButton cancelBookingButton = createStyledButton("Cancel a Booking", Color.BLACK);
        JButton trackHistoryButton = createStyledButton("Track Booking History", Color.BLACK);
        JButton logoutButton = createStyledButton("Logout", Color.BLACK);

        // Add buttons to the frame - Group 1
        gbc.gridwidth = 1;
        gbc.gridx = 0;
        gbc.gridy = 1;
        frame.add(checkAvailabilityButton, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        frame.add(viewPricingButton, gbc);

        // Add buttons to the frame - Group 2
        gbc.gridx = 1;
        gbc.gridy = 1;
        frame.add(createBookingButton, gbc);

        gbc.gridx = 1;
        gbc.gridy = 2;
        frame.add(cancelBookingButton, gbc);

        // Add remaining buttons to the frame
        gbc.gridx = 0;
        gbc.gridy = 3;
        frame.add(trackHistoryButton, gbc);

        gbc.gridx = 1;
        gbc.gridy = 3;
        frame.add(logoutButton, gbc);

        // Set action listeners for buttons
        checkAvailabilityButton.addActionListener(e -> viewSchedule());
        viewPricingButton.addActionListener(e -> viewFacilityPricing());
        createBookingButton.addActionListener(e -> createBooking());
        cancelBookingButton.addActionListener(e -> cancelBooking());
        trackHistoryButton.addActionListener(e -> trackBookingHistory());
        logoutButton.addActionListener(e -> {
            JOptionPane.showMessageDialog(null, "Thank you for using PlaySafe App!");
            frame.dispose(); // Close the current frame
            new LoginForm(); // Return to login form
        });

        // Make the frame visible
        frame.setVisible(true);
    }

    // Create a styled button with custom colors
    private JButton createStyledButton(String text, Color textColor) {
        JButton button = new JButton(text);
        button.setPreferredSize(new Dimension(200, 30));
        button.setBackground(Color.WHITE); // Set button background to white
        button.setForeground(textColor); // Set button text color
        button.setFocusPainted(false);
        button.setFont(new Font("Arial", Font.BOLD, 12));
        return button;
    }
    private Map<String, Boolean> facilityAvailability = new HashMap<>(); // To track facility availability

    private void initializeFacilityAvailability() {
        facilityAvailability.put("Basketball Court", true);
        facilityAvailability.put("Swimming Pool", true);
        facilityAvailability.put("Football Field", true);
    }

    private String[] facilities = {"Basketball Court", "Swimming Pool", "Football Field", "Volleyball Court", "Badminton Court"};
    private int[] bookingCounts = new int[facilities.length];

    private void viewSchedule() {
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.CENTER;

        // Title: View Schedule
        gbc.gridx = 0;  // Column
        gbc.gridy = 0;  // Row
        gbc.gridwidth = 2;
        JLabel titleLabel = new JLabel("View Schedule");
        titleLabel.setFont(new Font("Arial", Font.BOLD, 20));
        panel.add(titleLabel, gbc);

        gbc.gridy++; // Move to the next row
        gbc.gridwidth = 2; // Span across the whole row
        panel.add(new JSeparator(SwingConstants.HORIZONTAL), gbc); // Line separator

        JTextPane textPane = new JTextPane();
        textPane.setEditable(false); // Make it non-editable
        textPane.setPreferredSize(new Dimension(400, 200)); // Set preferred size
        textPane.setBackground(new Color(240, 248, 255)); // Light background for readability
        textPane.setFont(new Font("Arial", Font.PLAIN, 15));

        // Build the facility schedule content using StyledDocument for JTextPane
        StyledDocument doc = textPane.getStyledDocument();
        SimpleAttributeSet centerAlign = new SimpleAttributeSet();
        StyleConstants.setAlignment(centerAlign, StyleConstants.ALIGN_CENTER);
        doc.setParagraphAttributes(0, doc.getLength(), centerAlign, false); // Apply to the whole document

        // Set up date formatter for 12-hour format with AM/PM
        SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm a"); // 12-hour format with AM/PM

        // Check if the user has any reservations
        List<Reservation> reservations = currentUser.getReservations(); // Assume currentUser is the logged-in user

        if (reservations.isEmpty()) {
            try {
                doc.insertString(doc.getLength(), "No reservations found.\n", null);
            } catch (BadLocationException e) {
                e.printStackTrace();
            }
        } else {
            for (Reservation reservation : reservations) {
                try {
                    String reservationInfo;
                    // Format start and end times
                    String formattedStartTime = timeFormat.format(parseTime(reservation.getTime()));
                    String formattedEndTime = timeFormat.format(parseTime(reservation.getEndTime()));

                    if (reservation.isCancelled()) {
                        // Indicate that this reservation is canceled
                        reservationInfo = String.format(
                                "%s:\nID: %d, Event: %s, Date: %s, Time: %s - Ends at: %s [CANCELLED]\n",
                                reservation.getFacilityName(),
                                reservation.getId(),
                                reservation.getEventName(),
                                reservation.getDate(),
                                formattedStartTime,
                                formattedEndTime
                        );
                    } else {
                        // Display active reservations
                        reservationInfo = String.format(
                                "%s:\nID: %d, Event: %s, Date: %s, Time: %s - Ends at: %s\n",
                                reservation.getFacilityName(),
                                reservation.getId(),
                                reservation.getEventName(),
                                reservation.getDate(),
                                formattedStartTime,
                                formattedEndTime
                        );
                    }

                    // Insert the reservation info into the text pane
                    doc.insertString(doc.getLength(), reservationInfo, null);

                } catch (BadLocationException e) {
                    e.printStackTrace();
                }
            }
        }

        JScrollPane scrollPane = new JScrollPane(textPane);
        scrollPane.setPreferredSize(new Dimension(400, 200));

        gbc.gridy++;
        gbc.gridwidth = 2;
        panel.add(scrollPane, gbc);

        JOptionPane optionPane = new JOptionPane(panel, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION);
        JDialog dialog = optionPane.createDialog("View Schedule");
        dialog.setSize(500, 400);
        dialog.setVisible(true);
    }

    // Helper method to parse time strings (in "HH:mm" format) to Date objects
    private Date parseTime(String time) {
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm"); // 24-hour format
        try {
            return timeFormat.parse(time); // Parse the time string to a Date object
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private void viewFacilityPricing() {
        // Create a panel with GridBagLayout for flexible layout
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10); // Padding around components
        gbc.anchor = GridBagConstraints.CENTER;  // Center-align components

        // Title: Facility Pricing (centered)
        gbc.gridx = 0;  // Column
        gbc.gridy = 0;  // Row
        gbc.gridwidth = 2; // Span across two columns for centering
        JLabel titleLabel = new JLabel("Facility Price List");
        titleLabel.setFont(new Font("Arial", Font.BOLD, 20)); // Larger, bold font for title
        panel.add(titleLabel, gbc);

        // Add a divider or line break
        gbc.gridy++; // Move to the next row
        gbc.gridwidth = 2; // Span across the whole row
        panel.add(new JSeparator(SwingConstants.HORIZONTAL), gbc); // Line separator

        // Create JTextPane to display facility pricing
        JTextPane textPane = new JTextPane();
        textPane.setEditable(false); // Make it non-editable
        textPane.setPreferredSize(new Dimension(400, 200)); // Set preferred size
        textPane.setBackground(new Color(240, 248, 255)); // Light background for readability
        textPane.setFont(new Font("Arial", Font.PLAIN, 14)); // Set the font to Arial

        // Get the styled document to add styles to the JTextPane
        StyledDocument doc = textPane.getStyledDocument();

        // Center alignment for the text
        SimpleAttributeSet centered = new SimpleAttributeSet();
        StyleConstants.setAlignment(centered, StyleConstants.ALIGN_CENTER);

        // Add each facility and its price
        try {
            doc.setParagraphAttributes(0, doc.getLength(), centered, false);

            for (Facility facility : complex.facilities.values()) {
                doc.insertString(doc.getLength(), facility.getName() + ": ₱" + facility.getPricePerHour() + " per hour\n", null);
            }

        } catch (BadLocationException e) {
            e.printStackTrace();
        }

        // Add the JTextPane wrapped in a JScrollPane to handle overflow
        JScrollPane scrollPane = new JScrollPane(textPane);
        scrollPane.setPreferredSize(new Dimension(400, 200)); // Set preferred size

        gbc.gridy++; // Move to the next row for JTextPane
        gbc.gridwidth = 2; // Span across the whole row
        panel.add(scrollPane, gbc); // Add JTextPane to the panel

        // Show the facility pricing in a dialog
        JOptionPane optionPane = new JOptionPane(panel, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION);
        JDialog dialog = optionPane.createDialog("Facility Pricing");
        dialog.setSize(500, 400);
        dialog.setVisible(true); // Show the dialog
    }
    private void createBooking() {
        // Define available facilities
        String[] facilities = {"Basketball Court", "Swimming Pool", "Football Field", "Volleyball Court", "Badminton Court"}; // Add more facilities as needed

        // Create a combo box for facility selection
        JComboBox<String> facilityComboBox = new JComboBox<>(facilities);
        facilityComboBox.setSelectedIndex(0); // Set default selection

        // Create input fields for other booking details
        JTextField eventNameField = new JTextField(20);

        // Create input fields for date
        JTextField dateField = new JTextField(10);
        dateField.setText(new java.text.SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime())); // Set current date as default

        // Create input field for time
        JTextField timeField = new JTextField(5);
        timeField.setText(new java.text.SimpleDateFormat("hh:mm").format(Calendar.getInstance().getTime())); // Set current time as default

        // Create a combo box for AM/PM selection
        String[] amPmOptions = {"AM", "PM"};
        JComboBox<String> amPmComboBox = new JComboBox<>(amPmOptions);
        amPmComboBox.setSelectedItem("AM"); // Set default to AM

        // Create input field for duration
        JTextField durationField = new JTextField(5);

        // Create a panel to hold the input components
        JPanel panel = new JPanel(new GridLayout(0, 1)); // Vertical layout
        panel.add(new JLabel("Select Facility:"));
        panel.add(facilityComboBox);
        panel.add(new JLabel("Enter Event:"));
        panel.add(eventNameField);
        panel.add(new JLabel("Enter Date (YYYY-MM-DD):"));
        panel.add(dateField);
        panel.add(new JLabel("Enter Time (hh:mm):"));
        panel.add(timeField);
        panel.add(amPmComboBox); // Add AM/PM selection
        panel.add(new JLabel("Enter Duration in Hours:"));
        panel.add(durationField);

        // Show the input dialog
        int result = JOptionPane.showConfirmDialog(null, panel, "Create Booking", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

        // If user clicked OK, proceed with booking
        if (result == JOptionPane.OK_OPTION) {
            String facilityName = (String) facilityComboBox.getSelectedItem();
            String eventName = eventNameField.getText();
            String date = dateField.getText();
            String time = timeField.getText() + " " + amPmComboBox.getSelectedItem(); // Combine time and AM/PM
            int duration;

            // Validate and parse duration
            try {
                duration = Integer.parseInt(durationField.getText());
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(null, "Invalid duration. Please enter a number.", "Error", JOptionPane.ERROR_MESSAGE);
                return; // Exit the method if duration is invalid
            }

            // Validate date format (basic check)
            if (!date.matches("\\d{4}-\\d{2}-\\d{2}")) {
                JOptionPane.showMessageDialog(null, "Invalid date format. Please use YYYY-MM-DD.", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // Validate time format (basic check)
            if (!time.matches("\\d{1,2}:\\d{2} (AM|PM)")) {
                JOptionPane.showMessageDialog(null, "Invalid time format. Please use hh:mm AM/PM.", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // Attempt to make a reservation and show the result
            String message = complex.makeReservation(currentUser, facilityName, eventName, date, time, duration);
            JOptionPane.showMessageDialog(null, message);
        }
    }

    private void cancelBooking() {
        // Create a panel to hold the input components with more spacing
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10); // Add padding around components

        // Add a label for the reservation ID
        gbc.gridx = 0; // Column
        gbc.gridy = 0; // Row
        gbc.anchor = GridBagConstraints.CENTER; // Center alignment
        panel.add(new JLabel("Enter Reservation ID to Cancel:"), gbc);

        // Input field for reservation ID
        JTextField reservationIdField = new JTextField(15); // Wider field
        reservationIdField.setPreferredSize(new Dimension(200, 30)); // Set preferred size
        gbc.gridx = 0; // Column
        gbc.gridy = 1; // Row
        panel.add(reservationIdField, gbc);

        // Calculate dialog size based on the preferred sizes
        Dimension size = new Dimension(300, 150); // Default size
        panel.setPreferredSize(size);

        // Show the input dialog with a custom size
        JOptionPane optionPane = new JOptionPane(panel, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
        JDialog dialog = optionPane.createDialog("Cancel Booking");

        // Set the dialog size to accommodate the panel
        dialog.pack(); // Automatically sizes the dialog to fit the components
        dialog.setLocationRelativeTo(null); // Center the dialog on the screen
        dialog.setVisible(true); // Show the dialog

        // Get the user’s choice
        Object selectedValue = optionPane.getValue();
        if (selectedValue == null) {
            return; // User closed the dialog without action
        }

        // If user clicked OK, proceed with cancellation
        if (selectedValue.equals(JOptionPane.OK_OPTION)) {
            String reservationIdText = reservationIdField.getText();
            int reservationId;

            // Validate and parse reservation ID
            try {
                reservationId = Integer.parseInt(reservationIdText);
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(null, "Invalid ID. Please enter a numeric reservation ID.", "Error", JOptionPane.ERROR_MESSAGE);
                return; // Exit the method if the ID is invalid
            }

            // Confirmation dialog
            int confirmation = JOptionPane.showConfirmDialog(null,
                    "Are you sure you want to cancel reservation ID: " + reservationId + "?",
                    "Confirm Cancellation", JOptionPane.YES_NO_OPTION);

            // If user confirms, attempt to cancel the reservation and show the result
            if (confirmation == JOptionPane.YES_OPTION) {
                if (complex.cancelReservation(currentUser, reservationId)) {
                    JOptionPane.showMessageDialog(null, "Reservation canceled successfully.", "Success", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(null, "Reservation ID not found. Please check and try again.", "Error", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Cancellation aborted.", "Info", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }
    private void trackBookingHistory() {
        List<Reservation> reservations = currentUser.getReservations(); // Assume this method exists

        // Create the panel to hold the UI components
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.CENTER;

        // Title: Booking History
        gbc.gridx = 0;  // Column
        gbc.gridy = 0;  // Row
        gbc.gridwidth = 2;
        JLabel titleLabel = new JLabel("Reservations History");
        titleLabel.setFont(new Font("Arial", Font.BOLD, 20));
        panel.add(titleLabel, gbc);

        gbc.gridy++; // Move to the next row
        gbc.gridwidth = 2; // Span across the whole row
        panel.add(new JSeparator(SwingConstants.HORIZONTAL), gbc); // Line separator

        JTextPane textPane = new JTextPane();
        textPane.setEditable(false); // Make it non-editable
        textPane.setPreferredSize(new Dimension(400, 200)); // Set preferred size
        textPane.setBackground(new Color(240, 248, 255));
        textPane.setFont(new Font("Arial", Font.PLAIN, 14));

        StyledDocument doc = textPane.getStyledDocument();

        // Center alignment for the text
        SimpleAttributeSet centered = new SimpleAttributeSet();
        StyleConstants.setAlignment(centered, StyleConstants.ALIGN_CENTER);

        // Add a date formatter for 12-hour time with AM/PM
        SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm a");

        // Add each reservation to the JTextPane
        try {
            doc.setParagraphAttributes(0, doc.getLength(), centered, false);

            if (reservations.isEmpty()) {
                doc.insertString(doc.getLength(), "No reservations history found.\n", null);
            } else {
                for (Reservation reservation : reservations) {
                    // Format the start and end times
                    String formattedStartTime = timeFormat.format(parseTime(reservation.getTime()));
                    String formattedEndTime = timeFormat.format(parseTime(reservation.getEndTime()));

                    // Add reservation information
                    doc.insertString(doc.getLength(),
                            String.format("Facility: %s, Date: %s, Time: %s - Ends at: %s\nReserved by: %s\n\n",
                                    reservation.getFacilityName(),
                                    reservation.getDate(),
                                    formattedStartTime,
                                    formattedEndTime,
                                    reservation.getReservedBy()),  // Assuming you have this field in the Reservation class
                            null);
                }
            }
        } catch (BadLocationException e) {
            e.printStackTrace();
        }

        JScrollPane scrollPane = new JScrollPane(textPane);
        scrollPane.setPreferredSize(new Dimension(400, 200)); // Set preferred size

        gbc.gridy++; // Move to the next row for JTextPane
        gbc.gridwidth = 2; // Span across the whole row
        panel.add(scrollPane, gbc); // Add JTextPane to the panel

        // Create the JOptionPane dialog
        JOptionPane optionPane = new JOptionPane(panel, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION);
        JDialog dialog = optionPane.createDialog("Your Reservations History");
        dialog.setSize(500, 400);
        dialog.setVisible(true);
    }
}   

import javax.swing.*;
import java.awt.*;

class RegisterForm {
    private JTextField emailField;
    private JPasswordField passwordField;
    private JTextField usernameField;
    private JButton registerButton;
    private JButton backButton;
    private SportsComplex complex;

    public RegisterForm(SportsComplex complex) {
        this.complex = complex;
        createAndShowGUI();
    }

    private void createAndShowGUI() {
        JFrame frame = new JFrame("Register Form");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 250);
        frame.setLayout(new GridLayout(4, 2));

        emailField = new JTextField(15);
        passwordField = new JPasswordField(15);
        usernameField = new JTextField(15);
        registerButton = new JButton("Register");
        backButton = new JButton("Back to Login");

        frame.add(new JLabel("Email:"));
        frame.add(emailField);
        frame.add(new JLabel("Password:"));
        frame.add(passwordField);
        frame.add(new JLabel("Username:"));
        frame.add(usernameField);
        frame.add(registerButton);
        frame.add(backButton);

        // Register action
        registerButton.addActionListener(e -> register(frame));
        // Back button action to return to Login Form
        backButton.addActionListener(e -> {
            frame.dispose(); // Close the register form
            new LoginForm(); // Open the login form
        });

        frame.setVisible(true);
    }

    private void register(JFrame frame) {
        String email = emailField.getText();
        String password = new String(passwordField.getPassword());
        String username = usernameField.getText();
        String message = complex.signIn(email, password, username);
        JOptionPane.showMessageDialog(frame, message);

        if (message.equals("Sign in successful.")) {
            frame.dispose(); // Close the register form
            new Main(complex.logIn(email, password), complex); // Proceed to main page after successful registration
        }
    }
}

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

class Reservation {
    private static int counter = 0;
    private static List<Reservation> reservations = new ArrayList<>();

    public static List<Reservation> getReservations() {
        return reservations; // Return the static list of reservations
    }

    private int id;
    private String eventName;
    private User reservedBy; // Change to User object for tracking who made the reservation
    private String date;
    private String time; // format HH:mm or HH:mm AM/PM
    private int duration; // Duration in hours
    private String facilityName;
    private boolean isCancelled; // Add this variable to track cancellation

    // Constructor
    public Reservation(String eventName, User reservedBy, String date, String time, int duration, String facilityName) {
        this.id = ++counter;
        this.eventName = eventName;
        this.reservedBy = reservedBy; // Now a User object
        this.date = date;
        this.time = time;
        this.duration = duration;
        this.facilityName = facilityName;
        this.isCancelled = false; // Set to false by default when creating a new reservation
        reservations.add(this); // Add new reservation to the list
    }

    // Getter for isCancelled
    public boolean isCancelled() {
        return isCancelled;
    }

    // Setter for isCancelled
    public void setCancelled(boolean cancelled) {
        this.isCancelled = cancelled;
    }

    public static boolean cancelReservation(User user, int reservationId) {
        Reservation reservationToCancel = null;

        // Find the reservation to cancel
        for (Reservation reservation : reservations) {
            if (reservation.getId() == reservationId) {
                // Check if the user is the one who made the reservation
                if (reservation.getReservedBy().equals(user)) {
                    reservationToCancel = reservation;
                } else {
                    JOptionPane.showMessageDialog(null, "You cannot cancel a reservation made by another user.");
                    return false; // Exit if the user does not match
                }
                break;
            }
        }

        if (reservationToCancel != null) {
            reservationToCancel.setCancelled(true); // Mark as cancelled
            System.out.println("Reservation canceled: " + reservationToCancel.getFacilityName());

            // Ask user if they want to reschedule
            int choice = JOptionPane.showConfirmDialog(null,
                    "Do you want to reschedule your reservation?",
                    "Reschedule Confirmation",
                    JOptionPane.YES_NO_OPTION);

            if (choice == JOptionPane.YES_OPTION) {
                String newDate = JOptionPane.showInputDialog("Enter new date (YYYY-MM-DD):");
                String newTime = JOptionPane.showInputDialog("Enter new time (HH:mm AM/PM):");
                int newDuration = 0;
                boolean validInput = false;

                // Validate duration input
                while (!validInput) {
                    try {
                        newDuration = Integer.parseInt(JOptionPane.showInputDialog("Enter duration in hours:"));
                        if (newDuration > 0) {
                            validInput = true; // Valid input
                        } else {
                            JOptionPane.showMessageDialog(null, "Duration must be greater than 0. Please try again.");
                        }
                    } catch (NumberFormatException e) {
                        JOptionPane.showMessageDialog(null, "Invalid input. Please enter a valid number for duration.");
                    }
                }

                // Create a new reservation attempt
                Reservation newReservation = new Reservation(reservationToCancel.getEventName(),
                        reservationToCancel.getReservedBy(),
                        newDate,
                        newTime,
                        newDuration,
                        reservationToCancel.getFacilityName());

                // Check if the new reservation conflicts with existing reservations
                if (!isTimeSlotAvailable(newReservation)) {
                    JOptionPane.showMessageDialog(null, "Time not available. Unable to reschedule.",
                            "Reservation Conflict",
                            JOptionPane.INFORMATION_MESSAGE);
                } else {
                    // If available, confirm the new reservation
                    reservations.add(newReservation);
                    JOptionPane.showMessageDialog(null, "Reservation successfully rescheduled.");
                }
            }
            return true; // Successfully canceled
        } else {
            JOptionPane.showMessageDialog(null, "Reservation not found.");
            return false; // Reservation not found
        }
    }

    private static boolean isTimeSlotAvailable(Reservation reservation) {
        for (Reservation r : reservations) {
            if (r.conflictsWith(reservation)) {
                return false; // Conflict found, time slot not available
            }
        }
        return true; // No conflict, time slot is available
    }

    public int getId() {
        return id;
    }

    public String getEventName() {
        return eventName;
    }

    public User getReservedBy() {
        return reservedBy; // Getter for reservedBy
    }

    public String getDate() {
        return date;
    }

    public String getTime() {
        return time;
    }

    public int getDuration() {
        return duration;
    }

    public String getFacilityName() {
        return facilityName;
    }

    // New method to get end time
    public String getEndTime() {
        int startTimeInMinutes = convertTimeToMinutes(this.time);
        int endTimeInMinutes = startTimeInMinutes + (this.duration * 60);

        int endHour = endTimeInMinutes / 60;
        int endMinute = endTimeInMinutes % 60;

        return String.format("%02d:%02d", endHour, endMinute); // Format as HH:mm
    }

    public boolean conflictsWith(Reservation other) {
        return date.equals(other.date) && overlapsWith(other.time, other.duration);
    }

    // Method to check for overlapping reservations
    public boolean overlapsWith(String otherTime, int otherDuration) {
        int thisStartTime = convertTimeToMinutes(this.time);
        int thisEndTime = thisStartTime + (this.duration * 60);

        int otherStartTime = convertTimeToMinutes(otherTime);
        int otherEndTime = otherStartTime + (otherDuration * 60);

        return (thisStartTime < otherEndTime && otherStartTime < thisEndTime);
    }

    private int convertTimeToMinutes(String time) {
        // Check if the time is in 12-hour format
        if (time.endsWith("AM") || time.endsWith("PM")) {
            String[] parts = time.split(":");
            if (parts.length != 2) {
                throw new IllegalArgumentException("Invalid time format: " + time);
            }

            int hours = Integer.parseInt(parts[0].trim());
            int minutes = Integer.parseInt(parts[1].trim().substring(0, 2)); // Extracting minutes

            // Convert hours to 24-hour format
            if (time.endsWith("PM") && hours != 12) {
                hours += 12; // Convert PM hours to 24-hour format
            } else if (time.endsWith("AM") && hours == 12) {
                hours = 0; // Convert 12 AM to 0 hours
            }

            return hours * 60 + minutes; // Total minutes
        } else {
            // If it's in 24-hour format
            String[] parts = time.split(":");
            if (parts.length != 2) {
                throw new IllegalArgumentException("Invalid time format: " + time);
            }

            int hours = Integer.parseInt(parts[0].trim());
            int minutes = Integer.parseInt(parts[1].trim());

            return hours * 60 + minutes; // Total minutes
        }
    }
}

import java.util.HashMap;
import java.util.Map;

class SportsComplex {
    private Map<String, User> users;
    public Map<String, Facility> facilities;

    public SportsComplex() {
        users = new HashMap<>();
        facilities = new HashMap<>();
        facilities.put("Basketball Court", new Facility("Basketball Court", 140)); // Corrected price
        facilities.put("Swimming Pool", new Facility("Swimming Pool", 200)); // Corrected price
        facilities.put("Football Field", new Facility("Football Field", 300)); // Corrected price
    }

    public String signIn(String email, String password, String username) {
        if (!isValidEmail(email)) {
            return "Invalid email format. Please use a valid email (e.g., user@example.com).";
        }
        if (!users.containsKey(email)) {
            users.put(email, new User(email, password, username));
            return "Sign in successful.";
        }
        return "Email already exists.";
    }

    public User logIn(String email, String password) {
        User user = users.get(email);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }

    public String makeReservation(User user, String facilityName, String eventName, String date, String time, int duration) {
        Facility facility = facilities.get(facilityName);
        if (facility != null) {
            Reservation reservation = new Reservation(eventName, user, date, time, duration, facilityName);
            String message = facility.addReservation(reservation);
            if (message.contains("Reservation confirmed")) {
                user.addReservation(reservation); // Assuming addReservation is defined in User class
            }
            return message;
        }
        return "Facility not found.";
    }

    public boolean cancelReservation(User user, int reservationId) {
        for (Facility facility : facilities.values()) {
            if (facility.cancelReservation(reservationId, user)) {
                return true;
            }
        }
        return false;
    }

    public String displaySchedules() {
        StringBuilder sb = new StringBuilder();
        for (Facility facility : facilities.values()) {
            sb.append(facility.displaySchedule());
        }
        return sb.toString();
    }

    private boolean isValidEmail(String email) {
        return email.contains("@") && email.endsWith(".com");
    }
}

import javax.swing.*;
public class SportsComplexReservationSystem {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(LoginForm::new); // Start the application
    }
}


import java.util.ArrayList;
import java.util.List;

public class User {
    private String email;
    private String password;
    private String username;
    private List<Reservation> reservations;

    public User(String email, String password, String username) {
        this.email = email;
        this.password = password;
        this.username = username;
        this.reservations = new ArrayList<>();
    }

    public String getEmail() {
        return email;
    }

    public String getPassword() {
        return password;
    }

    public String getUsername() {
        return username;
    }

    public List<Reservation> getReservations() {
        return reservations;
    }

    public void addReservation(Reservation reservation) {
        reservations.add(reservation);
    }

    public boolean cancelReservation(Reservation reservation) {
        return reservations.remove(reservation);
    }
}

Editor is loading...
Leave a Comment