Advertisement
Gaudenz

SessionsForm.java

Mar 26th, 2025
366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 32.59 KB | None | 0 0
  1. package lyfjshs.gomis.view.sessions;
  2.  
  3. import java.awt.BorderLayout;
  4. import java.awt.Color;
  5. import java.awt.Dimension;
  6. import java.awt.FlowLayout;
  7. import java.awt.Font;
  8. import java.awt.Graphics;
  9. import java.awt.Graphics2D;
  10. import java.awt.GridLayout;
  11. import java.awt.Window;
  12. import java.awt.print.PageFormat;
  13. import java.awt.print.Printable;
  14. import java.awt.print.PrinterException;
  15. import java.awt.print.PrinterJob;
  16. import java.sql.Connection;
  17. import java.time.LocalDate;
  18. import java.time.LocalTime;
  19. import java.util.HashMap;
  20. import java.util.Map;
  21.  
  22. import javax.swing.BorderFactory;
  23. import javax.swing.JButton;
  24. import javax.swing.JComboBox;
  25. import javax.swing.JDialog;
  26. import javax.swing.JFormattedTextField;
  27. import javax.swing.JFrame;
  28. import javax.swing.JLabel;
  29. import javax.swing.JOptionPane;
  30. import javax.swing.JPanel;
  31. import javax.swing.JScrollPane;
  32. import javax.swing.JSeparator;
  33. import javax.swing.JTable;
  34. import javax.swing.JTextArea;
  35. import javax.swing.JTextField;
  36. import javax.swing.SwingConstants;
  37. import javax.swing.SwingUtilities;
  38. import javax.swing.table.DefaultTableModel;
  39.  
  40. import lyfjshs.gomis.Main;
  41. import lyfjshs.gomis.Database.DAO.AppointmentDAO;
  42. import lyfjshs.gomis.Database.DAO.ParticipantsDAO;
  43. import lyfjshs.gomis.Database.DAO.SessionsDAO;
  44. import lyfjshs.gomis.Database.DAO.ViolationCRUD;
  45. import lyfjshs.gomis.Database.entity.Appointment;
  46. import lyfjshs.gomis.Database.entity.Participants;
  47. import lyfjshs.gomis.Database.entity.Sessions;
  48. import lyfjshs.gomis.Database.entity.Student;
  49. import lyfjshs.gomis.components.FormManager.Form;
  50. import lyfjshs.gomis.components.FormManager.FormManager;
  51. import lyfjshs.gomis.view.appointment.AppointmentSearchPanel;
  52. import lyfjshs.gomis.view.students.StudentSearchPanel;
  53. import lyfjshs.gomis.view.violation.Violation_Record;
  54. import net.miginfocom.swing.MigLayout;
  55. import raven.datetime.DatePicker;
  56. import raven.datetime.TimePicker;
  57. import raven.modal.ModalDialog;
  58. import raven.modal.component.SimpleModalBorder;
  59.  
  60. public class SessionsForm extends Form implements Printable {
  61.     private JComboBox<String> violationField;
  62.     private JFormattedTextField timeField, dateField; // Declare the missing dateField
  63.     private JTextArea sessionSummaryArea, notesArea;
  64.     private JButton saveButton, printButton, searchStudentButton;
  65.     private JComboBox<String> participantsComboBox;
  66.     private JComboBox<String> consultationTypeComboBox;
  67.     private JComboBox<String> appointmentTypeComboBox;
  68.     private Connection connect;
  69.     private JPanel mainPanel;
  70.     private JComboBox<String> sexCBox;
  71.     private JTextField firstNameField, lastNameField, contactNumberField;
  72.     private JPanel contentPanel;
  73.     private JPanel panel;
  74.     private JSeparator separator;
  75.     private JPanel panel_1;
  76.     private JTable participantTable;
  77.     private DefaultTableModel participantTableModel;
  78.     private Map<Integer, Map<String, String>> participantDetails = new HashMap<>();
  79.     private Map<Integer, Participants> pendingParticipants = new HashMap<>();
  80.     private int tempIdCounter = -1;
  81.     private JButton searchBtn;
  82.     private Runnable saveCallback;
  83.     private JTextField customViolationField;
  84.     private Integer selectedAppointmentId = null;
  85.     private DatePicker sessionDatePicker;
  86.     private TimePicker sessionTimePicker;
  87.  
  88.     // Violation type arrays
  89.     private String[] violations = { "Absence/Late", "Minor Property Damage", "Threatening/Intimidating",
  90.             "Pornographic Materials", "Gadget Use in Class", "Cheating", "Stealing", "No Pass", "Bullying",
  91.             "Sexual Abuse", "Illegal Drugs", "Alcohol", "Smoking/Vaping", "Gambling", "Public Display of Affection",
  92.             "Fighting/Weapons", "Severe Property Damage", "Others" };
  93.  
  94.     private JTextField recordedByField;
  95.     private JLabel lblSessionTime;
  96.  
  97.     public SessionsForm(Connection conn) {
  98.         this.connect = conn;
  99.         initializeComponents();
  100.         layoutComponents();
  101.         populateRecordedByField(); // Call the method to populate the recordedByField
  102.     }
  103.  
  104.     private void initializeComponents() {
  105.         // Initialize the table model
  106.         participantTableModel = new DefaultTableModel(
  107.                 new Object[] { "#", "Participant Name", "Participant Type", "Actions", "ID" }, 0) {
  108.             @Override
  109.             public boolean isCellEditable(int row, int column) {
  110.                 return false; // Make all cells non-editable
  111.             }
  112.         };
  113.  
  114.         sessionTimePicker = new TimePicker();
  115.         sessionDatePicker = new DatePicker();
  116.  
  117.         // Initialize custom violation field
  118.         customViolationField = new JTextField(15);
  119.         customViolationField.setVisible(false);
  120.         customViolationField.setEnabled(false);
  121.  
  122.         // Initialize violation field with combined offenses
  123.         violationField = new JComboBox<>();
  124.         violationField.addItem("-- Select Violation --");
  125.         for (String violation : violations) {
  126.             violationField.addItem(violation);
  127.         }
  128.  
  129.         // Add listener to update violation type label and show/hide custom field
  130.         violationField.addActionListener(e -> {
  131.             String selected = (String) violationField.getSelectedItem();
  132.             if (selected == null || selected.equals("-- Select Violation --")) {
  133.                 customViolationField.setEnabled(false);
  134.                 customViolationField.setVisible(false);
  135.                 customViolationField.setText(""); // Clear the text when hidden
  136.             } else if (selected.equals("Others")) {
  137.                 customViolationField.setEnabled(true);
  138.                 customViolationField.setVisible(true);
  139.             } else {
  140.                 customViolationField.setEnabled(false);
  141.                 customViolationField.setVisible(false);
  142.                 customViolationField.setText(""); // Clear the text when hidden
  143.             }
  144.         });
  145.  
  146.         // Initialize recorded by field as JTextField
  147.         recordedByField = new JTextField();
  148.         recordedByField.setEditable(false); // Make it read-only
  149.     }
  150.  
  151.     private void toggleSearchStudentButton() {
  152.         searchStudentButton.setEnabled("Student".equals(participantsComboBox.getSelectedItem()));
  153.     }
  154.  
  155.     private void openStudentSearchUI() {
  156.         String modalId = "session_student_search"; // Use unique modal ID
  157.         if (ModalDialog.isIdExist(modalId)) {
  158.             return;
  159.         }
  160.  
  161.         StudentSearchPanel searchPanel = new StudentSearchPanel(connect, modalId) {
  162.             @Override
  163.             protected void onStudentSelected(Student student) {
  164.                 // Create new participant
  165.                 Participants participant = new Participants();
  166.                 participant.setStudentUid(student.getStudentUid());
  167.                 participant.setParticipantType("Student");
  168.                 participant.setParticipantLastName(student.getStudentLastname());
  169.                 participant.setParticipantFirstName(student.getStudentFirstname());
  170.                 participant.setSex(student.getStudentSex());
  171.                 participant.setContactNumber(student.getContact().getContactNumber());
  172.  
  173.                 // Generate temporary ID
  174.                 int tempId = tempIdCounter--;
  175.  
  176.                 // Store in pendingParticipants
  177.                 pendingParticipants.put(tempId, participant);
  178.  
  179.                 Map<String, String> details = new HashMap<>();
  180.                 details.put("firstName", participant.getParticipantFirstName());
  181.                 details.put("lastName", participant.getParticipantLastName());
  182.                 details.put("fullName", participant.getParticipantFirstName() + " " + participant.getParticipantLastName());
  183.                 details.put("type", "Student");
  184.                 details.put("contact", participant.getContactNumber());
  185.                 details.put("sex", participant.getSex());
  186.                 participantDetails.put(tempId, details);
  187.  
  188.                 // Add to table with row number and hidden tempId
  189.                 int rowNumber = participantTableModel.getRowCount() + 1;
  190.                 participantTableModel
  191.                         .addRow(new Object[] { rowNumber, details.get("fullName"), "Student", "View | Remove", tempId });
  192.  
  193.                 // Close the modal using the correct ID
  194.                 ModalDialog.closeModal(modalId);
  195.             }
  196.         };
  197.  
  198.         // Configure modal options
  199.         ModalDialog.getDefaultOption()
  200.                 .setOpacity(0f)
  201.                 .setAnimationOnClose(false)
  202.                 .getBorderOption()
  203.                 .setBorderWidth(0.5f)
  204.                 .setShadow(raven.modal.option.BorderOption.Shadow.MEDIUM);
  205.  
  206.         // Show modal with the correct ID
  207.         ModalDialog.showModal(this, searchPanel, modalId);
  208.         ModalDialog.getDefaultOption().getLayoutOption().setSize(700, 500);
  209.     }
  210.  
  211.     public void setSaveCallback(Runnable saveCallback) {
  212.         this.saveCallback = saveCallback;
  213.     }
  214.  
  215.     private void clearFields() {
  216.         firstNameField.setText("");
  217.         lastNameField.setText("");
  218.         contactNumberField.setText("");
  219.         notesArea.setText("");
  220.         sessionSummaryArea.setText("");
  221.         timeField.setText("");
  222.         dateField.setText("");
  223.  
  224.         participantsComboBox.setSelectedIndex(0);
  225.         consultationTypeComboBox.setSelectedIndex(0);
  226.         appointmentTypeComboBox.setSelectedIndex(0);
  227.         sexCBox.setSelectedIndex(0);
  228.         violationField.setSelectedIndex(0);
  229.  
  230.         participantTableModel.setRowCount(0);
  231.         participantDetails.clear();
  232.         pendingParticipants.clear();
  233.         tempIdCounter = -1; // Reset for next session
  234.         selectedAppointmentId = null;
  235.     }
  236.  
  237.     private void addParticipant() {
  238.         String firstName = firstNameField.getText();
  239.         String lastName = lastNameField.getText();
  240.         String contact = contactNumberField.getText();
  241.         String sex = (String) sexCBox.getSelectedItem();
  242.  
  243.         // Validate input
  244.         if (firstName.trim().isEmpty() || lastName.trim().isEmpty()) {
  245.             JOptionPane.showMessageDialog(this, "Please enter at least first and last name", "Missing Information",
  246.                     JOptionPane.WARNING_MESSAGE);
  247.             return;
  248.         }
  249.  
  250.         // Create new participant
  251.         Participants participant = new Participants();
  252.         participant.setStudentUid(null);
  253.         participant.setParticipantType("Non-Student");
  254.         participant.setParticipantLastName(lastName);
  255.         participant.setParticipantFirstName(firstName);
  256.         participant.setSex(sex);
  257.         participant.setContactNumber(contact);
  258.  
  259.         // Generate temporary ID
  260.         int tempId = tempIdCounter--;
  261.  
  262.         // Store in pendingParticipants
  263.         pendingParticipants.put(tempId, participant);
  264.  
  265.         // Store participant details
  266.         Map<String, String> details = new HashMap<>();
  267.         details.put("firstName", firstName);
  268.         details.put("lastName", lastName);
  269.         details.put("fullName", firstName + " " + lastName);
  270.         details.put("contact", contact);
  271.         details.put("sex", sex);
  272.         details.put("type", "Non-Student");
  273.         participantDetails.put(tempId, details);
  274.  
  275.         // Add to table with row number and hidden tempId
  276.         int rowNumber = participantTableModel.getRowCount() + 1;
  277.         participantTableModel
  278.                 .addRow(new Object[] { rowNumber, details.get("fullName"), "Non-Student", "View | Remove", tempId });
  279.  
  280.         // Clear input fields
  281.         firstNameField.setText("");
  282.         lastNameField.setText("");
  283.         contactNumberField.setText("");
  284.         sexCBox.setSelectedIndex(0);
  285.     }
  286.  
  287.     private void setupParticipantTableListener() {
  288.         participantTable.addMouseListener(new java.awt.event.MouseAdapter() {
  289.             public void mouseClicked(java.awt.event.MouseEvent evt) {
  290.                 int row = participantTable.rowAtPoint(evt.getPoint());
  291.                 int col = participantTable.columnAtPoint(evt.getPoint());
  292.  
  293.                 if (col == 3) { // Actions column
  294.                     int id = (int) participantTableModel.getValueAt(row, 4); // Get tempId or actual ID from hidden
  295.                                                                                 // column
  296.  
  297.                     int clickX = evt.getX();
  298.                     int cellX = participantTable.getCellRect(row, col, false).x;
  299.                     int relativeX = clickX - cellX;
  300.                     int viewWidth = 40; // Approximate width of "View"
  301.  
  302.                     if (relativeX <= viewWidth) {
  303.                         // View
  304.                         showParticipantDetails(id);
  305.                     } else {
  306.                         // Remove
  307.                         int option = JOptionPane.showConfirmDialog(SessionsForm.this,
  308.                                 "Are you sure you want to remove this participant?", "Confirm Remove",
  309.                                 JOptionPane.YES_NO_OPTION);
  310.                         if (option == JOptionPane.YES_OPTION) {
  311.                             // Remove from maps if new participant
  312.                             participantDetails.remove(id);
  313.                             pendingParticipants.remove(id); // Only affects new participants with tempId
  314.  
  315.                             // Remove row from table
  316.                             participantTableModel.removeRow(row);
  317.  
  318.                             // Update row numbers
  319.                             for (int i = 0; i < participantTableModel.getRowCount(); i++) {
  320.                                 participantTableModel.setValueAt(i + 1, i, 0);
  321.                             }
  322.                         }
  323.                     }
  324.                 }
  325.             }
  326.         });
  327.     }
  328.  
  329.     private void layoutComponents() {
  330.         this.setLayout(new MigLayout("gap 10", "[grow]", "[grow]"));
  331.         contentPanel = new JPanel(new MigLayout("", "[grow]", "[][grow]"));
  332.         add(contentPanel, "cell 0 0,grow");
  333.         sessionSummaryArea = new JTextArea(4, 20);
  334.  
  335.         saveButton = new JButton("SAVE");
  336.         saveButton.setBackground(new Color(70, 130, 180));
  337.         saveButton.setForeground(Color.WHITE);
  338.         saveButton.setFocusPainted(false);
  339.         saveButton.addActionListener(e -> saveSessionToDatabase());
  340.  
  341.         // Header with improved styling
  342.         JPanel headerPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
  343.         contentPanel.add(headerPanel, "cell 0 0,growx");
  344.         JLabel headerLabel = new JLabel("Session Documentation Form");
  345.         headerLabel.setFont(new Font("SansSerif", Font.BOLD, 24));
  346.         headerLabel.setForeground(Color.WHITE);
  347.         headerPanel.add(headerLabel);
  348.         headerPanel.setBackground(new Color(5, 117, 230));
  349.         headerPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
  350.  
  351.         firstNameField = new JTextField(10);
  352.         lastNameField = new JTextField(10);
  353.  
  354.         // Main Panel with improved spacing
  355.         mainPanel = new JPanel(new MigLayout("wrap, gap 15, hidemode 3, insets 20", "[][grow][20px][][]",
  356.                 "[][][][][][][fill][][grow][][]"));
  357.         contentPanel.add(mainPanel, "cell 0 1,grow");
  358.         mainPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10),
  359.                 BorderFactory.createLineBorder(new Color(200, 200, 200))));
  360.  
  361.         separator = new JSeparator();
  362.         separator.setSize(new Dimension(20, 20));
  363.         separator.setBackground(Color.GRAY);
  364.         separator.setForeground(Color.DARK_GRAY);
  365.         separator.setOrientation(SwingConstants.VERTICAL);
  366.         mainPanel.add(separator, "cell 2 0 1 7");
  367.  
  368.         // Participant Panel
  369.         JPanel participantPanel = new JPanel(new MigLayout("gap 10", "[][][][][]", "[][][][]"));
  370.         participantPanel.setBorder(BorderFactory.createTitledBorder("Add Participant"));
  371.  
  372.         // Participant
  373.         JLabel participantLabel = new JLabel("Participant Type: ");
  374.         participantPanel.add(participantLabel, "cell 0 0");
  375.         participantsComboBox = new JComboBox<>(new String[] { "Student", "Non-Student" });
  376.         participantPanel.add(participantsComboBox, "cell 1 0 2 1,growx");
  377.         participantsComboBox.addActionListener(e -> toggleSearchStudentButton());
  378.  
  379.         searchStudentButton = new JButton("Search Student");
  380.         participantPanel.add(searchStudentButton, "cell 3 0");
  381.         searchStudentButton.setEnabled(false);
  382.         searchStudentButton.addActionListener(e -> openStudentSearchUI());
  383.  
  384.         participantPanel.add(new JLabel("First Name"), "cell 0 1");
  385.         participantPanel.add(firstNameField, "cell 1 1,growx");
  386.  
  387.         participantPanel.add(new JLabel("Last Name"), "cell 3 1");
  388.         participantPanel.add(lastNameField, "cell 4 1");
  389.  
  390.         JLabel lblSexl = new JLabel("Sex: ");
  391.         participantPanel.add(lblSexl, "flowx,cell 0 2");
  392.  
  393.         mainPanel.add(participantPanel, "cell 1 0 1 5,growx"); // Initially visible
  394.  
  395.         JButton saveParticipantButton = new JButton("Add Participant");
  396.         saveParticipantButton.addActionListener(e -> addParticipant());
  397.         sexCBox = new JComboBox<>(new String[] { "Male", "Female" });
  398.         participantPanel.add(sexCBox, "cell 1 2,growx");
  399.  
  400.         JLabel label = new JLabel("Contact Number");
  401.         participantPanel.add(label, "flowx,cell 3 2");
  402.         contactNumberField = new JTextField(10);
  403.         participantPanel.add(contactNumberField, "cell 4 2,growx");
  404.         participantPanel.add(saveParticipantButton, "cell 4 3,alignx center");
  405.  
  406.         // Start Time
  407.         JLabel startTimeLabel = new JLabel("Session Date");
  408.         mainPanel.add(startTimeLabel, "flowx,cell 3 1");
  409.  
  410.         // Initialize the dateField
  411.         dateField = new JFormattedTextField();
  412.         sessionDatePicker.setSelectedDate(LocalDate.now());
  413.         sessionDatePicker.setEditor(dateField);
  414.         dateField.setColumns(10);
  415.         mainPanel.add(dateField, "cell 3 1,growx");
  416.  
  417.         lblSessionTime = new JLabel("Session Time");
  418.         mainPanel.add(lblSessionTime, "flowx,cell 3 2");
  419.  
  420.         timeField = new JFormattedTextField();
  421.         sessionTimePicker.setSelectedTime(LocalTime.now());
  422.         sessionTimePicker.setEditor(timeField);
  423.         timeField.setColumns(10);
  424.         mainPanel.add(timeField, "cell 3 2,growx");
  425.  
  426.         // Appointment Type
  427.         JLabel appointmentTypeLabel = new JLabel("Appointment Type");
  428.         mainPanel.add(appointmentTypeLabel, "flowx,cell 3 3,alignx left");
  429.  
  430.         searchBtn = new JButton("Search Appointment");
  431.         mainPanel.add(searchBtn, "cell 4 3");
  432.  
  433.         // Consultation Type
  434.         JLabel consultationTypeLabel = new JLabel("Consultation Type");
  435.         mainPanel.add(consultationTypeLabel, "flowx,cell 3 4,aligny top");
  436.  
  437.         // Violation type with label and custom field
  438.         JLabel violationLabel = new JLabel("Violation Type: ");
  439.         violationLabel.setFont(new Font("SansSerif", Font.BOLD, 12));
  440.         mainPanel.add(violationLabel, "cell 1 5");
  441.  
  442.         // Create a panel to hold both the combo box and custom field with proper layout
  443.         JPanel violationPanel = new JPanel(new MigLayout("insets 0", "[][grow]", "[]"));
  444.         violationPanel.add(violationField, "cell 0 0");
  445.  
  446.         // Add custom violation field with label
  447.         JLabel otherLabel = new JLabel("Other:");
  448.         otherLabel.setVisible(false);
  449.         violationPanel.add(otherLabel, "cell 1 0");
  450.  
  451.         // Setup custom violation field
  452.         customViolationField = new JTextField(20);
  453.         customViolationField.setVisible(false);
  454.         violationPanel.add(customViolationField, "cell 1 0, growx");
  455.  
  456.         // Add listener to show/hide the "Other:" label and field
  457.         violationField.addActionListener(e -> {
  458.             String selected = (String) violationField.getSelectedItem();
  459.             boolean isOthers = "Others".equals(selected);
  460.             otherLabel.setVisible(isOthers);
  461.             customViolationField.setVisible(isOthers);
  462.             customViolationField.setEnabled(isOthers);
  463.             violationPanel.revalidate();
  464.             violationPanel.repaint();
  465.         });
  466.  
  467.         mainPanel.add(violationPanel, "cell 1 5 2 1, growx");
  468.  
  469.         // Participant Table
  470.         participantTable = new JTable(participantTableModel);
  471.         participantTable.setPreferredScrollableViewportSize(new Dimension(400, 100));
  472.         participantTable.getColumnModel().removeColumn(participantTable.getColumnModel().getColumn(4));
  473.         JScrollPane tableScrollPane = new JScrollPane(participantTable);
  474.         tableScrollPane.setBorder(BorderFactory.createTitledBorder("Participant Table")); // pane
  475.  
  476.         panel_1 = new JPanel();
  477.         panel_1.setLayout(new BorderLayout()); // Use BorderLayout for better control
  478.         panel_1.add(tableScrollPane, BorderLayout.CENTER); // Add the scroll pane to the panel
  479.         mainPanel.add(panel_1, "cell 1 6,grow"); // Adjust the cell position to align with the participant panel
  480.  
  481.         // Setup listener for participant table actions
  482.         setupParticipantTableListener();
  483.  
  484.         panel = new JPanel();
  485.         mainPanel.add(panel, "cell 3 6 2 1,grow");
  486.         panel.setLayout(new MigLayout("", "[][grow]", "[grow]"));
  487.  
  488.         // Notes
  489.         JLabel notesLabel = new JLabel("Notes: ");
  490.         panel.add(notesLabel, "cell 0 0,aligny top");
  491.         notesArea = new JTextArea(4, 20);
  492.         JScrollPane notesScrollPane = new JScrollPane(notesArea);
  493.         panel.add(notesScrollPane, "cell 1 0,grow");
  494.  
  495.         // Session Summary
  496.         JLabel summaryLabel = new JLabel("Summary: ");
  497.         summaryLabel.setFont(new Font("Segoe UI", Font.BOLD, 13));
  498.         mainPanel.add(summaryLabel, "cell 1 7 4 1,alignx left,aligny bottom");
  499.         JScrollPane summaryScrollPane = new JScrollPane(sessionSummaryArea);
  500.         mainPanel.add(summaryScrollPane, "cell 1 8 4 1,grow");
  501.  
  502.         printButton = new JButton("PRINT");
  503.         printButton.setBackground(new Color(70, 130, 180));
  504.         printButton.setForeground(Color.WHITE);
  505.         printButton.setFocusPainted(false);
  506.         printButton.addActionListener(e -> printSessionDetails());
  507.  
  508.         // Replace JComboBox with JTextField for Recorded By
  509.         mainPanel.remove(recordedByField);
  510.         JLabel recordedByLabel = new JLabel("Recorded By:");
  511.         recordedByLabel.setFont(new Font("SansSerif", Font.BOLD, 12));
  512.         mainPanel.add(recordedByLabel, "flowx,cell 3 9");
  513.         mainPanel.add(recordedByField, "cell 3 9,growx");
  514.  
  515.         // Buttons
  516.         mainPanel.add(printButton, "flowx,cell 4 9,growx");
  517.         mainPanel.add(saveButton, "cell 4 9,growx");
  518.  
  519.         consultationTypeComboBox = new JComboBox<>(new String[] { "Academic Consultation", "Career Guidance",
  520.                 "Personal Consultation", "Behavioral Consultation", "Group Consultation" });
  521.         mainPanel.add(consultationTypeComboBox, "cell 3 4,growx,aligny top");
  522.  
  523.         appointmentTypeComboBox = new JComboBox<>(new String[] { "Walk-in", "Scheduled" });
  524.         mainPanel.add(appointmentTypeComboBox, "cell 3 3,growx");
  525.  
  526.         searchBtn.addActionListener(e -> openAppointmentSearchDialog());
  527.     }
  528.  
  529.     private void printSessionDetails() {
  530.         PrinterJob printerJob = PrinterJob.getPrinterJob();
  531.         printerJob.setPrintable(this);
  532.         if (printerJob.printDialog()) {
  533.             try {
  534.                 printerJob.print();
  535.             } catch (PrinterException e) {
  536.                 JOptionPane.showMessageDialog(this, "Printing Error: " + e.getMessage(), "Error",
  537.                         JOptionPane.ERROR_MESSAGE);
  538.             }
  539.         }
  540.     }
  541.  
  542.     @Override
  543.     public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {
  544.         if (pageIndex > 0) {
  545.             return NO_SUCH_PAGE;
  546.         }
  547.  
  548.         // Calculate printable area
  549.         double width = pf.getImageableWidth();
  550.         double height = pf.getImageableHeight();
  551.  
  552.         Graphics2D g2d = (Graphics2D) g;
  553.         g2d.translate(pf.getImageableX(), pf.getImageableY());
  554.  
  555.         // Scale to fit page
  556.         double scaleX = width / getWidth();
  557.         double scaleY = height / getHeight();
  558.         double scale = Math.min(scaleX, scaleY);
  559.         g2d.scale(scale, scale);
  560.  
  561.         // Print the component
  562.         printAll(g2d);
  563.  
  564.         return PAGE_EXISTS;
  565.     }
  566.  
  567.     // Add this method to properly handle modal dialog disposal
  568.     private void closeDialog() {
  569.         Window window = SwingUtilities.getWindowAncestor(this);
  570.         if (window instanceof JDialog) {
  571.             ((JDialog) window).dispose();
  572.         }
  573.     }
  574.  
  575.     private void showParticipantDetails(int id) {
  576.         Map<String, String> details = participantDetails.get(id);
  577.  
  578.         if (details == null) {
  579.             JOptionPane.showMessageDialog(this, "Participant details not found", "Error", JOptionPane.ERROR_MESSAGE);
  580.             return;
  581.         }
  582.  
  583.         JFrame detailFrame = new JFrame("Participant Details");
  584.         detailFrame.setSize(300, 200);
  585.         detailFrame.setLocationRelativeTo(this);
  586.  
  587.         JPanel detailsPanel = new JPanel();
  588.         detailsPanel.setLayout(new GridLayout(0, 2, 10, 10));
  589.         detailsPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
  590.  
  591.         detailsPanel.add(new JLabel("Full Name:"));
  592.         detailsPanel.add(new JLabel(details.get("fullName")));
  593.         detailsPanel.add(new JLabel("Contact Number:"));
  594.         detailsPanel.add(new JLabel(details.get("contact")));
  595.         detailsPanel.add(new JLabel("Email:"));
  596.         detailsPanel.add(new JLabel(details.get("email")));
  597.         detailsPanel.add(new JLabel("Type:"));
  598.         detailsPanel.add(new JLabel(details.get("type")));
  599.  
  600.         JButton closeButton = new JButton("Close");
  601.         closeButton.addActionListener(e -> detailFrame.dispose());
  602.  
  603.         JPanel buttonPanel = new JPanel();
  604.         buttonPanel.add(closeButton);
  605.  
  606.         detailFrame.getContentPane().setLayout(new BorderLayout());
  607.         detailFrame.getContentPane().add(detailsPanel, BorderLayout.CENTER);
  608.         detailFrame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
  609.  
  610.         detailFrame.setVisible(true);
  611.     }
  612.  
  613.     private void populateRecordedByField() {
  614.         try {
  615.             if (Main.formManager != null && Main.formManager.getCounselorObject() != null) {
  616.                 String counselorName = Main.formManager.getCounselorObject().getFirstName() + " "
  617.                         + Main.formManager.getCounselorObject().getMiddleName() + " "
  618.                         + Main.formManager.getCounselorObject().getLastName();
  619.                 if (counselorName != null && !counselorName.isEmpty()) {
  620.                     recordedByField.setText(counselorName);
  621.                 }
  622.             } else {
  623.                 System.out.println("No counselor logged in. Skipping population of 'Recorded By' field.");
  624.             }
  625.         } catch (Exception e) {
  626.             JOptionPane.showMessageDialog(this, "Error retrieving counselor information: " + e.getMessage(), "Error",
  627.                     JOptionPane.ERROR_MESSAGE);
  628.             e.printStackTrace();
  629.         }
  630.     }
  631.  
  632.     private void openAppointmentSearchDialog() {
  633.         if (ModalDialog.isIdExist("search_appointment")) {
  634.             return;
  635.         }
  636.  
  637.         try {
  638.             AppointmentSearchPanel searchPanel = new AppointmentSearchPanel(connect);
  639.  
  640.             // Configure default modal options to match TestModal
  641.             ModalDialog.getDefaultOption().setOpacity(0f) // Transparent background
  642.                     .setAnimationOnClose(false) // No close animation
  643.                     .getBorderOption().setBorderWidth(0.5f) // Thin border
  644.                     .setShadow(raven.modal.option.BorderOption.Shadow.MEDIUM); // Medium shadow
  645.  
  646.             // Show the modal dialog
  647.             ModalDialog.showModal(this,
  648.                     new SimpleModalBorder(searchPanel, "Search Appointment",
  649.                             new SimpleModalBorder.Option[] {
  650.                                     new SimpleModalBorder.Option("Select", SimpleModalBorder.YES_OPTION),
  651.                                     new SimpleModalBorder.Option("Cancel", SimpleModalBorder.NO_OPTION) },
  652.                             (controller, action) -> {
  653.                                 if (action == SimpleModalBorder.YES_OPTION) {
  654.                                     Integer selectedId = searchPanel.getSelectedAppointmentId();
  655.                                     if (selectedId != null) {
  656.                                         String consultationType = searchPanel.getSelectedConsultationType();
  657.                                         appointmentTypeComboBox.setSelectedItem("From Appointment");
  658.                                         consultationTypeComboBox.setSelectedItem(consultationType);
  659.                                         selectedAppointmentId = selectedId;
  660.                                         populateParticipantsFromAppointment(selectedId);
  661.                                         controller.close();
  662.                                     } else {
  663.                                         JOptionPane.showMessageDialog(this, "Please select an appointment.", "Warning",
  664.                                                 JOptionPane.WARNING_MESSAGE);
  665.                                     }
  666.                                 } else if (action == SimpleModalBorder.NO_OPTION) {
  667.                                     controller.close();
  668.                                 }
  669.                             }),
  670.                     "search_appointment");
  671.  
  672.             // Set size
  673.             ModalDialog.getDefaultOption().getLayoutOption().setSize(800, 500);
  674.  
  675.         } catch (Exception e) {
  676.             e.printStackTrace();
  677.             JOptionPane.showMessageDialog(this, "Error opening appointment search: " + e.getMessage(), "Error",
  678.                     JOptionPane.ERROR_MESSAGE);
  679.         }
  680.     }
  681.  
  682.     private void populateParticipantsFromAppointment(int appointmentId) {
  683.         try {
  684.             AppointmentDAO appointmentDAO = new AppointmentDAO(connect);
  685.             Appointment appointment = appointmentDAO.getAppointmentById(appointmentId);
  686.  
  687.             if (appointment != null) {
  688.                 participantTableModel.setRowCount(0); // Clear existing participants
  689.  
  690.                 if (appointment.getParticipants() != null) {
  691.                     for (Participants participant : appointment.getParticipants()) {
  692.                         // Store participant details with actual ID
  693.                         Map<String, String> details = new HashMap<>();
  694.                         details.put("firstName", participant.getParticipantFirstName());
  695.                         details.put("lastName", participant.getParticipantLastName());
  696.                         details.put("fullName",
  697.                                 participant.getParticipantFirstName() + " " + participant.getParticipantLastName());
  698.                         details.put("type", participant.getParticipantType());
  699.                         details.put("contact", participant.getContactNumber());
  700.                         details.put("sex", participant.getSex());
  701.                         participantDetails.put(participant.getParticipantId(), details);
  702.  
  703.                         // Add to table with row number and actual ID
  704.                         int rowNumber = participantTableModel.getRowCount() + 1;
  705.                         participantTableModel.addRow(new Object[] { rowNumber, details.get("fullName"),
  706.                                 participant.getParticipantType(), "View | Remove", participant.getParticipantId() });
  707.                     }
  708.                 }
  709.             }
  710.         } catch (Exception e) {
  711.             JOptionPane.showMessageDialog(this, "Error populating participants: " + e.getMessage(), "Error",
  712.                     JOptionPane.ERROR_MESSAGE);
  713.         }
  714.     }
  715.  
  716.     private void saveSessionToDatabase() {
  717.         try {
  718.             int guidanceCounselorId;
  719.             if (Main.formManager != null && Main.formManager.getCounselorObject() != null) {
  720.                 guidanceCounselorId = Main.formManager.getCounselorObject().getGuidanceCounselorId();
  721.             } else {
  722.                 JOptionPane.showMessageDialog(this, "No guidance counselor is currently logged in.", "Error",
  723.                         JOptionPane.ERROR_MESSAGE);
  724.                 return;
  725.             }
  726.  
  727.             // First create the session without violation records
  728.             String appointmentType = (String) appointmentTypeComboBox.getSelectedItem();
  729.             String consultationType = (String) consultationTypeComboBox.getSelectedItem();
  730.             String violation = (String) violationField.getSelectedItem();
  731.             String notes = notesArea.getText();
  732.  
  733.             Integer appointmentId = "Walk-in".equals(appointmentType) ? null : selectedAppointmentId;
  734.  
  735.             String violationText = "Others".equals(violation) ? customViolationField.getText().trim() : violation;
  736.  
  737.             // Validate custom violation text
  738.             if ("Others".equals(violation) && (violationText == null || violationText.trim().isEmpty())) {
  739.                 JOptionPane.showMessageDialog(this,
  740.                         "Please enter a custom violation type.",
  741.                         "Missing Information",
  742.                         JOptionPane.WARNING_MESSAGE);
  743.                 return;
  744.             }
  745.  
  746.             Sessions session = new Sessions(0, appointmentId, guidanceCounselorId, null, appointmentType,
  747.                     consultationType, new java.sql.Timestamp(System.currentTimeMillis()), notes, "Active",
  748.                     new java.sql.Timestamp(System.currentTimeMillis()));
  749.  
  750.             SessionsDAO sessionsDAO = new SessionsDAO(connect);
  751.             int sessionId = sessionsDAO.addSession(session);
  752.  
  753.             if (sessionId > 0) {
  754.                 ParticipantsDAO participantsDAO = new ParticipantsDAO(connect);
  755.                 // Map to track temporary IDs to real database IDs
  756.                 Map<Integer, Integer> idMapping = new HashMap<>();
  757.  
  758.                 // Process all participants in the table
  759.                 for (int i = 0; i < participantTableModel.getRowCount(); i++) {
  760.                     int id = (int) participantTableModel.getValueAt(i, 4); // Get ID from hidden column
  761.  
  762.                     if (id < 0) {
  763.                         // New participant with temporary ID
  764.                         Participants participant = pendingParticipants.get(id);
  765.                         int realId = participantsDAO.createParticipant(participant); // Save to DB, get actual ID
  766.                         sessionsDAO.addParticipantToSession(sessionId, realId);
  767.                         idMapping.put(id, realId); // Store mapping from temp ID to real ID
  768.                     } else {
  769.                         // Existing participant with actual ID
  770.                         sessionsDAO.addParticipantToSession(sessionId, id);
  771.                         idMapping.put(id, id); // Map ID to itself for consistency
  772.                     }
  773.                 }
  774.  
  775.                 // NOW create violation records if there's a violation, using real participant
  776.                 // IDs
  777.                 if (violation != null && !violation.equals("-- Select Violation --")) {
  778.                     ViolationCRUD violationCRUD = new ViolationCRUD(connect);
  779.  
  780.                     // For each participant, create a violation record using real IDs
  781.                     for (int i = 0; i < participantTableModel.getRowCount(); i++) {
  782.                         int tempId = (int) participantTableModel.getValueAt(i, 4);
  783.                         int realParticipantId = idMapping.get(tempId); // Get the real ID from our mapping
  784.  
  785.                         // Create violation record with real participant ID
  786.                         boolean success = violationCRUD.addViolation(
  787.                                 realParticipantId,
  788.                                 violationText, // Use custom text if "Others" is selected
  789.                                 violationText, // Use custom text as description
  790.                                 sessionSummaryArea.getText(), // Use session summary as anecdotal record
  791.                                 notesArea.getText(), // Use notes as reinforcement
  792.                                 "Active",
  793.                                 new java.sql.Timestamp(System.currentTimeMillis()));
  794.  
  795.                         if (!success) {
  796.                             throw new Exception(
  797.                                     "Failed to save violation record for participant ID: " + realParticipantId);
  798.                         }
  799.                     }
  800.                 }
  801.  
  802.                 JOptionPane.showMessageDialog(this, "Session and participants saved successfully!", "Success",
  803.                         JOptionPane.INFORMATION_MESSAGE);
  804.  
  805.                 // Refresh violation records if they exist in the system
  806.                 refreshViolationRecords();
  807.  
  808.                 if (saveCallback != null) {
  809.                     saveCallback.run();
  810.                 }
  811.  
  812.                 clearFields();
  813.             } else {
  814.                 JOptionPane.showMessageDialog(this, "Failed to save session.", "Error", JOptionPane.ERROR_MESSAGE);
  815.             }
  816.         } catch (Exception e) {
  817.             JOptionPane.showMessageDialog(this, "Error saving session: " + e.getMessage(), "Error",
  818.                     JOptionPane.ERROR_MESSAGE);
  819.             e.printStackTrace();
  820.         }
  821.     }
  822.  
  823.     private void refreshViolationRecords() {
  824.         // Find and refresh any open violation record forms
  825.         if (Main.formManager != null) {
  826.             Form[] forms = FormManager.getForms();
  827.             for (Form form : forms) {
  828.                 if (form instanceof Violation_Record) {
  829.                     ((Violation_Record) form).refreshViolations();
  830.                 }
  831.             }
  832.         }
  833.     }
  834.  
  835.     public void populateFromAppointment(Appointment appointment) {
  836.         if (appointment != null) {
  837.             // Set appointment type and ID
  838.             appointmentTypeComboBox.setSelectedItem("Scheduled");
  839.             selectedAppointmentId = appointment.getAppointmentId();
  840.  
  841.             // Set consultation type
  842.             consultationTypeComboBox.setSelectedItem(appointment.getConsultationType());
  843.  
  844.             // Populate participants
  845.             populateParticipantsFromAppointment(appointment.getAppointmentId());
  846.  
  847.             // Set date and time if available
  848.             if (appointment.getAppointmentDateTime() != null) {
  849.                 java.time.LocalDateTime dateTime = appointment.getAppointmentDateTime().toLocalDateTime();
  850.                 sessionDatePicker.setSelectedDate(dateTime.toLocalDate());
  851.                 sessionTimePicker.setSelectedTime(dateTime.toLocalTime());
  852.             }
  853.  
  854.             // If there are notes, populate them
  855.             if (appointment.getAppointmentNotes() != null) {
  856.                 notesArea.setText(appointment.getAppointmentNotes());
  857.             }
  858.         }
  859.     }
  860. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement