Upgrade this code as much as possible and revise add as many features as possible, its a gui for a laser cutting system. import sys
import threading
import time
import os
import json
import logging
import datetime
import shutil
import subprocess
from PyQt6 import QtCore, QtWidgets, QtGui
from PyQt6.QtWidgets import (
    QLabel, QLineEdit, QPushButton, QVBoxLayout, QWidget, QFileDialog,
    QHBoxLayout, QComboBox, QMessageBox, QProgressBar, QTabWidget, QTableWidget,
    QTableWidgetItem, QGroupBox, QTextEdit, QAction, QMenu, QSystemTrayIcon,
    QGridLayout, QListWidget, QSlider, QSpinBox, QCheckBox, QRadioButton,
    QDateTimeEdit, QCalendarWidget, QDial, QStackedWidget, QTreeWidget,
    QTreeWidgetItem, QSplitter, QFrame, QDialog, QFormLayout, QPlainTextEdit,
    QStatusBar, QToolBar, QToolBox, QScrollArea
)
from PyQt6.QtCore import Qt, pyqtSignal, QTimer, QSize
from PyQt6.QtGui import QIcon, QPixmap, QFont, QActionGroup

# Set up logging
logging.basicConfig(filename="laser_cutter_debug.log",
                    filemode='a',
                    format='%(asctime)s - %(levelname)s - %(message)s',
                    level=logging.DEBUG)

class LaserCutterGUI(QWidget):
    # Signals for thread-safe UI updates
    progress_update = pyqtSignal(int)
    status_update = pyqtSignal(str)
    log_update = pyqtSignal(str)
    job_update = pyqtSignal(dict)
    sensor_update = pyqtSignal(dict)

    def __init__(self):
        super().__init__()
        self.settings_file = "laser_settings.json"
        self.job_history_file = "job_history.json"
        self.sensor_data_file = "sensor_data.json"
        self.profile_directory = "profiles"
        self.gcode_directory = "gcode"
        self.design_directory = "designs"
        self.logs_directory = "logs"
        self.setup_directories()
        self.initUI()
        self.load_job_history()
        self.load_sensor_data()
        self.init_tray()
        self.init_logging()
        self.monitor_system()
        self.monitor_sensors()

    def setup_directories(self):
        """Create necessary directories if they do not exist."""
        directories = [
            self.profile_directory,
            self.gcode_directory,
            self.design_directory,
            self.logs_directory
        ]
        for dir in directories:
            if not os.path.exists(dir):
                os.makedirs(dir)
                logging.info(f"Created directory: {dir}")

    def initUI(self):
        """Initialize the main user interface."""
        try:
            # Main layout with tabs
            main_layout = QVBoxLayout()
            self.tabs = QTabWidget()
            main_layout.addWidget(self.tabs)

            # Initialize different tabs
            self.control_tab = QWidget()
            self.settings_tab = QWidget()
            self.history_tab = QWidget()
            self.logs_tab = QWidget()
            self.analytics_tab = QWidget()
            self.tools_tab = QWidget()
            self.help_tab = QWidget()

            # Add tabs to the tab widget
            self.tabs.addTab(self.control_tab, "Control Panel")
            self.tabs.addTab(self.settings_tab, "Settings")
            self.tabs.addTab(self.history_tab, "Job History")
            self.tabs.addTab(self.logs_tab, "Logs")
            self.tabs.addTab(self.analytics_tab, "Analytics")
            self.tabs.addTab(self.tools_tab, "Tools")
            self.tabs.addTab(self.help_tab, "Help")

            # Setup each tab
            self.setup_control_tab()
            self.setup_settings_tab()
            self.setup_history_tab()
            self.setup_logs_tab()
            self.setup_analytics_tab()
            self.setup_tools_tab()
            self.setup_help_tab()

            # Set the main layout
            self.setLayout(main_layout)
            self.setWindowTitle("Advanced Laser Cutter Control Panel")
            self.setWindowIcon(QIcon("laser_icon.png"))
            self.resize(1200, 800)

            logging.info("UI initialized successfully.")
        except Exception as e:
            logging.error(f"Error initializing UI: {e}")
            QMessageBox.critical(self, "Initialization Error", f"Failed to initialize UI:\n{e}")

    def setup_control_tab(self):
        """Setup the Control Panel tab."""
        try:
            control_layout = QVBoxLayout()

            # Material Settings Group
            material_group = QGroupBox("Material Settings")
            material_layout = QGridLayout()

            self.material_label = QLabel('Material Type:')
            self.material_combo = QComboBox()
            self.material_combo.addItems(["Wood", "Acrylic", "Metal", "Glass", "Leather", "Paper", "Fabric", "Plastic", "Stone", "Rubber"])
            self.material_combo.currentTextChanged.connect(self.update_material_settings)

            self.thickness_label = QLabel('Thickness (mm):')
            self.thickness_input = QLineEdit()
            self.thickness_input.setPlaceholderText("e.g. 2.5")
            self.thickness_input.setValidator(QtGui.QDoubleValidator(0.1, 100.0, 2))
            self.thickness_input.textChanged.connect(self.calculate_settings)

            self.quality_label = QLabel('Quality:')
            self.quality_combo = QComboBox()
            self.quality_combo.addItems(["Draft", "Normal", "High Quality", "Ultra"])
            self.quality_combo.currentTextChanged.connect(self.calculate_settings)

            self.color_label = QLabel('Color:')
            self.color_button = QPushButton('Select Color')
            self.color_button.clicked.connect(self.select_material_color)
            self.selected_color = QColor(255, 0, 0)  # Default Red

            material_layout.addWidget(self.material_label, 0, 0)
            material_layout.addWidget(self.material_combo, 0, 1)
            material_layout.addWidget(self.thickness_label, 1, 0)
            material_layout.addWidget(self.thickness_input, 1, 1)
            material_layout.addWidget(self.quality_label, 2, 0)
            material_layout.addWidget(self.quality_combo, 2, 1)
            material_layout.addWidget(self.color_label, 3, 0)
            material_layout.addWidget(self.color_button, 3, 1)
            material_group.setLayout(material_layout)

            # Laser Settings Group
            laser_group = QGroupBox("Laser Settings")
            laser_layout = QGridLayout()

            self.power_label = QLabel('Power (%):')
            self.power_input = QLineEdit()
            self.power_input.setValidator(QtGui.QIntValidator(0, 100))
            self.power_input.setText("60")

            self.speed_label = QLabel('Speed (mm/s):')
            self.speed_input = QLineEdit()
            self.speed_input.setValidator(QtGui.QDoubleValidator(0.1, 1000.0, 2))
            self.speed_input.setText("25")

            self.focal_height_label = QLabel('Focal Height (mm):')
            self.focal_height_input = QLineEdit()
            self.focal_height_input.setValidator(QtGui.QDoubleValidator(0.1, 100.0, 2))
            self.focal_height_input.setText("6.25")

            self.passes_label = QLabel('Number of Passes:')
            self.passes_input = QSpinBox()
            self.passes_input.setRange(1, 10)
            self.passes_input.setValue(1)

            self.air_assist_label = QLabel('Air Assist (%):')
            self.air_assist_input = QLineEdit()
            self.air_assist_input.setValidator(QtGui.QDoubleValidator(0.0, 100.0, 2))
            self.air_assist_input.setText("50")

            laser_layout.addWidget(self.power_label, 0, 0)
            laser_layout.addWidget(self.power_input, 0, 1)
            laser_layout.addWidget(self.speed_label, 1, 0)
            laser_layout.addWidget(self.speed_input, 1, 1)
            laser_layout.addWidget(self.focal_height_label, 2, 0)
            laser_layout.addWidget(self.focal_height_input, 2, 1)
            laser_layout.addWidget(self.passes_label, 3, 0)
            laser_layout.addWidget(self.passes_input, 3, 1)
            laser_layout.addWidget(self.air_assist_label, 4, 0)
            laser_layout.addWidget(self.air_assist_input, 4, 1)
            laser_group.setLayout(laser_layout)

            # Design Management Group
            design_group = QGroupBox("Design Management")
            design_layout = QVBoxLayout()

            self.import_button = QPushButton('Import Design')
            self.import_button.setIcon(QIcon.fromTheme("document-open"))
            self.import_button.clicked.connect(self.import_design)

            self.export_button = QPushButton('Export Design')
            self.export_button.setIcon(QIcon.fromTheme("document-save"))
            self.export_button.clicked.connect(self.export_design)

            self.clear_design_button = QPushButton('Clear Design')
            self.clear_design_button.setIcon(QIcon.fromTheme("edit-clear"))
            self.clear_design_button.clicked.connect(self.clear_design)

            design_buttons_layout = QHBoxLayout()
            design_buttons_layout.addWidget(self.import_button)
            design_buttons_layout.addWidget(self.export_button)
            design_buttons_layout.addWidget(self.clear_design_button)
            design_layout.addLayout(design_buttons_layout)

            # Design Preview
            self.design_label = QLabel('Design Preview:')
            self.design_display = QLabel()
            self.design_display.setFixedSize(500, 500)
            self.design_display.setFrameShape(QLabel.Shape.Box)
            self.design_display.setAlignment(Qt.AlignmentFlag.AlignCenter)
            self.design_display.setStyleSheet("background-color: #f0f0f0;")
            design_layout.addWidget(self.design_label)
            design_layout.addWidget(self.design_display)
            design_group.setLayout(design_layout)

            # Job Controls Group
            job_controls_group = QGroupBox("Job Controls")
            job_controls_layout = QHBoxLayout()

            self.start_button = QPushButton('Start Job')
            self.start_button.setIcon(QIcon.fromTheme("media-playback-start"))
            self.start_button.clicked.connect(self.start_job)

            self.pause_button = QPushButton('Pause Job')
            self.pause_button.setIcon(QIcon.fromTheme("media-playback-pause"))
            self.pause_button.setEnabled(False)
            self.pause_button.clicked.connect(self.pause_job)

            self.stop_button = QPushButton('Stop Job')
            self.stop_button.setIcon(QIcon.fromTheme("process-stop"))
            self.stop_button.setEnabled(False)
            self.stop_button.clicked.connect(self.stop_job)

            self.cancel_button = QPushButton('Cancel Job')
            self.cancel_button.setIcon(QIcon.fromTheme("edit-delete"))
            self.cancel_button.setEnabled(False)
            self.cancel_button.clicked.connect(self.cancel_job)

            job_controls_layout.addWidget(self.start_button)
            job_controls_layout.addWidget(self.pause_button)
            job_controls_layout.addWidget(self.stop_button)
            job_controls_layout.addWidget(self.cancel_button)
            job_controls_group.setLayout(job_controls_layout)

            # Progress and Status
            progress_status_layout = QVBoxLayout()
            self.progress_bar = QProgressBar()
            self.progress_bar.setValue(0)

            self.status_label = QLabel('Status: Idle')
            self.status_label.setFont(QFont("Arial", 12, QFont.Weight.Bold))

            progress_status_layout.addWidget(self.progress_bar)
            progress_status_layout.addWidget(self.status_label)

            # Add all groups to the control layout
            control_layout.addWidget(material_group)
            control_layout.addWidget(laser_group)
            control_layout.addWidget(design_group)
            control_layout.addWidget(job_controls_group)
            control_layout.addLayout(progress_status_layout)

            self.control_tab.setLayout(control_layout)
            logging.info("Control tab setup completed.")
        except Exception as e:
            logging.error(f"Error setting up Control tab: {e}")
            QMessageBox.critical(self, "Control Tab Error", f"Failed to setup Control tab:\n{e}")

    def setup_settings_tab(self):
        """Setup the Settings tab."""
        try:
            settings_layout = QVBoxLayout()

            # Connection Settings Group
            connection_group = QGroupBox("Connection Settings")
            connection_layout = QGridLayout()

            self.port_label = QLabel('Port:')
            self.port_input = QLineEdit()
            self.port_input.setPlaceholderText("/dev/ttyUSB0 or COM3")

            self.baudrate_label = QLabel('Baudrate:')
            self.baudrate_input = QLineEdit()
            self.baudrate_input.setPlaceholderText("9600")
            self.baudrate_input.setValidator(QtGui.QIntValidator(300, 115200))

            self.connect_button = QPushButton('Connect')
            self.connect_button.setIcon(QIcon.fromTheme("network-connect"))
            self.connect_button.clicked.connect(self.connect_laser)

            self.disconnect_button = QPushButton('Disconnect')
            self.disconnect_button.setIcon(QIcon.fromTheme("network-disconnect"))
            self.disconnect_button.setEnabled(False)
            self.disconnect_button.clicked.connect(self.disconnect_laser)

            connection_layout.addWidget(self.port_label, 0, 0)
            connection_layout.addWidget(self.port_input, 0, 1)
            connection_layout.addWidget(self.baudrate_label, 1, 0)
            connection_layout.addWidget(self.baudrate_input, 1, 1)
            connection_layout.addWidget(self.connect_button, 2, 0)
            connection_layout.addWidget(self.disconnect_button, 2, 1)
            connection_group.setLayout(connection_layout)

            # Profile Management Group
            profile_group = QGroupBox("Profile Management")
            profile_layout = QHBoxLayout()

            self.save_profile_button = QPushButton('Save Profile')
            self.save_profile_button.setIcon(QIcon.fromTheme("document-save"))
            self.save_profile_button.clicked.connect(self.save_profile)

            self.load_profile_button = QPushButton('Load Profile')
            self.load_profile_button.setIcon(QIcon.fromTheme("document-open"))
            self.load_profile_button.clicked.connect(self.load_profile)

            self.delete_profile_button = QPushButton('Delete Profile')
            self.delete_profile_button.setIcon(QIcon.fromTheme("edit-delete"))
            self.delete_profile_button.clicked.connect(self.delete_profile)

            profile_layout.addWidget(self.save_profile_button)
            profile_layout.addWidget(self.load_profile_button)
            profile_layout.addWidget(self.delete_profile_button)
            profile_group.setLayout(profile_layout)

            # Advanced Settings Group
            advanced_group = QGroupBox("Advanced Settings")
            advanced_layout = QGridLayout()

            self.gcode_checkbox = QCheckBox("Generate G-code")
            self.gcode_checkbox.setChecked(True)

            self.simulation_checkbox = QCheckBox("Enable Simulation Mode")
            self.simulation_checkbox.setChecked(False)

            self.auto_focus_checkbox = QCheckBox("Auto Focus Adjustment")
            self.auto_focus_checkbox.setChecked(True)

            self.cooling_fan_checkbox = QCheckBox("Enable Cooling Fan")
            self.cooling_fan_checkbox.setChecked(True)

            self.ventilation_checkbox = QCheckBox("Enable Ventilation System")
            self.ventilation_checkbox.setChecked(False)

            advanced_layout.addWidget(self.gcode_checkbox, 0, 0)
            advanced_layout.addWidget(self.simulation_checkbox, 0, 1)
            advanced_layout.addWidget(self.auto_focus_checkbox, 1, 0)
            advanced_layout.addWidget(self.cooling_fan_checkbox, 1, 1)
            advanced_layout.addWidget(self.ventilation_checkbox, 2, 0)
            advanced_group.setLayout(advanced_layout)

            # Backup and Restore Group
            backup_group = QGroupBox("Backup & Restore")
            backup_layout = QHBoxLayout()

            self.backup_button = QPushButton('Backup Settings')
            self.backup_button.setIcon(QIcon.fromTheme("document-save"))
            self.backup_button.clicked.connect(self.backup_settings)

            self.restore_button = QPushButton('Restore Settings')
            self.restore_button.setIcon(QIcon.fromTheme("document-open"))
            self.restore_button.clicked.connect(self.restore_settings)

            backup_layout.addWidget(self.backup_button)
            backup_layout.addWidget(self.restore_button)
            backup_group.setLayout(backup_layout)

            # Firmware Update Group
            firmware_group = QGroupBox("Firmware Update")
            firmware_layout = QHBoxLayout()

            self.update_firmware_button = QPushButton('Update Firmware')
            self.update_firmware_button.setIcon(QIcon.fromTheme("system-software-update"))
            self.update_firmware_button.clicked.connect(self.update_firmware)

            firmware_layout.addWidget(self.update_firmware_button)
            firmware_group.setLayout(firmware_layout)

            # Security Settings Group
            security_group = QGroupBox("Security Settings")
            security_layout = QHBoxLayout()

            self.enable_auth_checkbox = QCheckBox("Enable User Authentication")
            self.enable_auth_checkbox.setChecked(True)

            self.change_password_button = QPushButton('Change Password')
            self.change_password_button.setIcon(QIcon.fromTheme("preferences-system-user-password"))
            self.change_password_button.clicked.connect(self.change_password)

            security_layout.addWidget(self.enable_auth_checkbox)
            security_layout.addWidget(self.change_password_button)
            security_group.setLayout(security_layout)

            # Add all groups to settings layout
            settings_layout.addWidget(connection_group)
            settings_layout.addWidget(profile_group)
            settings_layout.addWidget(advanced_group)
            settings_layout.addWidget(backup_group)
            settings_layout.addWidget(firmware_group)
            settings_layout.addWidget(security_group)
            settings_layout.addStretch()

            self.settings_tab.setLayout(settings_layout)
            logging.info("Settings tab setup completed.")
        except Exception as e:
            logging.error(f"Error setting up Settings tab: {e}")
            QMessageBox.critical(self, "Settings Tab Error", f"Failed to setup Settings tab:\n{e}")

    def setup_history_tab(self):
        """Setup the Job History tab."""
        try:
            history_layout = QVBoxLayout()

            # Job History Table
            self.history_table = QTableWidget()
            self.history_table.setColumnCount(7)
            self.history_table.setHorizontalHeaderLabels(["Job ID", "Design", "Material", "Date", "Status", "Duration", "Actions"])
            self.history_table.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers)
            self.history_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows)
            self.history_table.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection)
            self.history_table.horizontalHeader().setStretchLastSection(True)

            history_layout.addWidget(self.history_table)

            # Search and Filter
            filter_layout = QHBoxLayout()
            self.search_input = QLineEdit()
            self.search_input.setPlaceholderText("Search by Design or Material")
            self.search_input.textChanged.connect(self.filter_history)

            self.filter_combo = QComboBox()
            self.filter_combo.addItems(["All", "Completed", "Running", "Paused", "Stopped", "Cancelled", "Error"])
            self.filter_combo.currentTextChanged.connect(self.filter_history)

            filter_layout.addWidget(QLabel("Search:"))
            filter_layout.addWidget(self.search_input)
            filter_layout.addWidget(QLabel("Filter by Status:"))
            filter_layout.addWidget(self.filter_combo)
            filter_layout.addStretch()

            history_layout.addLayout(filter_layout)

            # Export History Button
            self.export_history_button = QPushButton('Export History')
            self.export_history_button.setIcon(QIcon.fromTheme("document-save"))
            self.export_history_button.clicked.connect(self.export_job_history)
            history_layout.addWidget(self.export_history_button)

            self.history_tab.setLayout(history_layout)
            logging.info("History tab setup completed.")
        except Exception as e:
            logging.error(f"Error setting up History tab: {e}")
            QMessageBox.critical(self, "History Tab Error", f"Failed to setup History tab:\n{e}")

    def setup_logs_tab(self):
        """Setup the Logs tab."""
        try:
            logs_layout = QVBoxLayout()

            # Log Text Area
            self.log_text = QPlainTextEdit()
            self.log_text.setReadOnly(True)
            self.log_text.setFont(QFont("Courier", 10))
            logs_layout.addWidget(self.log_text)

            # Clear Logs Button
            self.clear_logs_button = QPushButton('Clear Logs')
            self.clear_logs_button.setIcon(QIcon.fromTheme("edit-clear"))
            self.clear_logs_button.clicked.connect(self.clear_logs)
            logs_layout.addWidget(self.clear_logs_button)

            self.logs_tab.setLayout(logs_layout)
            self.log_update.connect(self.append_log)
            logging.info("Logs tab setup completed.")
        except Exception as e:
            logging.error(f"Error setting up Logs tab: {e}")
            QMessageBox.critical(self, "Logs Tab Error", f"Failed to setup Logs tab:\n{e}")

    def setup_analytics_tab(self):
        """Setup the Analytics tab."""
        try:
            analytics_layout = QVBoxLayout()

            # Real-time Analytics Display
            real_time_group = QGroupBox("Real-time Analytics")
            real_time_layout = QVBoxLayout()

            self.realtime_graph = QLabel("Real-time Graph Placeholder")
            self.realtime_graph.setFixedSize(600, 400)
            self.realtime_graph.setFrameShape(QLabel.Shape.Box)
            real_time_layout.addWidget(self.realtime_graph)

            real_time_group.setLayout(real_time_layout)
            analytics_layout.addWidget(real_time_group)

            # Historical Data Charts
            historical_group = QGroupBox("Historical Data")
            historical_layout = QVBoxLayout()

            self.historical_graph = QLabel("Historical Data Graph Placeholder")
            self.historical_graph.setFixedSize(600, 400)
            self.historical_graph.setFrameShape(QLabel.Shape.Box)
            historical_layout.addWidget(self.historical_graph)

            historical_group.setLayout(historical_layout)
            analytics_layout.addWidget(historical_group)

            self.analytics_tab.setLayout(analytics_layout)
            logging.info("Analytics tab setup completed.")
        except Exception as e:
            logging.error(f"Error setting up Analytics tab: {e}")
            QMessageBox.critical(self, "Analytics Tab Error", f"Failed to setup Analytics tab:\n{e}")

    def setup_tools_tab(self):
        """Setup the Tools tab."""
        try:
            tools_layout = QVBoxLayout()

            # Calibration Tools Group
            calibration_group = QGroupBox("Calibration Tools")
            calibration_layout = QHBoxLayout()

            self.manual_calibrate_button = QPushButton('Manual Calibration')
            self.manual_calibrate_button.setIcon(QIcon.fromTheme("system-run"))
            self.manual_calibrate_button.clicked.connect(self.manual_calibration)

            self.auto_calibrate_button = QPushButton('Auto Calibration')
            self.auto_calibrate_button.setIcon(QIcon.fromTheme("system-run"))
            self.auto_calibrate_button.clicked.connect(self.auto_calibration)

            calibration_layout.addWidget(self.manual_calibrate_button)
            calibration_layout.addWidget(self.auto_calibrate_button)
            calibration_group.setLayout(calibration_layout)

            # Maintenance Tools Group
            maintenance_group = QGroupBox("Maintenance Tools")
            maintenance_layout = QHBoxLayout()

            self.clean_lenses_button = QPushButton('Clean Lenses')
            self.clean_lenses_button.setIcon(QIcon.fromTheme("applications-science"))
            self.clean_lenses_button.clicked.connect(self.clean_lenses)

            self.check_alignment_button = QPushButton('Check Alignment')
            self.check_alignment_button.setIcon(QIcon.fromTheme("preferences-desktop-display"))
            self.check_alignment_button.clicked.connect(self.check_alignment)

            maintenance_layout.addWidget(self.clean_lenses_button)
            maintenance_layout.addWidget(self.check_alignment_button)
            maintenance_group.setLayout(maintenance_layout)

            # Backup Tools Group
            backup_tool_group = QGroupBox("Backup Tools")
            backup_tool_layout = QHBoxLayout()

            self.backup_designs_button = QPushButton('Backup Designs')
            self.backup_designs_button.setIcon(QIcon.fromTheme("document-save"))
            self.backup_designs_button.clicked.connect(self.backup_designs)

            self.restore_designs_button = QPushButton('Restore Designs')
            self.restore_designs_button.setIcon(QIcon.fromTheme("document-open"))
            self.restore_designs_button.clicked.connect(self.restore_designs)

            backup_tool_layout.addWidget(self.backup_designs_button)
            backup_tool_layout.addWidget(self.restore_designs_button)
            backup_tool_group.setLayout(backup_tool_layout)

            # Diagnostic Tools Group
            diagnostic_group = QGroupBox("Diagnostic Tools")
            diagnostic_layout = QHBoxLayout()

            self.run_diagnostics_button = QPushButton('Run Diagnostics')
            self.run_diagnostics_button.setIcon(QIcon.fromTheme("system-run"))
            self.run_diagnostics_button.clicked.connect(self.run_diagnostics)

            self.view_logs_button = QPushButton('View Detailed Logs')
            self.view_logs_button.setIcon(QIcon.fromTheme("applications-utilities"))
            self.view_logs_button.clicked.connect(self.view_detailed_logs)

            diagnostic_layout.addWidget(self.run_diagnostics_button)
            diagnostic_layout.addWidget(self.view_logs_button)
            diagnostic_group.setLayout(diagnostic_layout)

            # Add all groups to tools layout
            tools_layout.addWidget(calibration_group)
            tools_layout.addWidget(maintenance_group)
            tools_layout.addWidget(backup_tool_group)
            tools_layout.addWidget(diagnostic_group)
            tools_layout.addStretch()

            self.tools_tab.setLayout(tools_layout)
            logging.info("Tools tab setup completed.")
        except Exception as e:
            logging.error(f"Error setting up Tools tab: {e}")
            QMessageBox.critical(self, "Tools Tab Error", f"Failed to setup Tools tab:\n{e}")

    def setup_help_tab(self):
        """Setup the Help tab."""
        try:
            help_layout = QVBoxLayout()

            # FAQ Section
            faq_group = QGroupBox("Frequently Asked Questions (FAQ)")
            faq_layout = QVBoxLayout()

            faq_text = QTextEdit()
            faq_text.setReadOnly(True)
            faq_text.setHtml("""
                <h2>Frequently Asked Questions</h2>
                <h3>1. How do I connect to the laser cutter?</h3>
                <p>Navigate to the <b>Settings</b> tab, enter the correct <b>Port</b> and <b>Baudrate</b>, then click <b>Connect</b>.</p>
                <h3>2. How can I import a design?</h3>
                <p>In the <b>Control Panel</b> tab, click on <b>Import Design</b> and select your design file.</p>
                <h3>3. What do the different quality settings mean?</h3>
                <p>The quality settings adjust the laser power and speed to balance between speed and precision of the cut.</p>
                <h3>4. How do I save my current settings?</h3>
                <p>Go to the <b>Settings</b> tab and use the <b>Save Profile</b> button to save your current configuration.</p>
                <h3>5. How to generate G-code?</h3>
                <p>Ensure the <b>Generate G-code</b> option is checked in the <b>Settings</b> tab before starting a job.</p>
                """)

            faq_layout.addWidget(faq_text)
            faq_group.setLayout(faq_layout)

            # Documentation Section
            documentation_group = QGroupBox("User Documentation")
            documentation_layout = QVBoxLayout()

            doc_text = QTextEdit()
            doc_text.setReadOnly(True)
            doc_text.setHtml("""
                <h2>User Documentation</h2>
                <p>For detailed user guides and troubleshooting, visit our <a href='https://yourdocumentationlink.com'>Documentation Page</a>.</p>
                """)

            documentation_layout.addWidget(doc_text)
            documentation_group.setLayout(documentation_layout)

            # Contact Support Section
            support_group = QGroupBox("Contact Support")
            support_layout = QVBoxLayout()

            support_text = QTextEdit()
            support_text.setReadOnly(True)
            support_text.setHtml("""
                <h2>Contact Support</h2>
                <p>If you encounter any issues or have questions, please reach out to our support team:</p>
                <ul>
                    <li>Email: <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS></li>
                    <li>Phone: +1 <PRESIDIO_ANONYMIZED_PHONE_NUMBER></li>
                    <li>Live Chat: Available 24/7 on our website.</li>
                </ul>
                """)

            support_layout.addWidget(support_text)
            support_group.setLayout(support_layout)

            # Add all sections to help layout
            help_layout.addWidget(faq_group)
            help_layout.addWidget(documentation_group)
            help_layout.addWidget(support_group)
            help_layout.addStretch()

            self.help_tab.setLayout(help_layout)
            logging.info("Help tab setup completed.")
        except Exception as e:
            logging.error(f"Error setting up Help tab: {e}")
            QMessageBox.critical(self, "Help Tab Error", f"Failed to setup Help tab:\n{e}")

    def init_tray(self):
        """Initialize the system tray icon and menu."""
        try:
            self.tray_icon = QSystemTrayIcon(QIcon("laser_icon.png"), self)
            tray_menu = QMenu()

            show_action = QAction("Show", self)
            show_action.triggered.connect(self.show)
            tray_menu.addAction(show_action)

            hide_action = QAction("Hide", self)
            hide_action.triggered.connect(self.hide)
            tray_menu.addAction(hide_action)

            exit_action = QAction("Exit", self)
            exit_action.triggered.connect(sys.exit)
            tray_menu.addAction(exit_action)

            self.tray_icon.setContextMenu(tray_menu)
            self.tray_icon.activated.connect(self.on_tray_icon_activated)
            self.tray_icon.show()
            logging.info("System tray initialized.")
        except Exception as e:
            logging.error(f"Error initializing system tray: {e}")

    def on_tray_icon_activated(self, reason):
        """Handle tray icon activation."""
        if reason == QSystemTrayIcon.ActivationReason.Trigger:
            if self.isVisible():
                self.hide()
            else:
                self.show()

    def init_logging(self):
        """Initialize logging for the Logs tab."""
        try:
            self.log_timer = QTimer()
            self.log_timer.timeout.connect(self.load_logs)
            self.log_timer.start(5000)  # Refresh logs every 5 seconds
            logging.info("Logging initialized.")
        except Exception as e:
            logging.error(f"Error initializing logging: {e}")

    def load_logs(self):
        """Load logs from the log file into the Logs tab."""
        try:
            if os.path.exists("laser_cutter_debug.log"):
                with open("laser_cutter_debug.log", 'r') as f:
                    logs = f.read()
                self.log_text.setPlainTex