// Sidebar toggle
const sidebarToggle = document.getElementById('sidebarToggle');
const sidebar = document.getElementById('sidebar');
const sidebarBackdrop = document.getElementById('sidebarBackdrop');

// ============ USER-SPECIFIC STORAGE HELPERS ============
// Helper functions to ensure all user data in localStorage is separated per user
function getUserId() {
    if (window.currentUserId) return window.currentUserId;
    try {
        const cachedUserId = sessionStorage.getItem('elogbook_current_user_id');
        return cachedUserId || 'guest';
    } catch (error) {
        return 'guest';
    }
}

function getUserSpecificStorageKey(baseKey) {
    const userId = getUserId();
    return `${baseKey}_user_${userId}`;
}

function setUserStorage(baseKey, value) {
    const key = getUserSpecificStorageKey(baseKey);
    try {
        localStorage.setItem(key, JSON.stringify(value));
    } catch (error) {
        console.error(`Error saving to localStorage: ${key}`, error);
    }
}

function getUserStorage(baseKey, defaultValue = null) {
    const key = getUserSpecificStorageKey(baseKey);
    try {
        const item = localStorage.getItem(key);
        return item ? JSON.parse(item) : defaultValue;
    } catch (error) {
        console.error(`Error reading from localStorage: ${key}`, error);
        return defaultValue;
    }
}

function removeUserStorage(baseKey) {
    const key = getUserSpecificStorageKey(baseKey);
    try {
        localStorage.removeItem(key);
    } catch (error) {
        console.error(`Error removing from localStorage: ${key}`, error);
    }
}

// Automatically scope localStorage data keys per user to prevent cross-account data mixing
(function setupUserScopedLocalStorage() {
    if (window.__userScopedLocalStorageInitialized) return;
    window.__userScopedLocalStorageInitialized = true;

    const rawGetItem = Storage.prototype.getItem;
    const rawSetItem = Storage.prototype.setItem;
    const rawRemoveItem = Storage.prototype.removeItem;

    function shouldScopeStorageKey(key) {
        if (typeof key !== 'string' || key.length === 0) return false;

        if (key.includes('_user_')) return false;

        if (key.startsWith('menu-') || key.startsWith('submenu-')) return false;

        return true;
    }

    function getScopedKey(key) {
        if (!shouldScopeStorageKey(key)) return key;
        return `${key}_user_${getUserId()}`;
    }

    Storage.prototype.getItem = function(key) {
        return rawGetItem.call(this, getScopedKey(key));
    };

    Storage.prototype.setItem = function(key, value) {
        return rawSetItem.call(this, getScopedKey(key), value);
    };

    Storage.prototype.removeItem = function(key) {
        return rawRemoveItem.call(this, getScopedKey(key));
    };
})();

// Profile dropdown toggle
const userProfile = document.querySelector('.user-profile');
const profileDropdown = document.querySelector('.dropdown-menu');

if (userProfile && profileDropdown) {
    userProfile.addEventListener('click', function(event) {
        const clickedLink = event.target.closest('.dropdown-menu a');
        if (clickedLink) {
            userProfile.classList.remove('open');
            profileDropdown.classList.remove('active');
            return;
        }

        event.preventDefault();
        event.stopPropagation();
        const isOpen = userProfile.classList.toggle('open');
        profileDropdown.classList.toggle('active', isOpen);
    });

    document.addEventListener('click', function(event) {
        if (!userProfile.contains(event.target)) {
            userProfile.classList.remove('open');
            profileDropdown.classList.remove('active');
        }
    });

    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            userProfile.classList.remove('open');
            profileDropdown.classList.remove('active');
        }
    });
}

if (sidebarToggle) {
    sidebarToggle.addEventListener('click', function(e) {
        e.stopPropagation();
        toggleSidebar();
    });
}

// Toggle sidebar function
function toggleSidebar() {
    const isOpening = !sidebar.classList.contains('active');
    sidebar.classList.toggle('active');
    if (sidebarToggle) sidebarToggle.classList.toggle('active');
    if (sidebarBackdrop) {
        sidebarBackdrop.classList.toggle('active');
    }
    // Lock body scroll on mobile when sidebar is open
    if (isOpening) {
        document.body.classList.add('sidebar-open');
    } else {
        document.body.classList.remove('sidebar-open');
    }
}

// Close sidebar when clicking on menu links
const menuLinks = document.querySelectorAll('.menu-link');
menuLinks.forEach(link => {
    link.addEventListener('click', function() {
        closeSidebar();
    });
});

// Close sidebar function
function closeSidebar() {
    sidebar.classList.remove('active');
    if (sidebarToggle) sidebarToggle.classList.remove('active');
    if (sidebarBackdrop) {
        sidebarBackdrop.classList.remove('active');
    }
    document.body.classList.remove('sidebar-open');
}

// Close sidebar when clicking on backdrop
if (sidebarBackdrop) {
    sidebarBackdrop.addEventListener('click', function() {
        closeSidebar();
    });
}

// Close sidebar when clicking outside
document.addEventListener('click', function(event) {
    if (sidebar && sidebar.classList.contains('active')) {
        // Check if click is outside sidebar and hamburger
        if (!sidebar.contains(event.target) && (sidebarToggle && !sidebarToggle.contains(event.target))) {
            closeSidebar();
        }
    }
});

// Close sidebar on escape key
document.addEventListener('keydown', function(event) {
    if (event.key === 'Escape' && sidebar && sidebar.classList.contains('active')) {
        closeSidebar();
    }
});

// Menu Collapse/Expand Toggle
const menuToggles = document.querySelectorAll('.menu-toggle');
menuToggles.forEach(toggle => {
    toggle.addEventListener('click', function(e) {
        e.preventDefault();
        const targetId = this.getAttribute('data-target');
        const targetMenu = document.getElementById(targetId);
        
        if (targetMenu) {
            targetMenu.classList.toggle('collapsed');
            this.classList.toggle('collapsed');
            
            // Save state to localStorage
            const isCollapsed = targetMenu.classList.contains('collapsed');
            localStorage.setItem('menu-' + targetId, isCollapsed);
        }
    });
    
    // Restore state from localStorage on page load
    const targetId = toggle.getAttribute('data-target');
    const targetMenu = document.getElementById(targetId);
    const savedState = localStorage.getItem('menu-' + targetId);
    
    if (savedState === 'true') {
        targetMenu.classList.add('collapsed');
        toggle.classList.add('collapsed');
    }
});

// Submenu Collapse/Expand Toggle
const submenuToggles = document.querySelectorAll('.menu-toggle-sub');
submenuToggles.forEach(toggle => {
    toggle.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        const targetId = this.getAttribute('data-target');
        const targetSubmenu = document.getElementById(targetId);
        
        if (targetSubmenu) {
            targetSubmenu.classList.toggle('collapsed');
            this.classList.toggle('collapsed');
            
            // Save state to localStorage
            const isCollapsed = targetSubmenu.classList.contains('collapsed');
            localStorage.setItem('submenu-' + targetId, isCollapsed);
        }
    });
    
    // Restore state from localStorage on page load
    const targetId = toggle.getAttribute('data-target');
    const targetSubmenu = document.getElementById(targetId);
    const savedState = localStorage.getItem('submenu-' + targetId);
    
    if (savedState === 'true') {
        targetSubmenu.classList.add('collapsed');
        toggle.classList.add('collapsed');
    }
});

document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.menu-list, .submenu').forEach(list => {
        list.classList.remove('collapsed');
    });
    document.querySelectorAll('.menu-toggle, .menu-toggle-sub').forEach(toggle => {
        toggle.classList.remove('collapsed');
    });

    Object.keys(localStorage).forEach(key => {
        if (key.startsWith('menu-') || key.startsWith('submenu-')) {
            localStorage.removeItem(key);
        }
    });
});

// Modal functions
function openLogModal() {
    const modal = document.getElementById('logModal');
    if (modal) {
        modal.classList.add('active');
        const logDate = new Date();
        document.getElementById('logDate').valueAsDate = logDate;
    }
}

function closeLogModal() {
    const modal = document.getElementById('logModal');
    if (modal) {
        modal.classList.remove('active');
        document.getElementById('logForm').reset();
    }
}

// Close modal when clicking outside
window.addEventListener('click', function(event) {
    const modal = document.getElementById('logModal');
    if (modal && event.target === modal) {
        closeLogModal();
    }
});

// Add log button click
const addLogBtn = document.getElementById('addLogBtn');
if (addLogBtn) {
    addLogBtn.addEventListener('click', openLogModal);
}

// Navigation between sections
let currentActiveSectionId = null;  // Track currently active section

function showSection(sectionId) {
    const sections = document.querySelectorAll('.content-section');
    sections.forEach(section => section.style.display = 'none');

    const selectedSection = document.getElementById(sectionId);
    if (selectedSection) {
        selectedSection.style.display = 'block';
        currentActiveSectionId = sectionId;  // Store active section
        
        // Load data when specific sections are shown
        if (sectionId === 'settings' && typeof loadSettingsData === 'function') {
            loadSettingsData();
        }
        if (sectionId === 'trainee-logbooks' && typeof loadTraineeLogbooks === 'function') {
            loadTraineeLogbooks();
        }

        if (typeof updateGlobalSectionActionState === 'function') {
            updateGlobalSectionActionState();
        }
    }
}

let isGlobalEditMode = true;

function showGlobalActionMessage(message, isError = false) {
    const statusEl = document.getElementById('globalActionStatus');
    if (!statusEl) return;
    statusEl.textContent = message;
    statusEl.style.color = isError ? '#dc3545' : '#198754';
    statusEl.style.opacity = '1';

    setTimeout(() => {
        statusEl.style.opacity = '0.7';
    }, 2500);
}

function getActiveContentSection() {
    return document.querySelector('.content-section[style*="display: block"], .content-section:not([style*="display: none"])');
}

function applySectionViewMode(isEditable) {
    const activeSection = getActiveContentSection();
    if (!activeSection) return;

    const fields = activeSection.querySelectorAll('input, textarea, select');
    fields.forEach(field => {
        if (field.type === 'hidden') return;
        const tag = field.tagName.toLowerCase();
        if (tag === 'select') {
            field.disabled = !isEditable;
        } else {
            field.readOnly = !isEditable;
        }
    });

    const actionButtons = activeSection.querySelectorAll('button');
    actionButtons.forEach(btn => {
        const id = (btn.id || '').toLowerCase();
        const txt = (btn.textContent || '').toLowerCase();
        const isProtected = id.includes('save') || txt.includes('save') || txt.includes('simpan') || txt.includes('edit') || txt.includes('lihat');
        if (!isProtected) {
            btn.disabled = !isEditable;
        }
    });
}

// Mapping of section IDs to their save functions
const sectionSaveFunctionsMap = {
    'personal-details': ['savePersonalDetails'],
    'academic-tutors': ['saveAcademicTutorsData'],
    'certificate': ['saveCertificateData'],
    'discussion-assessment': ['saveDiscussionAssessmentData'],
    'academic-tasks': ['saveAcademicTasks'],
    'research-activities': ['saveResearchActivities'],
    'scientific-activities': ['saveScientificActivities'],
    'sertifikat': ['saveSertifikatData'],
    'laporan-progres': ['saveLaporanProgressData'],
    'cpl': ['saveCPLData'],
    'female-endocrinology': ['saveFemaleEndoData'],
    'ovary-pcos': ['saveOvaryPCOSData'],
    'subfertility-i': ['saveSubfertilityData'],
    'hormonal-contraception': ['saveHormonalContraData'],
    'early-pregnancy-problems': ['saveEarlyPregData'],
    'research': ['saveResearchData'],
    'subfertility-ii': ['saveSubfertilityII_Data'],
    'reprod-surgery-i': ['saveReprodSurgery_Data'],
    'metabolic-endocrinology': ['saveMetabolic_Data'],
    'paediatric-gynecology': ['savePaediatric_Data'],
    'art-i': ['saveART1_Data'],
    'art1-sem3': ['saveART1S3_Data'],
    'art2': ['saveART2_Data'],
    'menopause-pof': ['saveMenopause_Data'],
    'endometriosis': ['saveEndoData'],
    'reprod-surgery-iii': ['saveSurgeryIII_Data'],
    'seminar-workshop': [],
    'publikasi': [],
    'penelitian': [],
    'aktivitas-pembelajaran': []
};

function getGlobalSaveFunctionNames(sectionId = null) {
    if (sectionId && sectionSaveFunctionsMap[sectionId]) {
        return sectionSaveFunctionsMap[sectionId];
    }
    
    return [
        'savePersonalDetails', 'saveAcademicTutorsData', 'saveCertificateData', 'saveDiscussionAssessmentData',
        'saveAcademicTasks', 'saveResearchActivities', 'saveScientificActivities', 'saveSertifikatData',
        'saveLaporanProgressData', 'saveCPLData', 'saveFemaleEndoData', 'saveOvaryPCOSData',
        'saveSubfertilityData', 'saveHormonalContraData', 'saveEarlyPregData', 'saveResearchData',
        'saveSubfertilityII_Data', 'saveReprodSurgery_Data', 'saveMetabolic_Data', 'savePaediatric_Data',
        'saveART1_Data', 'saveART1S3_Data', 'saveART2_Data', 'saveMenopause_Data', 'saveEndoData', 'saveSurgeryIII_Data'
    ];
}

async function runGlobalSave() {
    let hasError = false;

    try {
        // Get section-specific save functions
        const functionNames = getGlobalSaveFunctionNames(currentActiveSectionId);
        
        // Check if current section has generic CRUD tables
        if (currentActiveSectionId === 'seminar-workshop') {
            await saveGenericCrudTable('seminarWorkshop');
        } else if (currentActiveSectionId === 'publikasi') {
            await saveGenericCrudTable('publikasiIlmiah');
        } else if (currentActiveSectionId === 'penelitian') {
            await saveGenericCrudTable('penelitian');
        } else if (currentActiveSectionId === 'aktivitas-pembelajaran') {
            await saveGenericCrudTable('aktivitasPembelajaran');
        }

        // Call named save functions for this section
        functionNames.forEach(fnName => {
            const fn = window[fnName];
            if (typeof fn === 'function') {
                try {
                    fn();
                } catch (error) {
                    hasError = true;
                    console.error(`Error running ${fnName}:`, error);
                }
            }
        });
    } catch (error) {
        hasError = true;
        console.error('Global save failed:', error);
    }

    if (hasError) {
        showGlobalActionMessage('Sebagian data gagal disimpan, cek Console/Network.', true);
    } else {
        showGlobalActionMessage('Data berhasil disimpan.');
    }
}

function updateGlobalSectionActionState() {
    const statusEl = document.getElementById('globalActionMode');
    if (statusEl) {
        statusEl.textContent = isGlobalEditMode ? 'Mode: Edit' : 'Mode: Lihat';
    }
}

function initializeGlobalSectionActions() {
    let actionBar = document.getElementById('globalSectionActions');

    if (!actionBar) {
        const mainContent = document.querySelector('.main-content');
        if (!mainContent) return;

        actionBar = document.createElement('div');
        actionBar.id = 'globalSectionActions';
        actionBar.style.display = 'flex';
        actionBar.style.alignItems = 'center';
        actionBar.style.gap = '8px';
        actionBar.style.marginBottom = '12px';
        actionBar.innerHTML = `
            <button type="button" id="globalSaveBtn" class="btn btn-success">💾 Save</button>
            <button type="button" id="globalEditBtn" class="btn btn-primary">✏️ Edit</button>
            <button type="button" id="globalViewBtn" class="btn btn-info">👁️ Lihat</button>
            <span id="globalActionMode" style="font-size: 12px; color: #666; margin-left: 8px;">Mode: Edit</span>
            <span id="globalActionStatus" style="font-size: 12px; color: #198754; margin-left: 8px; opacity: 0.7;"></span>
        `;

        mainContent.insertBefore(actionBar, mainContent.firstChild);
    }

    if (actionBar.dataset.bound === '1') {
        updateGlobalSectionActionState();
        return;
    }

    const saveBtn = document.getElementById('globalSaveBtn');
    const editBtn = document.getElementById('globalEditBtn');
    const viewBtn = document.getElementById('globalViewBtn');

    if (saveBtn) saveBtn.addEventListener('click', runGlobalSave);
    if (editBtn) editBtn.addEventListener('click', function() {
        isGlobalEditMode = true;
        applySectionViewMode(true);
        updateGlobalSectionActionState();
    });
    if (viewBtn) viewBtn.addEventListener('click', function() {
        isGlobalEditMode = false;
        applySectionViewMode(false);
        updateGlobalSectionActionState();
    });

    actionBar.dataset.bound = '1';
    updateGlobalSectionActionState();
}

const menuLinks2 = document.querySelectorAll('.sidebar-menu .menu-link');
menuLinks2.forEach(link => {
    link.addEventListener('click', function(e) {
        e.preventDefault();

        menuLinks2.forEach(l => l.classList.remove('active'));
        this.classList.add('active');

        const sectionId = this.getAttribute('href').replace('#', '');
        showSection(sectionId);
        
        // Update hash to trigger hashchange event for portfolio sections
        if (window.location.hash !== '#' + sectionId) {
            window.location.hash = sectionId;
        }
    });
});

const dropdownLinks = document.querySelectorAll('.dropdown-menu a[href^="#"]');
dropdownLinks.forEach(link => {
    link.addEventListener('click', function(e) {
        const sectionId = this.getAttribute('href').replace('#', '');
        if (!sectionId) return;
        e.preventDefault();
        showSection(sectionId);
    });
});

/* ========== PERSONAL DETAILS FORM FUNCTIONS ========== */

// Open Personal Details Form
function openPersonalDetailsForm() {
    const modal = document.getElementById('personalDetailsModal');
    if (modal) {
        modal.style.display = 'flex';
        modal.classList.add('active');
        loadPersonalDetails();
    }
}

// Close Personal Details Form
function closePersonalDetailsForm() {
    const modal = document.getElementById('personalDetailsModal');
    if (modal) {
        modal.style.display = 'none';
        modal.classList.remove('active');
    }
}

// Close Preview
function closePersonalDetailsPreview() {
    const modal = document.getElementById('personalDetailsPreview');
    if (modal) {
        modal.style.display = 'none';
        modal.classList.remove('active');
    }
}

// Load Personal Details from localStorage
function loadPersonalDetails() {
    const data = getUserStorage('personalDetails');
    if (data) {
        const namaEl = document.getElementById('nama');
        const alamatEl = document.getElementById('alamat');
        const teleponEl = document.getElementById('telepon');
        const hpEl = document.getElementById('hp');
        const dateCommenceEl = document.getElementById('dateCommence');
        const photoPreviewEl = document.getElementById('photoPreview');
        
        if (namaEl) namaEl.value = data.nama || '';
        if (alamatEl) alamatEl.value = data.alamat || '';
        if (teleponEl) teleponEl.value = data.telepon || '';
        if (hpEl) hpEl.value = data.hp || '';
        if (dateCommenceEl) dateCommenceEl.value = data.dateCommence || '';
        
        if (data.photo && photoPreviewEl) {
            photoPreviewEl.src = data.photo;
        }
    }
}

// Handle Photo Upload
document.addEventListener('DOMContentLoaded', function() {
    const photoInput = document.getElementById('photoInput');
    if (photoInput) {
        photoInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    document.getElementById('photoPreview').src = event.target.result;
                };
                reader.readAsDataURL(file);
            }
        });
    }
});

// Save Personal Details
function savePersonalDetails() {
    const nama = document.getElementById('nama').value;
    const alamat = document.getElementById('alamat').value;
    const telepon = document.getElementById('telepon').value;
    const hp = document.getElementById('hp').value;
    const dateCommence = document.getElementById('dateCommence').value;
    const photo = document.getElementById('photoPreview').src;

    if (!nama || !alamat || !telepon || !hp || !dateCommence) {
        alert('Mohon lengkapi semua field yang wajib diisi');
        return;
    }

    const personalDetails = {
        nama,
        alamat,
        telepon,
        hp,
        dateCommence,
        photo
    };

    setUserStorage('personalDetails', personalDetails);
    closePersonalDetailsForm();
    showPersonalDetailsPreview(personalDetails);
}

// Show Preview
function showPersonalDetailsPreview(data) {
    const previewModal = document.getElementById('personalDetailsPreview');
    const previewContent = document.getElementById('previewContent');

    const previewHTML = `
        <div class="preview-content-personal">
            <h1 class="preview-title">PERSONAL DETAILS</h1>
            
            <table class="personal-details-table">
                <tr>
                    <td class="label-col">Nama</td>
                    <td class="value-col">${escapeHtml(data.nama)}</td>
                </tr>
                <tr>
                    <td class="label-col" rowspan="3">Alamat</td>
                    <td class="value-col">${escapeHtml(data.alamat).split('\n')[0] || ''}</td>
                </tr>
                <tr>
                    <td class="value-col">${escapeHtml(data.alamat).split('\n')[1] || ''}</td>
                </tr>
                <tr>
                    <td class="value-col">${escapeHtml(data.alamat).split('\n')[2] || ''}</td>
                </tr>
                <tr>
                    <td class="label-col">Telepon</td>
                    <td class="value-col">${escapeHtml(data.telepon)}</td>
                </tr>
                <tr>
                    <td class="label-col">HP</td>
                    <td class="value-col">${escapeHtml(data.hp)}</td>
                </tr>
            </table>
            
            <div class="preview-photo-container">
                <div class="preview-photo-box-large">
                    <img src="${data.photo}" alt="Pas Foto">
                </div>
            </div>
            
            <div class="date-field">
                <span class="date-label">Date of commence :</span>
                <span class="date-value">${data.dateCommence}</span>
            </div>
            
            <div class="signature-field">
                <span class="signature-label">Signature :</span>
                <div class="signature-line-long"></div>
            </div>
        </div>
    `;

    previewContent.innerHTML = previewHTML;
    previewModal.style.display = 'flex';
    previewModal.classList.add('active');
}

// Utility function to escape HTML
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Close modal when clicking backdrop
document.addEventListener('click', function(e) {
    const personalDetailsModal = document.getElementById('personalDetailsModal');
    const previewModal = document.getElementById('personalDetailsPreview');
    
    if (e.target === personalDetailsModal) {
        closePersonalDetailsForm();
    }
    if (e.target === previewModal) {
        closePersonalDetailsPreview();
    }
});

// Close modal on Escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closePersonalDetailsForm();
        closePersonalDetailsPreview();
        closeObjectiveLevelPreview();
    }
});

/* ========== OBJECTIVE LEVEL OF EDUCATION FUNCTIONS ========== */

// Open Objective Level Preview
function openObjectiveLevelPreview() {
    const modal = document.getElementById('objectiveLevelPreview');
    if (modal) {
        modal.style.display = 'flex';
        modal.classList.add('active');
    }
}

// Close Objective Level Preview
function closeObjectiveLevelPreview() {
    const modal = document.getElementById('objectiveLevelPreview');
    if (modal) {
        modal.style.display = 'none';
        modal.classList.remove('active');
    }
}

// Close modal when clicking backdrop
document.addEventListener('click', function(e) {
    const objectiveLevelPreview = document.getElementById('objectiveLevelPreview');
    
    if (e.target === objectiveLevelPreview) {
        closeObjectiveLevelPreview();
    }
});

/* ========== ACADEMIC TUTORS FUNCTIONS ========== */

// Open Academic Tutors Form
function openAcademicTutorsForm() {
    const modal = document.getElementById('academicTutorsModal');
    if (modal) {
        modal.style.display = 'flex';
        modal.classList.add('active');
        loadAcademicTutorsData();
    }
}

// Close Academic Tutors Form
function closeAcademicTutorsForm() {
    const modal = document.getElementById('academicTutorsModal');
    if (modal) {
        modal.style.display = 'none';
        modal.classList.remove('active');
    }
}

// Load Academic Tutors data from localStorage
function loadAcademicTutorsData() {
    const data = getUserStorage('academicTutorsData', {});
    const s1_name1El = document.getElementById('s1_name1');
    const s1_name2El = document.getElementById('s1_name2');
    const s2_name1El = document.getElementById('s2_name1');
    const s2_name2El = document.getElementById('s2_name2');
    const s3_name1El = document.getElementById('s3_name1');
    const s3_name2El = document.getElementById('s3_name2');
    
    if (s1_name1El) s1_name1El.value = data.s1_name1 || '';
    if (s1_name2El) s1_name2El.value = data.s1_name2 || '';
    if (s2_name1El) s2_name1El.value = data.s2_name1 || '';
    if (s2_name2El) s2_name2El.value = data.s2_name2 || '';
    if (s3_name1El) s3_name1El.value = data.s3_name1 || '';
    if (s3_name2El) s3_name2El.value = data.s3_name2 || '';
}

// Save Academic Tutors data to localStorage
function saveAcademicTutorsData() {
    const data = {
        s1_name1: document.getElementById('s1_name1').value,
        s1_name2: document.getElementById('s1_name2').value,
        s2_name1: document.getElementById('s2_name1').value,
        s2_name2: document.getElementById('s2_name2').value,
        s3_name1: document.getElementById('s3_name1').value,
        s3_name2: document.getElementById('s3_name2').value
    };
    setUserStorage('academicTutorsData', data);
}

// Auto-save form when inputs change
document.addEventListener('input', function(e) {
    if (e.target.id && e.target.id.startsWith('s') && (e.target.id.includes('_name'))) {
        saveAcademicTutorsData();
    }
});

// Close modal when clicking backdrop
document.addEventListener('click', function(e) {
    const academicTutorsModal = document.getElementById('academicTutorsModal');
    
    if (e.target === academicTutorsModal) {
        closeAcademicTutorsForm();
    }
});

// CERTIFICATE FUNCTIONS
function openCertificateForm() {
    const modal = document.getElementById('certificateModal');
    if (modal) {
        modal.style.display = 'flex';
        modal.classList.add('active');
        loadCertificateData();
    }
}

// Close Certificate Form
function closeCertificateForm() {
    const modal = document.getElementById('certificateModal');
    if (modal) {
        modal.style.display = 'none';
        modal.classList.remove('active');
    }
}

// Load Certificate data from localStorage
function loadCertificateData() {
    const data = getUserStorage('certificateData', {});
    const cert1SignatureEl = document.getElementById('cert1_signature');
    const cert1DateEl = document.getElementById('cert1_date');
    const cert2NameEl = document.getElementById('cert2_name');
    const cert2SignatureEl = document.getElementById('cert2_signature');
    const cert2DateEl = document.getElementById('cert2_date');
    
    if (cert1SignatureEl) cert1SignatureEl.value = data.cert1_signature || '';
    if (cert1DateEl) cert1DateEl.value = data.cert1_date || '';
    if (cert2NameEl) cert2NameEl.value = data.cert2_name || '';
    if (cert2SignatureEl) cert2SignatureEl.value = data.cert2_signature || '';
    if (cert2DateEl) cert2DateEl.value = data.cert2_date || '';
}

// Save Certificate data to localStorage
function saveCertificateData() {
    const data = {
        cert1_signature: document.getElementById('cert1_signature').value,
        cert1_date: document.getElementById('cert1_date').value,
        cert2_name: document.getElementById('cert2_name').value,
        cert2_signature: document.getElementById('cert2_signature').value,
        cert2_date: document.getElementById('cert2_date').value
    };
    setUserStorage('certificateData', data);
}

// Auto-save certificate form when inputs change
document.addEventListener('input', function(e) {
    if (e.target.id && e.target.id.startsWith('cert')) {
        saveCertificateData();
    }
});

// Close certificate modal when clicking backdrop
document.addEventListener('click', function(e) {
    const certificateModal = document.getElementById('certificateModal');
    
    if (e.target === certificateModal) {
        closeCertificateForm();
    }
});

// DISCUSSION & ASSESSMENT FUNCTIONS
function openDiscussionAssessmentForm() {
    const modal = document.getElementById('discussionAssessmentModal');
    if (modal) {
        modal.style.display = 'flex';
        modal.classList.add('active');
        loadDiscussionAssessmentData();
    }
}

// Close Discussion & Assessment Form
function closeDiscussionAssessmentForm() {
    const modal = document.getElementById('discussionAssessmentModal');
    if (modal) {
        modal.style.display = 'none';
        modal.classList.remove('active');
    }
}

// Load Discussion & Assessment data from localStorage
function loadDiscussionAssessmentData() {
    const data = getUserStorage('discussionAssessmentData', {});
    const dateInputs = document.querySelectorAll('#discussionAssessmentForm .discussion-date');
    const signedInputs = document.querySelectorAll('#discussionAssessmentForm .discussion-signed');
    const dateInputs2 = document.querySelectorAll('#discussionAssessmentForm .discussion-date-2');
    const signedInputs2 = document.querySelectorAll('#discussionAssessmentForm .discussion-signed-2');
    
    dateInputs.forEach((input, index) => {
        input.value = data[`date_${index}`] || '';
    });
    signedInputs.forEach((input, index) => {
        input.value = data[`signed_${index}`] || '';
    });
    dateInputs2.forEach((input, index) => {
        input.value = data[`date2_${index}`] || '';
    });
    signedInputs2.forEach((input, index) => {
        input.value = data[`signed2_${index}`] || '';
    });
}

// Save Discussion & Assessment data to localStorage
function saveDiscussionAssessmentData() {
    const data = {};
    const dateInputs = document.querySelectorAll('#discussionAssessmentForm .discussion-date');
    const signedInputs = document.querySelectorAll('#discussionAssessmentForm .discussion-signed');
    const dateInputs2 = document.querySelectorAll('#discussionAssessmentForm .discussion-date-2');
    const signedInputs2 = document.querySelectorAll('#discussionAssessmentForm .discussion-signed-2');
    
    dateInputs.forEach((input, index) => {
        data[`date_${index}`] = input.value;
    });
    signedInputs.forEach((input, index) => {
        data[`signed_${index}`] = input.value;
    });
    dateInputs2.forEach((input, index) => {
        data[`date2_${index}`] = input.value;
    });
    signedInputs2.forEach((input, index) => {
        data[`signed2_${index}`] = input.value;
    });
    setUserStorage('discussionAssessmentData', data);
}

// Auto-save discussion & assessment form when inputs change
document.addEventListener('input', function(e) {
    if (e.target.classList.contains('discussion-date') || e.target.classList.contains('discussion-signed') || 
        e.target.classList.contains('discussion-date-2') || e.target.classList.contains('discussion-signed-2')) {
        saveDiscussionAssessmentData();
    }
});

// Close discussion & assessment modal when clicking backdrop
document.addEventListener('click', function(e) {
    const discussionModal = document.getElementById('discussionAssessmentModal');
    
    if (e.target === discussionModal) {
        closeDiscussionAssessmentForm();
    }
});

// ROTATION SCHEDULE FUNCTIONS
function openRotationSchedule() {
    const modal = document.getElementById('rotationScheduleModal');
    if (modal) {
        modal.style.display = 'flex';
        modal.classList.add('active');
    }
}

// Close Rotation Schedule
function closeRotationSchedule() {
    const modal = document.getElementById('rotationScheduleModal');
    if (modal) {
        modal.style.display = 'none';
        modal.classList.remove('active');
    }
}

// Close rotation schedule modal when clicking backdrop
document.addEventListener('click', function(e) {
    const rotationModal = document.getElementById('rotationScheduleModal');
    
    if (e.target === rotationModal) {
        closeRotationSchedule();
    }
});

// Academic Tasks Functions
function openAcademicTasks() {
    const modal = document.getElementById('academicTasksModal');
    if (modal) {
        modal.style.display = 'flex';
        modal.classList.add('active');
        loadAcademicTasks();
    }
}

function closeAcademicTasks() {
    const modal = document.getElementById('academicTasksModal');
    if (modal) {
        modal.style.display = 'none';
        modal.classList.remove('active');
    }
}

function loadAcademicTasks() {
    const data = getUserStorage('academicTasks', {});
    Object.keys(data).forEach(key => {
        const input = document.getElementById(key);
        if (input) {
            input.value = data[key];
        }
    });
}

function saveAcademicTasks() {
    const inputs = document.querySelectorAll('.academic-input');
    const data = {};
    inputs.forEach(input => {
        data[input.id] = input.value;
    });
    setUserStorage('academicTasks', data);
}

// Auto-save on input
document.addEventListener('DOMContentLoaded', function() {
    setTimeout(() => {
        const inputs = document.querySelectorAll('.academic-input');
        inputs.forEach(input => {
            input.addEventListener('input', saveAcademicTasks);
        });
    }, 500);
});

// Close Academic Tasks modal when clicking backdrop
document.addEventListener('click', function(e) {
    const academicModal = document.getElementById('academicTasksModal');
    
    if (e.target === academicModal) {
        closeAcademicTasks();
    }
});

// Research Activities Functions
function openResearchActivities() {
    const modal = document.getElementById('researchActivitiesModal');
    if (modal) {
        modal.style.display = 'flex';
        modal.classList.add('active');
        loadResearchActivities();
    }
}

function closeResearchActivities() {
    const modal = document.getElementById('researchActivitiesModal');
    if (modal) {
        modal.style.display = 'none';
        modal.classList.remove('active');
    }
}

function loadResearchActivities() {
    const data = getUserStorage('researchActivities', {});
    Object.keys(data).forEach(key => {
        const input = document.getElementById(key);
        if (input) {
            input.value = data[key];
        }
    });
}

function saveResearchActivities() {
    const inputs = document.querySelectorAll('.research-input');
    const data = {};
    inputs.forEach(input => {
        data[input.id] = input.value;
    });
    setUserStorage('researchActivities', data);
}

// Auto-save Research Activities on input
document.addEventListener('DOMContentLoaded', function() {
    setTimeout(() => {
        const inputs = document.querySelectorAll('.research-input');
        inputs.forEach(input => {
            input.addEventListener('input', saveResearchActivities);
        });
    }, 500);
});

// Close Research Activities modal when clicking backdrop
document.addEventListener('click', function(e) {
    const researchModal = document.getElementById('researchActivitiesModal');
    
    if (e.target === researchModal) {
        closeResearchActivities();
    }
});

// Scientific Activities Functions
function openScientificActivities() {
    const modal = document.getElementById('scientificActivitiesModal');
    if (modal) {
        modal.style.display = 'flex';
        modal.classList.add('active');
        loadScientificActivities();
    }
}

function closeScientificActivities() {
    const modal = document.getElementById('scientificActivitiesModal');
    if (modal) {
        modal.style.display = 'none';
        modal.classList.remove('active');
    }
}

function addScientificRow() {
    const tbody = document.getElementById('scientificActivitiesTableBody');
    const rowCount = tbody.children.length;
    const newRow = document.createElement('tr');
    newRow.innerHTML = `
        <td style="border: 1px solid #000; padding: 8px; vertical-align: top;">
            <input type="text" class="scientific-input" data-field="date" data-row="${rowCount}" placeholder="dd/mm/yyyy" style="width: 100%; min-width: 110px; border: 1px solid #ccc; padding: 5px; box-sizing: border-box; background: #fff;">
        </td>
        <td style="border: 1px solid #000; padding: 8px; vertical-align: top;">
            <textarea class="scientific-input" data-field="type" data-row="${rowCount}" rows="2" style="width: 100%; border: none; padding: 5px; resize: vertical; font-family: inherit;"></textarea>
        </td>
        <td style="border: 1px solid #000; padding: 8px; vertical-align: top;">
            <textarea class="scientific-input" data-field="title" data-row="${rowCount}" rows="2" style="width: 100%; border: none; padding: 5px; resize: vertical; font-family: inherit;"></textarea>
        </td>
        <td style="border: 1px solid #000; padding: 8px; vertical-align: top;">
            <textarea class="scientific-input" data-field="lecturer" data-row="${rowCount}" rows="2" style="width: 100%; border: none; padding: 5px; resize: vertical; font-family: inherit;"></textarea>
        </td>
        <td class="no-print" style="border: 1px solid #000; padding: 8px; text-align: center; vertical-align: middle;">
            <button onclick="deleteScientificRow(this)" class="btn-delete" style="background: #dc3545; color: white; border: none; padding: 5px 10px; cursor: pointer; border-radius: 3px;">Delete</button>
        </td>
    `;
    tbody.appendChild(newRow);
    
    // Add event listeners to new inputs
    newRow.querySelectorAll('.scientific-input').forEach(input => {
        input.addEventListener('input', saveScientificActivities);
    });
}

function deleteScientificRow(button) {
    const row = button.closest('tr');
    row.remove();
    saveScientificActivities();
}

function loadScientificActivities() {
    const data = getUserStorage('scientificActivities', []);
    const tbody = document.getElementById('scientificActivitiesTableBody');
    tbody.innerHTML = ''; // Clear existing rows
    
    if (Array.isArray(data) && data.length > 0) {
        data.forEach((rowData, index) => {
            const newRow = document.createElement('tr');
            newRow.innerHTML = `
                <td style="border: 1px solid #000; padding: 8px; vertical-align: top;">
                    <input type="text" class="scientific-input" data-field="date" data-row="${index}" value="${rowData.date || ''}" placeholder="dd/mm/yyyy" style="width: 100%; min-width: 110px; border: 1px solid #ccc; padding: 5px; box-sizing: border-box; background: #fff;">
                </td>
                <td style="border: 1px solid #000; padding: 8px; vertical-align: top;">
                    <textarea class="scientific-input" data-field="type" data-row="${index}" rows="2" style="width: 100%; border: none; padding: 5px; resize: vertical; font-family: inherit;">${rowData.type || ''}</textarea>
                </td>
                <td style="border: 1px solid #000; padding: 8px; vertical-align: top;">
                    <textarea class="scientific-input" data-field="title" data-row="${index}" rows="2" style="width: 100%; border: none; padding: 5px; resize: vertical; font-family: inherit;">${rowData.title || ''}</textarea>
                </td>
                <td style="border: 1px solid #000; padding: 8px; vertical-align: top;">
                    <textarea class="scientific-input" data-field="lecturer" data-row="${index}" rows="2" style="width: 100%; border: none; padding: 5px; resize: vertical; font-family: inherit;">${rowData.lecturer || ''}</textarea>
                </td>
                <td class="no-print" style="border: 1px solid #000; padding: 8px; text-align: center; vertical-align: middle;">
                    <button onclick="deleteScientificRow(this)" class="btn-delete" style="background: #dc3545; color: white; border: none; padding: 5px 10px; cursor: pointer; border-radius: 3px;">Delete</button>
                </td>
            `;
            tbody.appendChild(newRow);
            
            // Add event listeners
            newRow.querySelectorAll('.scientific-input').forEach(input => {
                input.addEventListener('input', saveScientificActivities);
            });
        });
    }
    
    // If no data, add a few empty rows
    if (tbody.children.length === 0) {
        for (let i = 0; i < 5; i++) {
            addScientificRow();
        }
    }
}

function saveScientificActivities() {
    const tbody = document.getElementById('scientificActivitiesTableBody');
    const rows = tbody.querySelectorAll('tr');
    const data = [];
    
    rows.forEach(row => {
        const inputs = row.querySelectorAll('.scientific-input');
        const rowData = {
            date: inputs[0]?.value || '',
            type: inputs[1]?.value || '',
            title: inputs[2]?.value || '',
            lecturer: inputs[3]?.value || ''
        };
        data.push(rowData);
    });
    
    setUserStorage('scientificActivities', data);
}

// Close Scientific Activities modal when clicking backdrop
document.addEventListener('click', function(e) {
    const scientificModal = document.getElementById('scientificActivitiesModal');
    
    if (e.target === scientificModal) {
        closeScientificActivities();
    }
});

// Sertifikat Section Functions
let sertifikatRowsData = [];

function escapeSertifikatHtml(value) {
    return String(value || '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
}

function loadSertifikatData() {
    try {
        // Use user-specific storage key
        const userId = window.currentUserId || 'guest';
        const storageKey = `sertifikatTableData_user_${userId}`;
        const saved = JSON.parse(localStorage.getItem(storageKey));
        sertifikatRowsData = Array.isArray(saved) ? saved : [];
    } catch (error) {
        sertifikatRowsData = [];
    }

    if (sertifikatRowsData.length === 0) {
        sertifikatRowsData.push({
            nama: '',
            tanggal: '',
            institusi: '',
            fileName: '',
            fileData: '',
            fileType: ''
        });
    }

    renderSertifikatTable();
}

function saveSertifikatData() {
    setUserStorage('sertifikatTableData', sertifikatRowsData);
}

function renderSertifikatTable() {
    const tbody = document.getElementById('sertifikatTableBody');
    if (!tbody) return;

    tbody.innerHTML = '';

    sertifikatRowsData.forEach((row, index) => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td style="border: 1px solid #ddd; padding: 8px; text-align: center;">${index + 1}</td>
            <td style="border: 1px solid #ddd; padding: 8px;">
                <input type="text" class="sertifikat-input" data-index="${index}" data-field="nama" value="${escapeSertifikatHtml(row.nama)}" style="width: 100%; border: 1px solid #ccc; padding: 6px; box-sizing: border-box;" placeholder="Masukkan nama sertifikat">
            </td>
            <td style="border: 1px solid #ddd; padding: 8px;">
                <input type="date" class="sertifikat-input" data-index="${index}" data-field="tanggal" value="${escapeSertifikatHtml(row.tanggal)}" style="width: 100%; border: 1px solid #ccc; padding: 6px; box-sizing: border-box;">
            </td>
            <td style="border: 1px solid #ddd; padding: 8px;">
                <input type="text" class="sertifikat-input" data-index="${index}" data-field="institusi" value="${escapeSertifikatHtml(row.institusi)}" style="width: 100%; border: 1px solid #ccc; padding: 6px; box-sizing: border-box;" placeholder="Institusi penerbit">
            </td>
            <td style="border: 1px solid #ddd; padding: 8px;">
                <input type="file" id="sertifikat_file_${index}" class="sertifikat-file-input" data-index="${index}" accept=".pdf,.jpg,.jpeg,.png" style="display: none;">
                <div class="no-print" style="display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-bottom: 4px;">
                    <button type="button" class="btn btn-secondary" onclick="triggerSertifikatUpload(${index})">Upload</button>
                    ${row.fileData ? `<button type="button" class="btn btn-primary" onclick="viewSertifikatFile(${index})">Lihat</button>` : ''}
                </div>
                <div style="font-size: 12px; color: #555; word-break: break-word;">${escapeSertifikatHtml(row.fileName || 'Belum ada file')}</div>
            </td>
            <td class="no-print" style="border: 1px solid #ddd; padding: 8px; text-align: center;">
                <button type="button" class="btn btn-danger" onclick="deleteSertifikatRow(${index})">Hapus</button>
            </td>
        `;
        tbody.appendChild(tr);
    });

    tbody.querySelectorAll('.sertifikat-input').forEach(input => {
        input.addEventListener('input', handleSertifikatInputChange);
        input.addEventListener('change', handleSertifikatInputChange);
    });

    tbody.querySelectorAll('.sertifikat-file-input').forEach(input => {
        input.addEventListener('change', handleSertifikatFileChange);
    });
}

function handleSertifikatInputChange(event) {
    const index = Number(event.target.dataset.index);
    const field = event.target.dataset.field;

    if (!Number.isNaN(index) && sertifikatRowsData[index]) {
        sertifikatRowsData[index][field] = event.target.value;
        saveSertifikatData();
    }
}

function handleSertifikatFileChange(event) {
    const index = Number(event.target.dataset.index);
    const file = event.target.files[0];

    if (Number.isNaN(index) || !sertifikatRowsData[index] || !file) return;

    const reader = new FileReader();
    reader.onload = function(loadEvent) {
        sertifikatRowsData[index].fileName = file.name;
        sertifikatRowsData[index].fileData = loadEvent.target.result;
        sertifikatRowsData[index].fileType = file.type;
        saveSertifikatData();
        renderSertifikatTable();
    };
    reader.readAsDataURL(file);
}

function triggerSertifikatUpload(index) {
    const input = document.getElementById(`sertifikat_file_${index}`);
    if (input) {
        input.click();
    }
}

function viewSertifikatFile(index) {
    const row = sertifikatRowsData[index];
    if (!row || !row.fileData) return;
    window.open(row.fileData, '_blank');
}

function addSertifikatRow() {
    sertifikatRowsData.push({
        nama: '',
        tanggal: '',
        institusi: '',
        fileName: '',
        fileData: '',
        fileType: ''
    });
    saveSertifikatData();
    renderSertifikatTable();
}

function deleteSertifikatRow(index) {
    sertifikatRowsData.splice(index, 1);
    if (sertifikatRowsData.length === 0) {
        sertifikatRowsData.push({
            nama: '',
            tanggal: '',
            institusi: '',
            fileName: '',
            fileData: '',
            fileType: ''
        });
    }
    saveSertifikatData();
    renderSertifikatTable();
}

function printSertifikatTable() {
    const rowsHtml = sertifikatRowsData.map((row, index) => `
        <tr>
            <td>${index + 1}</td>
            <td>${escapeSertifikatHtml(row.nama)}</td>
            <td>${escapeSertifikatHtml(row.tanggal)}</td>
            <td>${escapeSertifikatHtml(row.institusi)}</td>
            <td>${escapeSertifikatHtml(row.fileName || '-')}</td>
        </tr>
    `).join('');

    const printWindow = window.open('', '_blank');
    if (!printWindow) return;

    printWindow.document.write(`
        <html>
            <head>
                <title>Data Sertifikat</title>
                <style>
                    body { font-family: Arial, sans-serif; margin: 24px; }
                    h2 { margin-bottom: 16px; }
                    table { width: 100%; border-collapse: collapse; }
                    th, td { border: 1px solid #000; padding: 8px; text-align: left; font-size: 12px; }
                    th { background: #f2f2f2; }
                </style>
            </head>
            <body>
                <h2>Data Sertifikat</h2>
                <table>
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Nama Sertifikat</th>
                            <th>Tanggal</th>
                            <th>Institusi</th>
                            <th>Nama File</th>
                        </tr>
                    </thead>
                    <tbody>${rowsHtml}</tbody>
                </table>
            </body>
        </html>
    `);
    printWindow.document.close();
    printWindow.focus();
    printWindow.print();
}

document.addEventListener('DOMContentLoaded', function() {
    loadSertifikatData();
});

// Laporan Progress Section Functions
let laporanProgressRowsData = [];

function escapeLaporanProgressHtml(value) {
    return String(value || '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
}

function loadLaporanProgressData() {
    try {
        // Use user-specific storage key
        const userId = window.currentUserId || 'guest';
        const storageKey = `laporanProgressTableData_user_${userId}`;
        const saved = JSON.parse(localStorage.getItem(storageKey));
        laporanProgressRowsData = Array.isArray(saved) ? saved : [];
    } catch (error) {
        laporanProgressRowsData = [];
    }

    if (laporanProgressRowsData.length === 0) {
        laporanProgressRowsData.push({
            periode: '',
            target: '',
            pencapaian: '',
            status: 'On Progress',
            catatan: ''
        });
    }

    renderLaporanProgressTable();
}

function saveLaporanProgressData() {
    // Use user-specific storage key
    const userId = window.currentUserId || 'guest';
    const storageKey = `laporanProgressTableData_user_${userId}`;
    localStorage.setItem(storageKey, JSON.stringify(laporanProgressRowsData));
}

function renderLaporanProgressTable() {
    const tbody = document.getElementById('laporanProgressTableBody');
    if (!tbody) return;

    tbody.innerHTML = '';

    laporanProgressRowsData.forEach((row, index) => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td style="border: 1px solid #ddd; padding: 8px; text-align: center;">${index + 1}</td>
            <td style="border: 1px solid #ddd; padding: 8px;">
                <input type="month" class="laporan-progress-input" data-index="${index}" data-field="periode" value="${escapeLaporanProgressHtml(row.periode)}" style="width: 100%; border: 1px solid #ccc; padding: 6px; box-sizing: border-box;">
            </td>
            <td style="border: 1px solid #ddd; padding: 8px;">
                <textarea class="laporan-progress-input" data-index="${index}" data-field="target" rows="2" style="width: 100%; border: 1px solid #ccc; padding: 6px; box-sizing: border-box; resize: vertical;">${escapeLaporanProgressHtml(row.target)}</textarea>
            </td>
            <td style="border: 1px solid #ddd; padding: 8px;">
                <textarea class="laporan-progress-input" data-index="${index}" data-field="pencapaian" rows="2" style="width: 100%; border: 1px solid #ccc; padding: 6px; box-sizing: border-box; resize: vertical;">${escapeLaporanProgressHtml(row.pencapaian)}</textarea>
            </td>
            <td style="border: 1px solid #ddd; padding: 8px;">
                <select class="laporan-progress-input" data-index="${index}" data-field="status" style="width: 100%; border: 1px solid #ccc; padding: 6px; box-sizing: border-box;">
                    <option value="On Progress" ${row.status === 'On Progress' ? 'selected' : ''}>On Progress</option>
                    <option value="Selesai" ${row.status === 'Selesai' ? 'selected' : ''}>Selesai</option>
                    <option value="Tertunda" ${row.status === 'Tertunda' ? 'selected' : ''}>Tertunda</option>
                </select>
            </td>
            <td style="border: 1px solid #ddd; padding: 8px;">
                <textarea class="laporan-progress-input" data-index="${index}" data-field="catatan" rows="2" style="width: 100%; border: 1px solid #ccc; padding: 6px; box-sizing: border-box; resize: vertical;">${escapeLaporanProgressHtml(row.catatan)}</textarea>
            </td>
            <td class="no-print" style="border: 1px solid #ddd; padding: 8px; text-align: center;">
                <button type="button" class="btn btn-danger" onclick="deleteLaporanProgressRow(${index})">Hapus</button>
            </td>
        `;
        tbody.appendChild(tr);
    });

    tbody.querySelectorAll('.laporan-progress-input').forEach(input => {
        input.addEventListener('input', handleLaporanProgressInputChange);
        input.addEventListener('change', handleLaporanProgressInputChange);
    });
}

function handleLaporanProgressInputChange(event) {
    const index = Number(event.target.dataset.index);
    const field = event.target.dataset.field;

    if (!Number.isNaN(index) && laporanProgressRowsData[index]) {
        laporanProgressRowsData[index][field] = event.target.value;
        saveLaporanProgressData();
    }
}

function addLaporanProgressRow() {
    laporanProgressRowsData.push({
        periode: '',
        target: '',
        pencapaian: '',
        status: 'On Progress',
        catatan: ''
    });
    saveLaporanProgressData();
    renderLaporanProgressTable();
}

function deleteLaporanProgressRow(index) {
    laporanProgressRowsData.splice(index, 1);
    if (laporanProgressRowsData.length === 0) {
        laporanProgressRowsData.push({
            periode: '',
            target: '',
            pencapaian: '',
            status: 'On Progress',
            catatan: ''
        });
    }
    saveLaporanProgressData();
    renderLaporanProgressTable();
}

function printLaporanProgressTable() {
    const rowsHtml = laporanProgressRowsData.map((row, index) => `
        <tr>
            <td>${index + 1}</td>
            <td>${escapeLaporanProgressHtml(row.periode)}</td>
            <td>${escapeLaporanProgressHtml(row.target)}</td>
            <td>${escapeLaporanProgressHtml(row.pencapaian)}</td>
            <td>${escapeLaporanProgressHtml(row.status)}</td>
            <td>${escapeLaporanProgressHtml(row.catatan)}</td>
        </tr>
    `).join('');

    const printWindow = window.open('', '_blank');
    if (!printWindow) return;

    printWindow.document.write(`
        <html>
            <head>
                <title>Laporan Progress</title>
                <style>
                    body { font-family: Arial, sans-serif; margin: 24px; }
                    h2 { margin-bottom: 16px; }
                    table { width: 100%; border-collapse: collapse; }
                    th, td { border: 1px solid #000; padding: 8px; text-align: left; font-size: 12px; vertical-align: top; }
                    th { background: #f2f2f2; }
                </style>
            </head>
            <body>
                <h2>Laporan Progress</h2>
                <table>
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Periode</th>
                            <th>Target Kompetensi</th>
                            <th>Pencapaian</th>
                            <th>Status</th>
                            <th>Catatan</th>
                        </tr>
                    </thead>
                    <tbody>${rowsHtml}</tbody>
                </table>
            </body>
        </html>
    `);
    printWindow.document.close();
    printWindow.focus();
    printWindow.print();
}

document.addEventListener('DOMContentLoaded', function() {
    initializeGlobalSectionActions();
    loadLaporanProgressData();
});

// Generic CRUD Tables for menu sections
const genericCrudTableConfigs = {
    publikasiIlmiah: {
        storageKey: 'publikasiIlmiahTableData',
        tableBodyId: 'publikasiIlmiahTableBody',
        printTitle: 'Publikasi Ilmiah',
        fields: [
            { key: 'tahun', label: 'Tahun', type: 'number', min: '1900', max: '2100', placeholder: '2026' },
            { key: 'judul', label: 'Judul Publikasi', type: 'textarea', rows: 2, placeholder: 'Judul publikasi' },
            { key: 'jurnal', label: 'Jurnal / Media', type: 'text', placeholder: 'Nama jurnal/media' },
            { key: 'status', label: 'Status', type: 'select', options: ['Draft', 'Submit', 'Published'] },
            { key: 'catatan', label: 'Catatan', type: 'textarea', rows: 2, placeholder: 'Catatan tambahan' }
        ]
    },
    penelitian: {
        storageKey: 'penelitianTableData',
        tableBodyId: 'penelitianTableBody',
        printTitle: 'Penelitian',
        fields: [
            { key: 'periode', label: 'Periode', type: 'month' },
            { key: 'judul', label: 'Judul Penelitian', type: 'textarea', rows: 2, placeholder: 'Judul penelitian' },
            { key: 'peran', label: 'Peran', type: 'text', placeholder: 'Peran Anda' },
            { key: 'status', label: 'Status', type: 'select', options: ['Perencanaan', 'Berjalan', 'Selesai'] },
            { key: 'catatan', label: 'Catatan', type: 'textarea', rows: 2, placeholder: 'Catatan tambahan' }
        ]
    },
    aktivitasPembelajaran: {
        storageKey: 'aktivitasPembelajaranTableData',
        tableBodyId: 'aktivitasPembelajaranTableBody',
        printTitle: 'Aktivitas Pembelajaran',
        fields: [
            { key: 'tanggal', label: 'Tanggal', type: 'date' },
            { key: 'aktivitas', label: 'Aktivitas', type: 'textarea', rows: 2, placeholder: 'Nama aktivitas pembelajaran' },
            { key: 'tempat', label: 'Tempat / Platform', type: 'text', placeholder: 'Tempat/platform' },
            { key: 'durasi', label: 'Durasi', type: 'text', placeholder: 'Contoh: 2 jam' },
            { key: 'catatan', label: 'Catatan', type: 'textarea', rows: 2, placeholder: 'Catatan tambahan' }
        ]
    },
    seminarWorkshop: {
        storageKey: 'seminarWorkshopTableData',
        tableBodyId: 'seminarWorkshopTableBody',
        printTitle: 'Seminar & Workshop',
        fields: [
            { key: 'tanggal', label: 'Tanggal', type: 'date' },
            { key: 'kegiatan', label: 'Nama Kegiatan', type: 'textarea', rows: 2, placeholder: 'Nama seminar/workshop' },
            { key: 'penyelenggara', label: 'Penyelenggara', type: 'text', placeholder: 'Penyelenggara' },
            { key: 'peran', label: 'Peran', type: 'text', placeholder: 'Peserta/Pemateri/Moderator' },
            { key: 'catatan', label: 'Catatan', type: 'textarea', rows: 2, placeholder: 'Catatan tambahan' }
        ]
    }
};

const genericCrudTableData = {
    publikasiIlmiah: [],
    penelitian: [],
    aktivitasPembelajaran: [],
    seminarWorkshop: []
};

function escapeGenericCrudHtml(value) {
    return String(value || '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
}

const genericCrudSaveTimers = {};

function genericCrudRequest(action, payload = {}, method = 'POST') {
    if (method === 'GET') {
        const query = new URLSearchParams({ action, ...payload }).toString();
        return fetch(`php/api.php?${query}`, {
            method: 'GET',
            credentials: 'same-origin'
        }).then(response => response.json());
    }

    const body = new URLSearchParams({ action, ...payload });
    return fetch('php/api.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
        credentials: 'same-origin',
        body: body.toString()
    }).then(response => response.json());
}

function createGenericDefaultRow(configKey) {
    const config = genericCrudTableConfigs[configKey];
    const row = {};
    config.fields.forEach(field => {
        if (field.type === 'select' && Array.isArray(field.options) && field.options.length > 0) {
            row[field.key] = field.options[0];
        } else {
            row[field.key] = '';
        }
    });
    return row;
}

async function loadGenericCrudTable(configKey) {
    const config = genericCrudTableConfigs[configKey];
    if (!config) return;

    try {
        const response = await genericCrudRequest('get_generic_menu_table', { table_key: configKey }, 'GET');
        if (response && response.success && Array.isArray(response.data)) {
            genericCrudTableData[configKey] = response.data;
        } else {
            genericCrudTableData[configKey] = [];
        }
    } catch (error) {
        genericCrudTableData[configKey] = [];
    }

    if (genericCrudTableData[configKey].length === 0) {
        genericCrudTableData[configKey].push(createGenericDefaultRow(configKey));
    }

    renderGenericCrudTable(configKey);
}

async function saveGenericCrudTable(configKey) {
    const config = genericCrudTableConfigs[configKey];
    if (!config) return;

    try {
        const response = await genericCrudRequest('save_generic_menu_table', {
            table_key: configKey,
            rows_json: JSON.stringify(genericCrudTableData[configKey] || [])
        }, 'POST');

        if (!response || !response.success) {
            throw new Error(response?.message || `Gagal menyimpan ${configKey}`);
        }
    } catch (error) {
        console.error('Failed saving generic menu table:', configKey, error);
        throw error;
    }
}

function queueGenericCrudSave(configKey, delay = 300) {
    if (genericCrudSaveTimers[configKey]) {
        clearTimeout(genericCrudSaveTimers[configKey]);
    }

    genericCrudSaveTimers[configKey] = setTimeout(() => {
        saveGenericCrudTable(configKey);
    }, delay);
}

function reloadUserScopedDataAfterSessionReady() {
    const genericKeys = Object.keys(genericCrudTableConfigs);
    genericKeys.forEach(loadGenericCrudTable);

    if (typeof loadPersonalDetails === 'function') loadPersonalDetails();
    if (typeof loadSertifikatData === 'function') loadSertifikatData();
    if (typeof loadLaporanProgressData === 'function') loadLaporanProgressData();
}

window.addEventListener('elogbook:user-ready', function() {
    reloadUserScopedDataAfterSessionReady();
});

function buildGenericFieldHtml(field, row, index, configKey) {
    const value = row[field.key] || '';
    const commonData = `class="generic-crud-input" data-config="${configKey}" data-index="${index}" data-field="${field.key}"`;

    if (field.type === 'textarea') {
        return `<textarea ${commonData} rows="${field.rows || 2}" style="width: 100%; border: 1px solid #ccc; padding: 6px; box-sizing: border-box; resize: vertical;" placeholder="${escapeGenericCrudHtml(field.placeholder || '')}">${escapeGenericCrudHtml(value)}</textarea>`;
    }

    if (field.type === 'select') {
        const optionsHtml = (field.options || []).map(option => {
            const selected = value === option ? 'selected' : '';
            return `<option value="${escapeGenericCrudHtml(option)}" ${selected}>${escapeGenericCrudHtml(option)}</option>`;
        }).join('');
        return `<select ${commonData} style="width: 100%; border: 1px solid #ccc; padding: 6px; box-sizing: border-box;">${optionsHtml}</select>`;
    }

    const minAttr = field.min ? `min="${field.min}"` : '';
    const maxAttr = field.max ? `max="${field.max}"` : '';
    return `<input type="${field.type || 'text'}" ${commonData} value="${escapeGenericCrudHtml(value)}" placeholder="${escapeGenericCrudHtml(field.placeholder || '')}" ${minAttr} ${maxAttr} style="width: 100%; border: 1px solid #ccc; padding: 6px; box-sizing: border-box;">`;
}

function renderGenericCrudTable(configKey) {
    const config = genericCrudTableConfigs[configKey];
    if (!config) return;

    const tbody = document.getElementById(config.tableBodyId);
    if (!tbody) return;

    const rows = genericCrudTableData[configKey];
    tbody.innerHTML = '';

    rows.forEach((row, index) => {
        const tr = document.createElement('tr');
        const fieldCells = config.fields.map(field => `
            <td style="border: 1px solid #ddd; padding: 8px; vertical-align: top;">
                ${buildGenericFieldHtml(field, row, index, configKey)}
            </td>
        `).join('');

        tr.innerHTML = `
            <td style="border: 1px solid #ddd; padding: 8px; text-align: center;">${index + 1}</td>
            ${fieldCells}
            <td class="no-print" style="border: 1px solid #ddd; padding: 8px; text-align: center;">
                <button type="button" class="btn btn-danger" onclick="deleteGenericCrudRow('${configKey}', ${index})">Hapus</button>
            </td>
        `;
        tbody.appendChild(tr);
    });

    tbody.querySelectorAll('.generic-crud-input').forEach(input => {
        input.addEventListener('input', handleGenericCrudInputChange);
        input.addEventListener('change', handleGenericCrudInputChange);
    });
}

function handleGenericCrudInputChange(event) {
    const configKey = event.target.dataset.config;
    const index = Number(event.target.dataset.index);
    const field = event.target.dataset.field;

    if (!genericCrudTableData[configKey] || Number.isNaN(index) || !genericCrudTableData[configKey][index]) return;

    genericCrudTableData[configKey][index][field] = event.target.value;
    queueGenericCrudSave(configKey);
}

function addGenericCrudRow(configKey) {
    if (!genericCrudTableData[configKey]) return;
    genericCrudTableData[configKey].push(createGenericDefaultRow(configKey));
    queueGenericCrudSave(configKey, 0);
    renderGenericCrudTable(configKey);
}

function deleteGenericCrudRow(configKey, index) {
    if (!genericCrudTableData[configKey]) return;
    genericCrudTableData[configKey].splice(index, 1);
    if (genericCrudTableData[configKey].length === 0) {
        genericCrudTableData[configKey].push(createGenericDefaultRow(configKey));
    }
    queueGenericCrudSave(configKey, 0);
    renderGenericCrudTable(configKey);
}

function printGenericCrudTable(configKey) {
    const config = genericCrudTableConfigs[configKey];
    if (!config) return;

    const rows = genericCrudTableData[configKey] || [];
    const headersHtml = config.fields.map(field => `<th>${escapeGenericCrudHtml(field.label)}</th>`).join('');
    const rowsHtml = rows.map((row, index) => {
        const cells = config.fields.map(field => `<td>${escapeGenericCrudHtml(row[field.key] || '')}</td>`).join('');
        return `<tr><td>${index + 1}</td>${cells}</tr>`;
    }).join('');

    const printWindow = window.open('', '_blank');
    if (!printWindow) return;

    printWindow.document.write(`
        <html>
            <head>
                <title>${escapeGenericCrudHtml(config.printTitle)}</title>
                <style>
                    body { font-family: Arial, sans-serif; margin: 24px; }
                    h2 { margin-bottom: 16px; }
                    table { width: 100%; border-collapse: collapse; }
                    th, td { border: 1px solid #000; padding: 8px; text-align: left; font-size: 12px; vertical-align: top; }
                    th { background: #f2f2f2; }
                </style>
            </head>
            <body>
                <h2>${escapeGenericCrudHtml(config.printTitle)}</h2>
                <table>
                    <thead>
                        <tr>
                            <th>No</th>
                            ${headersHtml}
                        </tr>
                    </thead>
                    <tbody>${rowsHtml}</tbody>
                </table>
            </body>
        </html>
    `);
    printWindow.document.close();
    printWindow.focus();
    printWindow.print();
}

function addPublikasiIlmiahRow() { addGenericCrudRow('publikasiIlmiah'); }
function printPublikasiIlmiahTable() { printGenericCrudTable('publikasiIlmiah'); }
function addPenelitianRow() { addGenericCrudRow('penelitian'); }
function printPenelitianTable() { printGenericCrudTable('penelitian'); }
function addAktivitasPembelajaranRow() { addGenericCrudRow('aktivitasPembelajaran'); }
function printAktivitasPembelajaranTable() { printGenericCrudTable('aktivitasPembelajaran'); }
function addSeminarWorkshopRow() { addGenericCrudRow('seminarWorkshop'); }
function printSeminarWorkshopTable() { printGenericCrudTable('seminarWorkshop'); }

document.addEventListener('DOMContentLoaded', function() {
    loadGenericCrudTable('publikasiIlmiah');
    loadGenericCrudTable('penelitian');
    loadGenericCrudTable('aktivitasPembelajaran');
    loadGenericCrudTable('seminarWorkshop');
});

// CPL (Capaian Pembelajaran) CRUD Functions
// Pre-defined curriculum items
const cplCurriculumData = [
    // === CAPAIAN KOMPETENSI BERDASARKAN DIAGNOSIS ===
    { category: 'GINEKOLOGI', subcategory: 'Kelainan Jinak Ginekologi - Miometrium', daftarMasalah: 'Mioma uteri dengan penyulit (infertilitas, perlekatan, distorsianatomi, uterusmiomatosus, mioma serviks, dsb)', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Kelainan Jinak Ginekologi - Miometrium', daftarMasalah: 'Adenomiosis terkait infertilitas', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Kelainan Jinak Ginekologi - Endometrium', daftarMasalah: 'Hiperplasia endometrium', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Kelainan Jinak Ginekologi - Endometrium', daftarMasalah: 'Endometritis', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Kelainan Jinak Ginekologi - Ovarium', daftarMasalah: 'Endometriosis dengan infertilitas', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Kelainan Jinak Ginekologi - Gangguan Haid', daftarMasalah: 'Dismenore dengan infertilitas', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Kelainan Jinak Ginekologi - Gangguan Haid', daftarMasalah: 'Perdarahan uterus abnormal', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Kelainan Jinak Ginekologi - Gangguan Haid', daftarMasalah: 'Amenore primer', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Kelainan Jinak Ginekologi - Gangguan Haid', daftarMasalah: 'Amenore sekunder - WHO kelas I', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Kelainan Jinak Ginekologi - Gangguan Haid', daftarMasalah: 'Amenore sekunder - WHO kelas II', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Kelainan Jinak Ginekologi - Gangguan Haid', daftarMasalah: 'Amenore sekunder - WHO kelas III', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Kelainan Jinak Ginekologi - Gangguan Haid', daftarMasalah: 'Amenore sekunder - WHO kelas IV', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Endokrinologi Reproduksi dan Infertilitas', daftarMasalah: 'Sindroma ovarium polikistik', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Endokrinologi Reproduksi dan Infertilitas', daftarMasalah: 'Infertilitas', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Endokrinologi Reproduksi dan Infertilitas', daftarMasalah: 'Pubertas prekoks', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Endokrinologi Reproduksi dan Infertilitas', daftarMasalah: 'Delayed puberty', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Endokrinologi Reproduksi dan Infertilitas', daftarMasalah: 'Menopause', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Endokrinologi Reproduksi dan Infertilitas', daftarMasalah: 'Disorders of Sexual Development (DSD)', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Endokrinologi Reproduksi dan Infertilitas', daftarMasalah: 'Keguguran berulang', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Teknologi Reproduksi Berbantu', daftarMasalah: 'Hiperstimulasi ovarium terkendali', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: 'Teknologi Reproduksi Berbantu', daftarMasalah: 'OHSS (Ovarian Hyperstimulation Syndrome)', kompetensi: 4 },
    
    // === CAPAIAN KOMPETENSI BERDASARKAN KETERAMPILAN KLINIK ===
    { category: 'KONTRASEPSI', subcategory: '', daftarMasalah: 'Konseling kontrasepsi bermasalah (ekstraksi IUD sulit)', kompetensi: 4 },
    { category: 'ULTRASONOGRAFI', subcategory: '', daftarMasalah: 'Saline infusion sonography', kompetensi: 4 },
    { category: 'ULTRASONOGRAFI', subcategory: 'Ultrasonografi pada TRB', daftarMasalah: 'Ultrasonografi pada TRB: Pemantauan perkembangan folikel, Pengukuran dan penilaian endometrium, Penilaian kehamilan awal pasca fertilisasi', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: '', daftarMasalah: 'Reseksi adenomyosis terkait fertilitas', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: '', daftarMasalah: 'Laparoskopi diagnostik pada kasus infertilitas', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: '', daftarMasalah: 'Laparoskopi salpingektomi (hidrosalping)', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: '', daftarMasalah: 'Laparoskopi kistektomi/ovarektomi (endometriosis denganinfertilitas)', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: '', daftarMasalah: 'Laparoskopi lisis adhesi dengan infertilitas', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: '', daftarMasalah: 'Laparoskopi oklusi tuba pada kasus hidrosalping pra IVF', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: '', daftarMasalah: 'Laparoskopi neosalpingostomy atau salpingoplasty', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: '', daftarMasalah: 'Ovarian drilling', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: '', daftarMasalah: 'Laparoskopi histerektomi (LAVH, LASH, dan TLH) dengan nyeri pelvik kronik', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: '', daftarMasalah: 'Laparoskopi miomektomi pada kasus infertilitas dan perdarahan uterus abnormal', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: '', daftarMasalah: 'Laparoskopi Deep infiltrating endometriosis', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: '', daftarMasalah: 'Histeroskopi diagnostik pada kasus infertilitas', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: '', daftarMasalah: 'Histeroskopi operatif dengan infertilitas', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: '', daftarMasalah: 'Menangani kasus medikolegal infertilitas', kompetensi: 4 },
    { category: 'GINEKOLOGI', subcategory: '', daftarMasalah: 'Melakukan audit manajemen infertilitas', kompetensi: 4 },
    { category: 'TEKNOLOGI REPRODUKSI BERBANTU', subcategory: '', daftarMasalah: 'Ovum pick up', kompetensi: 4 },
    { category: 'TEKNOLOGI REPRODUKSI BERBANTU', subcategory: '', daftarMasalah: 'Transfer embrio', kompetensi: 4 },
    { category: 'TEKNOLOGI REPRODUKSI BERBANTU', subcategory: '', daftarMasalah: 'USG folikel', kompetensi: 4 },
    { category: 'TEKNOLOGI REPRODUKSI BERBANTU', subcategory: '', daftarMasalah: 'Inseminasi intrauterin', kompetensi: 4 },
    { category: 'TEKNOLOGI REPRODUKSI BERBANTU', subcategory: '', daftarMasalah: 'Transfer embrio pasca simpan beku', kompetensi: 4 },
    { category: 'TEKNOLOGI REPRODUKSI BERBANTU', subcategory: '', daftarMasalah: 'Stimulasi ovarium', kompetensi: 4 },
    { category: 'TEKNOLOGI REPRODUKSI BERBANTU', subcategory: '', daftarMasalah: 'Penanganan OHSS', kompetensi: 4 }
];

let cplJumlahKasusData = {};

function escapeCPLHtml(value) {
    return String(value || '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
}

function loadCPLData() {
    try {
        cplJumlahKasusData = getUserStorage('cplJumlahKasusData', {});
    } catch (error) {
        cplJumlahKasusData = {};
    }

    renderCPLTable();
}

function saveCPLData() {
    setUserStorage('cplJumlahKasusData', cplJumlahKasusData);
}

function renderCPLTable() {
    const tbody = document.getElementById('cplTableBody');
    if (!tbody) return;

    tbody.innerHTML = '';

    let currentCategory = '';
    let currentSubcategory = '';

    cplCurriculumData.forEach((item, index) => {
        // Add category header row if category changes
        if (item.category !== currentCategory) {
            currentCategory = item.category;
            const categoryRow = document.createElement('tr');
            categoryRow.innerHTML = `
                <td colspan="4" style="border: 1px solid #ddd; padding: 8px; background: #000; color: #fff; font-weight: bold; text-align: left;">
                    ${escapeCPLHtml(currentCategory)}
                </td>
            `;
            tbody.appendChild(categoryRow);
        }

        // Add subcategory header row if subcategory exists and changes
        if (item.subcategory && item.subcategory !== currentSubcategory) {
            currentSubcategory = item.subcategory;
            const subcategoryRow = document.createElement('tr');
            subcategoryRow.innerHTML = `
                <td colspan="4" style="border: 1px solid #ddd; padding: 8px; background: #f5f5f5; font-style: italic; text-align: left;">
                    ${escapeCPLHtml(currentSubcategory)}
                </td>
            `;
            tbody.appendChild(subcategoryRow);
        } else if (!item.subcategory) {
            currentSubcategory = '';
        }

        // Add data row
        const tr = document.createElement('tr');
        const jumlahKasus = cplJumlahKasusData[index] || '';
        
        tr.innerHTML = `
            <td style="border: 1px solid #ddd; padding: 8px; text-align: center;">${index + 1}</td>
            <td style="border: 1px solid #ddd; padding: 8px;">
                ${escapeCPLHtml(item.daftarMasalah)}
            </td>
            <td style="border: 1px solid #ddd; padding: 8px; text-align: center;">
                ${item.kompetensi}
            </td>
            <td style="border: 1px solid #ddd; padding: 8px;">
                <input type="number" class="cpl-input" data-index="${index}" value="${escapeCPLHtml(jumlahKasus)}" style="width: 100%; border: 1px solid #ccc; padding: 6px; box-sizing: border-box; text-align: center;" min="0" placeholder="0">
            </td>
        `;
        tbody.appendChild(tr);
    });

    tbody.querySelectorAll('.cpl-input').forEach(input => {
        input.addEventListener('input', handleCPLInputChange);
        input.addEventListener('change', handleCPLInputChange);
    });
}

function handleCPLInputChange(event) {
    const index = Number(event.target.dataset.index);
    
    if (!Number.isNaN(index)) {
        cplJumlahKasusData[index] = event.target.value;
        saveCPLData();
    }
}

function resetCPLData() {
    if (confirm('Apakah Anda yakin ingin mereset semua data Jumlah Kasus? Data yang telah diinput akan dihapus.')) {
        cplJumlahKasusData = {};
        saveCPLData();
        renderCPLTable();
    }
}

function printCPLTable() {
    let rowsHtml = '';
    let currentCategory = '';
    let currentSubcategory = '';

    cplCurriculumData.forEach((item, index) => {
        // Add category header row if category changes
        if (item.category !== currentCategory) {
            currentCategory = item.category;
            rowsHtml += `
                <tr>
                    <td colspan="4" style="background: #000; color: #fff; font-weight: bold; text-align: left; padding: 8px;">
                        ${escapeCPLHtml(currentCategory)}
                    </td>
                </tr>
            `;
        }

        // Add subcategory header row if subcategory exists and changes
        if (item.subcategory && item.subcategory !== currentSubcategory) {
            currentSubcategory = item.subcategory;
            rowsHtml += `
                <tr>
                    <td colspan="4" style="background: #f5f5f5; font-style: italic; text-align: left; padding: 8px;">
                        ${escapeCPLHtml(currentSubcategory)}
                    </td>
                </tr>
            `;
        } else if (!item.subcategory) {
            currentSubcategory = '';
        }

        // Add data row
        const jumlahKasus = cplJumlahKasusData[index] || '';
        rowsHtml += `
            <tr>
                <td style="text-align: center;">${index + 1}</td>
                <td>${escapeCPLHtml(item.daftarMasalah)}</td>
                <td style="text-align: center;">${item.kompetensi}</td>
                <td style="text-align: center;">${escapeCPLHtml(jumlahKasus)}</td>
            </tr>
        `;
    });

    const printWindow = window.open('', '_blank');
    if (!printWindow) return;

    printWindow.document.write(`
        <html>
            <head>
                <title>Capaian Pembelajaran (CPL)</title>
                <style>
                    body { 
                        font-family: Arial, sans-serif; 
                        margin: 24px;
                    }
                    .header {
                        text-align: center;
                        margin-bottom: 20px;
                    }
                    .header h1 {
                        font-size: 14px;
                        margin: 4px 0;
                        font-weight: bold;
                        text-transform: uppercase;
                    }
                    .header h2 {
                        font-size: 12px;
                        margin: 8px 0 16px 0;
                        font-weight: bold;
                    }
                    table { 
                        width: 100%; 
                        border-collapse: collapse;
                        margin-top: 16px;
                    }
                    th, td { 
                        border: 1px solid #000; 
                        padding: 8px; 
                        text-align: left; 
                        font-size: 11px; 
                        vertical-align: top; 
                    }
                    th { 
                        background: #f2f2f2;
                        font-weight: bold;
                        text-align: center;
                    }
                    .text-center {
                        text-align: center;
                    }
                </style>
            </head>
            <body>
                <div class="header">
                    <h1>Kurikulum Pendidikan PPDS-2 Fertilitas Endokrinologi Reproduksi</h1>
                    <h1>Fakultas Kedokteran Universitas Sriwijaya</h1>
                    <h2>Capaian Kompetensi Berdasarkan Diagnosis dan Keterampilan Klinik</h2>
                </div>
                <table>
                    <thead>
                        <tr>
                            <th style="width: 60px;">No</th>
                            <th>Daftar Masalah</th>
                            <th style="width: 140px;">Kompetensi<br>SpOG (K)</th>
                            <th style="width: 110px;">Jumlah<br>Kasus</th>
                        </tr>
                    </thead>
                    <tbody>${rowsHtml}</tbody>
                </table>
            </body>
        </html>
    `);
    printWindow.document.close();
    printWindow.focus();
    printWindow.print();
}

// ========== FEMALE ENDOCRINOLOGY COMPETENCY ASSESSMENT ==========
const femaleEndoItems = [
    { category: 'INVESTIGATIONS', items: [
        'Neuroendocrine and anatomy and physiology'
    ]},
    { category: 'IMAGING', items: [
        'Pelvic ultrasound',
        'Pituitary MRI / CT',
        'Abdomino-pelvic MRI / CT'
    ]},
    { category: 'PITUITARY DISORDERS', items: [
        'Hypogonadotropic-hypogonadism'
    ]},
    { category: 'METABOLIC ENDOCRINE DISORDERS', items: [
        'Anorexia nervosa / exercise and lifestyle related disorders',
        'Pituitary adenoma',
        'Kalliman syndrome',
        'Hyperprolactinemia'
    ]}
];

let femaleEndoData = {};

function openFemaleEndocrinology() {
    showSection('female-endocrinology');
    loadFemaleEndoData();
}

function loadFemaleEndoData() {
    try {
        femaleEndoData = getUserStorage('femaleEndoData', {});
    } catch (error) {
        femaleEndoData = {};
    }

    renderFemaleEndoTable();
    
    // Load other fields
    const dateCommence = getUserStorage('femaleEndo_dateCommence');
    const dateCommenceEl = document.getElementById('femaleEndoDateCommence');
    if (dateCommence && dateCommenceEl) dateCommenceEl.value = dateCommence;
    
    const tutorName = getUserStorage('femaleEndo_tutorName');
    const tutorNameEl = document.getElementById('femaleEndoTutorName');
    if (tutorName && tutorNameEl) tutorNameEl.value = tutorName;
    
    const tutorSignature = getUserStorage('femaleEndo_tutorSignature');
    const tutorSignatureEl = document.getElementById('femaleEndoTutorSignature');
    if (tutorSignature && tutorSignatureEl) tutorSignatureEl.value = tutorSignature;
    
    const tutorDate = getUserStorage('femaleEndo_tutorDate');
    const tutorDateEl = document.getElementById('femaleEndoTutorDate');
    if (tutorDate && tutorDateEl) tutorDateEl.value = tutorDate;
    
    const traineeName = getUserStorage('femaleEndo_traineeName');
    const traineeNameEl = document.getElementById('femaleEndoTraineeName');
    if (traineeName && traineeNameEl) traineeNameEl.value = traineeName;
    
    const traineeSignature = getUserStorage('femaleEndo_traineeSignature');
    const traineeSignatureEl = document.getElementById('femaleEndoTraineeSignature');
    if (traineeSignature && traineeSignatureEl) traineeSignatureEl.value = traineeSignature;
    
    const traineeDate = getUserStorage('femaleEndo_traineeDate');
    const traineeDateEl = document.getElementById('femaleEndoTraineeDate');
    if (traineeDate && traineeDateEl) traineeDateEl.value = traineeDate;
}

function saveFemaleEndoData() {
    setUserStorage('femaleEndoData', femaleEndoData);
    setUserStorage('femaleEndo_dateCommence', document.getElementById('femaleEndoDateCommence').value);
    setUserStorage('femaleEndo_tutorName', document.getElementById('femaleEndoTutorName').value);
    setUserStorage('femaleEndo_tutorSignature', document.getElementById('femaleEndoTutorSignature').value);
    setUserStorage('femaleEndo_tutorDate', document.getElementById('femaleEndoTutorDate').value);
    setUserStorage('femaleEndo_traineeName', document.getElementById('femaleEndoTraineeName').value);
    setUserStorage('femaleEndo_traineeSignature', document.getElementById('femaleEndoTraineeSignature').value);
    setUserStorage('femaleEndo_traineeDate', document.getElementById('femaleEndoTraineeDate').value);
}

function renderFemaleEndoTable() {
    const tbody = document.getElementById('femaleEndoTableBody');
    if (!tbody) return;
    
    tbody.innerHTML = '';
    let rowNum = 1;

    femaleEndoItems.forEach((section) => {
        // Add category header
        const categoryRow = document.createElement('tr');
        categoryRow.innerHTML = `
            <td colspan="5" style="border: 1px solid #333; padding: 10px; background: #8B7355; color: #fff; font-weight: bold;">
                ${section.category}
            </td>
        `;
        tbody.appendChild(categoryRow);

        // Add items
        section.items.forEach((item) => {
            const dataKey = `item_${rowNum}`;
            const checked1 = femaleEndoData[`${dataKey}_1`] || '';
            const checked2 = femaleEndoData[`${dataKey}_2`] || '';
            const checked3 = femaleEndoData[`${dataKey}_3`] || '';
            const sign = femaleEndoData[`${dataKey}_sign`] || '';

            const row = document.createElement('tr');
            row.innerHTML = `
                <td style="border: 1px solid #333; padding: 10px; min-width: 300px;">
                    <span>${rowNum}</span>. ${item}
                </td>
                <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;">
                    <input type="checkbox" class="femaleendo-checkbox" data-key="${dataKey}_1" ${checked1 ? 'checked' : ''}>
                </td>
                <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;">
                    <input type="checkbox" class="femaleendo-checkbox" data-key="${dataKey}_2" ${checked2 ? 'checked' : ''}>
                </td>
                <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;">
                    <input type="checkbox" class="femaleendo-checkbox" data-key="${dataKey}_3" ${checked3 ? 'checked' : ''}>
                </td>
                <td style="border: 1px solid #333; padding: 10px; min-width: 200px; height: 60px;">
                    <textarea class="femaleendo-input" data-key="${dataKey}_sign" rows="3" style="width: 100%; border: none; padding: 6px; resize: none; font-size: 12px;">${sign}</textarea>
                </td>
            `;
            tbody.appendChild(row);
            rowNum++;
        });
    });

    // Add event listeners
    tbody.querySelectorAll('.femaleendo-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', handleFemaleEndoChange);
    });

    tbody.querySelectorAll('.femaleendo-input').forEach(input => {
        input.addEventListener('input', handleFemaleEndoChange);
    });
}

function handleFemaleEndoChange(event) {
    const key = event.target.dataset.key;
    
    if (event.target.type === 'checkbox') {
        femaleEndoData[key] = event.target.checked ? '1' : '';
    } else {
        femaleEndoData[key] = event.target.value;
    }
    
    saveFemaleEndoData();
}

function printFemaleEndocrinology() {
    let tableRows = '';
    let rowNum = 1;

    femaleEndoItems.forEach((section) => {
        // Add category header
        tableRows += `
            <tr>
                <td colspan="5" style="border: 1px solid #000; padding: 10px; background: #8B7355; color: #fff; font-weight: bold;">
                    ${section.category}
                </td>
            </tr>
        `;

        // Add items
        section.items.forEach((item) => {
            const dataKey = `item_${rowNum}`;
            const checked1 = femaleEndoData[`${dataKey}_1`] ? '☑' : '☐';
            const checked2 = femaleEndoData[`${dataKey}_2`] ? '☑' : '☐';
            const checked3 = femaleEndoData[`${dataKey}_3`] ? '☑' : '☐';
            const sign = femaleEndoData[`${dataKey}_sign`] || '';

            tableRows += `
                <tr>
                    <td style="border: 1px solid #000; padding: 10px;">${rowNum}. ${item}</td>
                    <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked1}</td>
                    <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked2}</td>
                    <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked3}</td>
                    <td style="border: 1px solid #000; padding: 10px; font-size: 11px; white-space: pre-wrap;">${sign}</td>
                </tr>
            `;
            rowNum++;
        });
    });

    const dateCommence = document.getElementById('femaleEndoDateCommence').value;
    const tutorName = document.getElementById('femaleEndoTutorName').value;
    const tutorSignature = document.getElementById('femaleEndoTutorSignature').value;
    const tutorDate = document.getElementById('femaleEndoTutorDate').value;
    const traineeName = document.getElementById('femaleEndoTraineeName').value;
    const traineeSignature = document.getElementById('femaleEndoTraineeSignature').value;
    const traineeDate = document.getElementById('femaleEndoTraineeDate').value;

    const printWindow = window.open('', '_blank');
    if (!printWindow) return;

    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
            <head>
                <title>Female Endocrinology - Competency Assessment</title>
                <style>
                    body {
                        font-family: Arial, sans-serif;
                        margin: 20px;
                    }
                    h1 {
                        text-align: center;
                        background: #4472C4;
                        color: white;
                        padding: 12px;
                        margin: 0 0 20px 0;
                    }
                    .date-field {
                        margin-bottom: 20px;
                        border: 1px solid #999;
                        padding: 10px;
                    }
                    .date-field span {
                        font-weight: bold;
                        display: inline-block;
                        width: 150px;
                    }
                    table {
                        width: 100%;
                        border-collapse: collapse;
                        margin-bottom: 20px;
                    }
                    th, td {
                        border: 1px solid #000;
                        padding: 8px;
                        text-align: left;
                        font-size: 11px;
                    }
                    th {
                        background: #ffd700;
                        font-weight: bold;
                    }
                    .signature-table th {
                        background: #f5f5f5;
                        font-weight: bold;
                    }
                    .signature-table td {
                        height: 60px;
                        vertical-align: top;
                        font-size: 10px;
                    }
                </style>
            </head>
            <body>
                <h1>FEMALE ENDOCRINOLOGY</h1>
                
                <div class="date-field">
                    <span>Date of commence:</span> <strong>${dateCommence}</strong>
                </div>

                <table>
                    <thead>
                        <tr style="background: #ffd700;">
                            <th colspan="5" style="text-align: center; background: #ffd700;">REPRODUCTIVE ENDOCRINOLOGY OUTPATIENT CLINIC</th>
                        </tr>
                        <tr style="background: #ffd700;">
                            <th style="width: 45%;">TARGET REQUIRING SIGNATURE</th>
                            <th colspan="3" style="text-align: center;">EXPECTED COMPETENCE LEVEL</th>
                            <th style="text-align: center;">CERTIFICATION</th>
                        </tr>
                        <tr style="background: #ffd700;">
                            <th></th>
                            <th style="text-align: center;">1</th>
                            <th style="text-align: center;">2</th>
                            <th style="text-align: center;">3</th>
                            <th style="text-align: center;">Sign & Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${tableRows}
                    </tbody>
                </table>

                <table class="signature-table">
                    <thead>
                        <tr>
                            <th colspan="3" style="text-align: center;">SIGNATURE TO CONFIRM COMPLETION</th>
                        </tr>
                        <tr>
                            <th>Name of Academic Tutor</th>
                            <th>Signature of Academic Tutor</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>${tutorName}</td>
                            <td style="white-space: pre-wrap; font-size: 10px;">${tutorSignature}</td>
                            <td>${tutorDate}</td>
                        </tr>
                        <tr style="background: #f5f5f5;">
                            <th>Name of Trainee</th>
                            <th>Signature of Trainee</th>
                            <th>Date</th>
                        </tr>
                        <tr>
                            <td>${traineeName}</td>
                            <td style="white-space: pre-wrap; font-size: 10px;">${traineeSignature}</td>
                            <td>${traineeDate}</td>
                        </tr>
                    </tbody>
                </table>
            </body>
        </html>
    `);
    printWindow.document.close();
    printWindow.focus();
    printWindow.print();
}

document.addEventListener('DOMContentLoaded', function() {
    // Auto-save form fields for Female Endocrinology
    const formInputs = ['femaleEndoDateCommence', 'femaleEndoTutorName', 'femaleEndoTutorSignature', 'femaleEndoTutorDate', 'femaleEndoTraineeName', 'femaleEndoTraineeSignature', 'femaleEndoTraineeDate'];
    formInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', saveFemaleEndoData);
            element.addEventListener('change', saveFemaleEndoData);
        }
    });
});

// ========== THE OVARY AND PCOS COMPETENCY ASSESSMENT ==========
const ovaryPCOSItems = [
    'Ovarian anatomy and physiology',
    'Diagnosis of PCOS',
    'Ultrasound imaging of PCO',
    'Management of obesity',
    'Dietary advice',
    'Management of anovulation /oligoovulation',
    'Ovulation induction in PCOS',
    'Anti-estrogens',
    'Metformin / insulin sensitizers',
    'Gonadotrophin therapy',
    'Ovarian diathermy',
    'Aromatase inhibitors',
    'Management of hyperandrogenism (hirsutism / acne / alopecia)'
];

let ovaryPCOSData = {};

function openOvaryPCOS() {
    showSection('ovary-pcos');
    loadOvaryPCOSData();
}

function loadOvaryPCOSData() {
    try {
        ovaryPCOSData = getUserStorage('ovaryPCOSData', {});
    } catch (error) {
        ovaryPCOSData = {};
    }

    renderOvaryPCOSTable();
    
    // Load other fields
    const dateCommence = getUserStorage('ovaryPCOS_dateCommence');
    if (dateCommence) document.getElementById('ovaryPCOSDateCommence').value = dateCommence;
    
    const tutorName = getUserStorage('ovaryPCOS_tutorName');
    if (tutorName) document.getElementById('ovaryPCOSTutorName').value = tutorName;
    
    const tutorSignature = getUserStorage('ovaryPCOS_tutorSignature');
    if (tutorSignature) document.getElementById('ovaryPCOSTutorSignature').value = tutorSignature;
    
    const tutorDate = getUserStorage('ovaryPCOS_tutorDate');
    if (tutorDate) document.getElementById('ovaryPCOSTutorDate').value = tutorDate;
    
    const traineeName = getUserStorage('ovaryPCOS_traineeName');
    if (traineeName) document.getElementById('ovaryPCOSTraineeName').value = traineeName;
    
    const traineeSignature = getUserStorage('ovaryPCOS_traineeSignature');
    if (traineeSignature) document.getElementById('ovaryPCOSTraineeSignature').value = traineeSignature;
    
    const traineeDate = getUserStorage('ovaryPCOS_traineeDate');
    if (traineeDate) document.getElementById('ovaryPCOSTraineeDate').value = traineeDate;
}

function saveOvaryPCOSData() {
    setUserStorage('ovaryPCOSData', ovaryPCOSData);
    setUserStorage('ovaryPCOS_dateCommence', document.getElementById('ovaryPCOSDateCommence').value);
    setUserStorage('ovaryPCOS_tutorName', document.getElementById('ovaryPCOSTutorName').value);
    setUserStorage('ovaryPCOS_tutorSignature', document.getElementById('ovaryPCOSTutorSignature').value);
    setUserStorage('ovaryPCOS_tutorDate', document.getElementById('ovaryPCOSTutorDate').value);
    setUserStorage('ovaryPCOS_traineeName', document.getElementById('ovaryPCOSTraineeName').value);
    setUserStorage('ovaryPCOS_traineeSignature', document.getElementById('ovaryPCOSTraineeSignature').value);
    setUserStorage('ovaryPCOS_traineeDate', document.getElementById('ovaryPCOSTraineeDate').value);
}

function renderOvaryPCOSTable() {
    const tbody = document.getElementById('ovaryPCOSTableBody');
    if (!tbody) return;
    
    tbody.innerHTML = '';

    ovaryPCOSItems.forEach((item, index) => {
        const rowNum = index + 1;
        const dataKey = `item_${rowNum}`;
        const checked1 = ovaryPCOSData[`${dataKey}_1`] || '';
        const checked2 = ovaryPCOSData[`${dataKey}_2`] || '';
        const checked3 = ovaryPCOSData[`${dataKey}_3`] || '';
        const sign = ovaryPCOSData[`${dataKey}_sign`] || '';

        const row = document.createElement('tr');
        row.innerHTML = `
            <td style="border: 1px solid #333; padding: 10px; min-width: 300px;">
                <span>${rowNum}</span>. ${item}
            </td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;">
                <input type="checkbox" class="ovarypcos-checkbox" data-key="${dataKey}_1" ${checked1 ? 'checked' : ''}>
            </td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;">
                <input type="checkbox" class="ovarypcos-checkbox" data-key="${dataKey}_2" ${checked2 ? 'checked' : ''}>
            </td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;">
                <input type="checkbox" class="ovarypcos-checkbox" data-key="${dataKey}_3" ${checked3 ? 'checked' : ''}>
            </td>
            <td style="border: 1px solid #333; padding: 10px; min-width: 200px; height: 60px;">
                <textarea class="ovarypcos-input" data-key="${dataKey}_sign" rows="3" style="width: 100%; border: none; padding: 6px; resize: none; font-size: 12px;">${sign}</textarea>
            </td>
        `;
        tbody.appendChild(row);
    });

    // Add event listeners
    tbody.querySelectorAll('.ovarypcos-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', handleOvaryPCOSChange);
    });

    tbody.querySelectorAll('.ovarypcos-input').forEach(input => {
        input.addEventListener('input', handleOvaryPCOSChange);
    });
}

function handleOvaryPCOSChange(event) {
    const key = event.target.dataset.key;
    
    if (event.target.type === 'checkbox') {
        ovaryPCOSData[key] = event.target.checked ? '1' : '';
    } else {
        ovaryPCOSData[key] = event.target.value;
    }
    
    saveOvaryPCOSData();
}

function printOvaryPCOS() {
    let tableRows = '';

    ovaryPCOSItems.forEach((item, index) => {
        const rowNum = index + 1;
        const dataKey = `item_${rowNum}`;
        const checked1 = ovaryPCOSData[`${dataKey}_1`] ? '☑' : '☐';
        const checked2 = ovaryPCOSData[`${dataKey}_2`] ? '☑' : '☐';
        const checked3 = ovaryPCOSData[`${dataKey}_3`] ? '☑' : '☐';
        const sign = ovaryPCOSData[`${dataKey}_sign`] || '';

        tableRows += `
            <tr>
                <td style="border: 1px solid #000; padding: 10px;">${rowNum}. ${item}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked1}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked2}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked3}</td>
                <td style="border: 1px solid #000; padding: 10px; font-size: 11px; white-space: pre-wrap;">${sign}</td>
            </tr>
        `;
    });

    const dateCommence = document.getElementById('ovaryPCOSDateCommence').value;
    const tutorName = document.getElementById('ovaryPCOSTutorName').value;
    const tutorSignature = document.getElementById('ovaryPCOSTutorSignature').value;
    const tutorDate = document.getElementById('ovaryPCOSTutorDate').value;
    const traineeName = document.getElementById('ovaryPCOSTraineeName').value;
    const traineeSignature = document.getElementById('ovaryPCOSTraineeSignature').value;
    const traineeDate = document.getElementById('ovaryPCOSTraineeDate').value;

    const printWindow = window.open('', '_blank');
    if (!printWindow) return;

    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
            <head>
                <title>The Ovary and PCOS - Competency Assessment</title>
                <style>
                    body {
                        font-family: Arial, sans-serif;
                        margin: 20px;
                    }
                    h1 {
                        text-align: center;
                        background: #4472C4;
                        color: white;
                        padding: 12px;
                        margin: 0 0 20px 0;
                    }
                    .date-field {
                        margin-bottom: 20px;
                        border: 1px solid #999;
                        padding: 10px;
                    }
                    .date-field span {
                        font-weight: bold;
                        display: inline-block;
                        width: 150px;
                    }
                    table {
                        width: 100%;
                        border-collapse: collapse;
                        margin-bottom: 20px;
                    }
                    th, td {
                        border: 1px solid #000;
                        padding: 8px;
                        text-align: left;
                        font-size: 11px;
                    }
                    th {
                        background: #ffd700;
                        font-weight: bold;
                    }
                    .signature-table th {
                        background: #f5f5f5;
                        font-weight: bold;
                    }
                    .signature-table td {
                        height: 60px;
                        vertical-align: top;
                        font-size: 10px;
                    }
                </style>
            </head>
            <body>
                <h1>THE OVARY AND POLICYSTIC OVARY SYNDROME</h1>
                
                <div class="date-field">
                    <span>Date of commence:</span> <strong>${dateCommence}</strong>
                </div>

                <table>
                    <thead>
                        <tr style="background: #ffd700;">
                            <th colspan="5" style="text-align: center; background: #ffd700;">REPRODUCTIVE ENDOCRINOLOGY OUTPATIENT CLINIC</th>
                        </tr>
                        <tr style="background: #ffd700;">
                            <th style="width: 45%;">TARGET REQUIRING SIGNATURE</th>
                            <th colspan="3" style="text-align: center;">EXPECTED COMPETENCE LEVEL</th>
                            <th style="text-align: center;">CERTIFICATION</th>
                        </tr>
                        <tr style="background: #ffd700;">
                            <th></th>
                            <th style="text-align: center;">1</th>
                            <th style="text-align: center;">2</th>
                            <th style="text-align: center;">3</th>
                            <th style="text-align: center;">Sign & Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${tableRows}
                    </tbody>
                </table>

                <table class="signature-table">
                    <thead>
                        <tr>
                            <th colspan="3" style="text-align: center;">SIGNATURE TO CONFIRM COMPLETION</th>
                        </tr>
                        <tr>
                            <th>Name of Academic Tutor</th>
                            <th>Signature of Academic Tutor</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>${tutorName}</td>
                            <td style="white-space: pre-wrap; font-size: 10px;">${tutorSignature}</td>
                            <td>${tutorDate}</td>
                        </tr>
                        <tr style="background: #f5f5f5;">
                            <th>Name of Trainee</th>
                            <th>Signature of Trainee</th>
                            <th>Date</th>
                        </tr>
                        <tr>
                            <td>${traineeName}</td>
                            <td style="white-space: pre-wrap; font-size: 10px;">${traineeSignature}</td>
                            <td>${traineeDate}</td>
                        </tr>
                    </tbody>
                </table>
            </body>
        </html>
    `);
    printWindow.document.close();
    printWindow.focus();
    printWindow.print();
}

document.addEventListener('DOMContentLoaded', function() {
    // Auto-save form fields for Ovary and PCOS
    const formInputs = ['ovaryPCOSDateCommence', 'ovaryPCOSTutorName', 'ovaryPCOSTutorSignature', 'ovaryPCOSTutorDate', 'ovaryPCOSTraineeName', 'ovaryPCOSTraineeSignature', 'ovaryPCOSTraineeDate'];
    formInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', saveOvaryPCOSData);
            element.addEventListener('change', saveOvaryPCOSData);
        }
    });
});

const subfertilityItems = [
    { category: 'PATHOLOGY/IMMUNOLOGY/ANATOMY', items: [
        'Uterus, tubes, ovaries',
        'Adrenal / Thyroid',
        'Pituitary',
        'Testis'
    ]},
    { category: 'INVESTIGATIONS', items: [
        'History from subfertile couple',
        'Examination of subfertile couple',
        'Interpret semen analysis',
        'Interpret endocrine profile'
    ]},
    { category: 'UTERINE AND TUBAL IMAGING', items: [
        'HSG',
        'Saline sonohysterography',
        'CT / MRI'
    ]},
    { category: 'DISCUSS WITH COUPLE AND COUNSEL TOWARDS APPROPRIATE TREATMENT', items: [
        'Ovulation induction; anti-estrogens',
        'IUI natural cycle',
        'Psychosexual problems'
    ]}
];

let subfertilityData = {};

function openSubfertilityI() {
    showSection('subfertility-i');
    loadSubfertilityData();
}

function loadSubfertilityData() {
    try {
        subfertilityData = getUserStorage('subfertilityData', {});
    } catch (error) {
        subfertilityData = {};
    }

    renderSubfertilityTable();
    
    // Load other fields
    const dateCommence = getUserStorage('subfertility_dateCommence');
    if (dateCommence) document.getElementById('subfertilityDateCommence').value = dateCommence;
    
    const tutorName = getUserStorage('subfertility_tutorName');
    if (tutorName) document.getElementById('tutorName').value = tutorName;
    
    const tutorSignature = getUserStorage('subfertility_tutorSignature');
    if (tutorSignature) document.getElementById('tutorSignature').value = tutorSignature;
    
    const tutorDate = getUserStorage('subfertility_tutorDate');
    if (tutorDate) document.getElementById('tutorDate').value = tutorDate;
    
    const traineeName = getUserStorage('subfertility_traineeName');
    if (traineeName) document.getElementById('traineeName').value = traineeName;
    
    const traineeSignature = getUserStorage('subfertility_traineeSignature');
    if (traineeSignature) document.getElementById('traineeSignature').value = traineeSignature;
    
    const traineeDate = getUserStorage('subfertility_traineeDate');
    if (traineeDate) document.getElementById('traineeDate').value = traineeDate;
}

function saveSubfertilityData() {
    setUserStorage('subfertilityData', subfertilityData);
    setUserStorage('subfertility_dateCommence', document.getElementById('subfertilityDateCommence').value);
    setUserStorage('subfertility_tutorName', document.getElementById('tutorName').value);
    setUserStorage('subfertility_tutorSignature', document.getElementById('tutorSignature').value);
    setUserStorage('subfertility_tutorDate', document.getElementById('tutorDate').value);
    setUserStorage('subfertility_traineeName', document.getElementById('traineeName').value);
    setUserStorage('subfertility_traineeSignature', document.getElementById('traineeSignature').value);
    setUserStorage('subfertility_traineeDate', document.getElementById('traineeDate').value);
}

function renderSubfertilityTable() {
    const tbody = document.getElementById('subfertilityTableBody');
    if (!tbody) return;
    
    tbody.innerHTML = '';
    let rowNum = 1;

    subfertilityItems.forEach((section) => {
        // Add category header
        const categoryRow = document.createElement('tr');
        categoryRow.innerHTML = `
            <td colspan="5" style="border: 1px solid #333; padding: 10px; background: #8B7355; color: #fff; font-weight: bold;">
                ${section.category}
            </td>
        `;
        tbody.appendChild(categoryRow);

        // Add items
        section.items.forEach((item) => {
            const dataKey = `item_${rowNum}`;
            const checked1 = subfertilityData[`${dataKey}_1`] || '';
            const checked2 = subfertilityData[`${dataKey}_2`] || '';
            const checked3 = subfertilityData[`${dataKey}_3`] || '';
            const sign = subfertilityData[`${dataKey}_sign`] || '';

            const row = document.createElement('tr');
            row.innerHTML = `
                <td style="border: 1px solid #333; padding: 10px; min-width: 300px;">
                    <span>${rowNum}</span>. ${item}
                </td>
                <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;">
                    <input type="checkbox" class="subfertility-checkbox" data-key="${dataKey}_1" ${checked1 ? 'checked' : ''}>
                </td>
                <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;">
                    <input type="checkbox" class="subfertility-checkbox" data-key="${dataKey}_2" ${checked2 ? 'checked' : ''}>
                </td>
                <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;">
                    <input type="checkbox" class="subfertility-checkbox" data-key="${dataKey}_3" ${checked3 ? 'checked' : ''}>
                </td>
                <td style="border: 1px solid #333; padding: 10px; min-width: 200px; height: 60px;">
                    <textarea class="subfertility-input" data-key="${dataKey}_sign" rows="3" style="width: 100%; border: none; padding: 6px; resize: none; font-size: 12px;">${sign}</textarea>
                </td>
            `;
            tbody.appendChild(row);
            rowNum++;
        });
    });

    // Add event listeners
    tbody.querySelectorAll('.subfertility-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', handleSubfertilityChange);
    });

    tbody.querySelectorAll('.subfertility-input').forEach(input => {
        input.addEventListener('input', handleSubfertilityChange);
    });
}

function handleSubfertilityChange(event) {
    const key = event.target.dataset.key;
    
    if (event.target.type === 'checkbox') {
        subfertilityData[key] = event.target.checked ? '1' : '';
    } else {
        subfertilityData[key] = event.target.value;
    }
    
    saveSubfertilityData();
}

function printSubfertilityI() {
    let tableRows = '';
    let rowNum = 1;

    subfertilityItems.forEach((section) => {
        // Add category header
        tableRows += `
            <tr>
                <td colspan="5" style="border: 1px solid #000; padding: 10px; background: #8B7355; color: #fff; font-weight: bold;">
                    ${section.category}
                </td>
            </tr>
        `;

        // Add items
        section.items.forEach((item) => {
            const dataKey = `item_${rowNum}`;
            const checked1 = subfertilityData[`${dataKey}_1`] ? '☑' : '☐';
            const checked2 = subfertilityData[`${dataKey}_2`] ? '☑' : '☐';
            const checked3 = subfertilityData[`${dataKey}_3`] ? '☑' : '☐';
            const sign = subfertilityData[`${dataKey}_sign`] || '';

            tableRows += `
                <tr>
                    <td style="border: 1px solid #000; padding: 10px;">${rowNum}. ${item}</td>
                    <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked1}</td>
                    <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked2}</td>
                    <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked3}</td>
                    <td style="border: 1px solid #000; padding: 10px; font-size: 11px; white-space: pre-wrap;">${sign}</td>
                </tr>
            `;
            rowNum++;
        });
    });

    const dateCommence = document.getElementById('subfertilityDateCommence').value;
    const tutorName = document.getElementById('tutorName').value;
    const tutorSignature = document.getElementById('tutorSignature').value;
    const tutorDate = document.getElementById('tutorDate').value;
    const traineeName = document.getElementById('traineeName').value;
    const traineeSignature = document.getElementById('traineeSignature').value;
    const traineeDate = document.getElementById('traineeDate').value;

    const printWindow = window.open('', '_blank');
    if (!printWindow) return;

    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
            <head>
                <title>Subfertility I - Competency Assessment</title>
                <style>
                    body {
                        font-family: Arial, sans-serif;
                        margin: 20px;
                    }
                    h1 {
                        text-align: center;
                        background: #4472C4;
                        color: white;
                        padding: 12px;
                        margin: 0 0 20px 0;
                    }
                    .date-field {
                        margin-bottom: 20px;
                        border: 1px solid #999;
                        padding: 10px;
                    }
                    .date-field span {
                        font-weight: bold;
                        display: inline-block;
                        width: 150px;
                    }
                    table {
                        width: 100%;
                        border-collapse: collapse;
                        margin-bottom: 20px;
                    }
                    th, td {
                        border: 1px solid #000;
                        padding: 8px;
                        text-align: left;
                        font-size: 11px;
                    }
                    th {
                        background: #ffd700;
                        font-weight: bold;
                    }
                    .signature-table th {
                        background: #f5f5f5;
                        font-weight: bold;
                    }
                    .signature-table td {
                        height: 60px;
                        vertical-align: top;
                        font-size: 10px;
                    }
                </style>
            </head>
            <body>
                <h1>SUBFERTILITY I</h1>
                
                <div class="date-field">
                    <span>Date of commence:</span> <strong>${dateCommence}</strong>
                </div>

                <table>
                    <thead>
                        <tr style="background: #ffd700;">
                            <th colspan="5" style="text-align: center; background: #ffd700;">REPRODUCTIVE ENDOCRINOLOGY OUTPATIENT CLINIC</th>
                        </tr>
                        <tr style="background: #ffd700;">
                            <th style="width: 45%;">TARGET REQUIRING SIGNATURE</th>
                            <th colspan="3" style="text-align: center;">EXPECTED COMPETENCE LEVEL</th>
                            <th style="text-align: center;">CERTIFICATION</th>
                        </tr>
                        <tr style="background: #ffd700;">
                            <th></th>
                            <th style="text-align: center;">1</th>
                            <th style="text-align: center;">2</th>
                            <th style="text-align: center;">3</th>
                            <th style="text-align: center;">Sign & Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${tableRows}
                    </tbody>
                </table>

                <table class="signature-table">
                    <thead>
                        <tr>
                            <th colspan="3" style="text-align: center;">SIGNATURE TO CONFIRM COMPLETION</th>
                        </tr>
                        <tr>
                            <th>Name of Academic Tutor</th>
                            <th>Signature of Academic Tutor</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>${tutorName}</td>
                            <td style="white-space: pre-wrap; font-size: 10px;">${tutorSignature}</td>
                            <td>${tutorDate}</td>
                        </tr>
                        <tr style="background: #f5f5f5;">
                            <th>Name of Trainee</th>
                            <th>Signature of Trainee</th>
                            <th>Date</th>
                        </tr>
                        <tr>
                            <td>${traineeName}</td>
                            <td style="white-space: pre-wrap; font-size: 10px;">${traineeSignature}</td>
                            <td>${traineeDate}</td>
                        </tr>
                    </tbody>
                </table>
            </body>
        </html>
    `);
    printWindow.document.close();
    printWindow.focus();
    printWindow.print();
}

document.addEventListener('DOMContentLoaded', function() {
    // Auto-save form fields
    const formInputs = ['subfertilityDateCommence', 'tutorName', 'tutorSignature', 'tutorDate', 'traineeName', 'traineeSignature', 'traineeDate'];
    formInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', saveSubfertilityData);
            element.addEventListener('change', saveSubfertilityData);
        }
    });
});

// ========== HORMONAL CONTRACEPTION COMPETENCY ASSESSMENT ==========
const hormonalContraItems = [
    'Combined oral contraceptive pill',
    'Progestin only pill',
    'Depot',
    'Implants',
    'Intra-uterine contraceptive devices'
];

let hormonalContraData = {};

function openHormonalContraception() {
    showSection('hormonal-contraception');
    loadHormonalContraData();
}

function loadHormonalContraData() {
    try {
        hormonalContraData = getUserStorage('hormonalContraData', {});
    } catch (error) {
        hormonalContraData = {};
    }

    renderHormonalContraTable();
    
    // Load other fields
    const dateCommence = getUserStorage('hormonalContra_dateCommence');
    if (dateCommence) document.getElementById('hormonalContraDateCommence').value = dateCommence;
    
    const tutorName = getUserStorage('hormonalContra_tutorName');
    if (tutorName) document.getElementById('hormonalContraTutorName').value = tutorName;
    
    const tutorSignature = getUserStorage('hormonalContra_tutorSignature');
    if (tutorSignature) document.getElementById('hormonalContraTutorSignature').value = tutorSignature;
    
    const tutorDate = getUserStorage('hormonalContra_tutorDate');
    if (tutorDate) document.getElementById('hormonalContraTutorDate').value = tutorDate;
    
    const traineeName = getUserStorage('hormonalContra_traineeName');
    if (traineeName) document.getElementById('hormonalContraTraineeName').value = traineeName;
    
    const traineeSignature = getUserStorage('hormonalContra_traineeSignature');
    if (traineeSignature) document.getElementById('hormonalContraTraineeSignature').value = traineeSignature;
    
    const traineeDate = getUserStorage('hormonalContra_traineeDate');
    if (traineeDate) document.getElementById('hormonalContraTraineeDate').value = traineeDate;
}

function saveHormonalContraData() {
    setUserStorage('hormonalContraData', hormonalContraData);
    setUserStorage('hormonalContra_dateCommence', document.getElementById('hormonalContraDateCommence').value);
    setUserStorage('hormonalContra_tutorName', document.getElementById('hormonalContraTutorName').value);
    setUserStorage('hormonalContra_tutorSignature', document.getElementById('hormonalContraTutorSignature').value);
    setUserStorage('hormonalContra_tutorDate', document.getElementById('hormonalContraTutorDate').value);
    setUserStorage('hormonalContra_traineeName', document.getElementById('hormonalContraTraineeName').value);
    setUserStorage('hormonalContra_traineeSignature', document.getElementById('hormonalContraTraineeSignature').value);
    setUserStorage('hormonalContra_traineeDate', document.getElementById('hormonalContraTraineeDate').value);
}

function renderHormonalContraTable() {
    const tbody = document.getElementById('hormonalContraTableBody');
    if (!tbody) return;
    
    tbody.innerHTML = '';

    // Add category header
    const categoryRow = document.createElement('tr');
    categoryRow.innerHTML = `
        <td colspan="5" style="border: 1px solid #333; padding: 10px; background: #8B7355; color: white; font-weight: bold; text-align: left;">
            CONTRACEPTIVE MANAGEMENT
        </td>
    `;
    tbody.appendChild(categoryRow);

    hormonalContraItems.forEach((item, index) => {
        const rowNum = index + 1;
        const dataKey = `item_${rowNum}`;
        const checked1 = hormonalContraData[`${dataKey}_1`] || '';
        const checked2 = hormonalContraData[`${dataKey}_2`] || '';
        const checked3 = hormonalContraData[`${dataKey}_3`] || '';
        const sign = hormonalContraData[`${dataKey}_sign`] || '';

        const row = document.createElement('tr');
        row.innerHTML = `
            <td style="border: 1px solid #333; padding: 10px; min-width: 300px;">
                <span>${rowNum}</span>. ${item}
            </td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;">
                <input type="checkbox" class="hormonalcontra-checkbox" data-key="${dataKey}_1" ${checked1 ? 'checked' : ''}>
            </td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;">
                <input type="checkbox" class="hormonalcontra-checkbox" data-key="${dataKey}_2" ${checked2 ? 'checked' : ''}>
            </td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;">
                <input type="checkbox" class="hormonalcontra-checkbox" data-key="${dataKey}_3" ${checked3 ? 'checked' : ''}>
            </td>
            <td style="border: 1px solid #333; padding: 10px; min-width: 200px; height: 60px;">
                <textarea class="hormonalcontra-input" data-key="${dataKey}_sign" rows="3" style="width: 100%; border: none; padding: 6px; resize: none; font-size: 12px;">${sign}</textarea>
            </td>
        `;
        tbody.appendChild(row);
    });

    // Add event listeners
    tbody.querySelectorAll('.hormonalcontra-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', handleHormonalContraChange);
    });

    tbody.querySelectorAll('.hormonalcontra-input').forEach(input => {
        input.addEventListener('input', handleHormonalContraChange);
    });
}

function handleHormonalContraChange(event) {
    const key = event.target.dataset.key;
    
    if (event.target.type === 'checkbox') {
        hormonalContraData[key] = event.target.checked ? '1' : '';
    } else {
        hormonalContraData[key] = event.target.value;
    }
    
    saveHormonalContraData();
}

function printHormonalContraception() {
    let tableRows = '';

    // Add category header
    tableRows += `
        <tr>
            <td colspan="5" style="border: 1px solid #000; padding: 10px; background: #8B7355; color: white; font-weight: bold;">CONTRACEPTIVE MANAGEMENT</td>
        </tr>
    `;

    hormonalContraItems.forEach((item, index) => {
        const rowNum = index + 1;
        const dataKey = `item_${rowNum}`;
        const checked1 = hormonalContraData[`${dataKey}_1`] ? '☑' : '☐';
        const checked2 = hormonalContraData[`${dataKey}_2`] ? '☑' : '☐';
        const checked3 = hormonalContraData[`${dataKey}_3`] ? '☑' : '☐';
        const sign = hormonalContraData[`${dataKey}_sign`] || '';

        tableRows += `
            <tr>
                <td style="border: 1px solid #000; padding: 10px;">${rowNum}. ${item}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked1}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked2}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked3}</td>
                <td style="border: 1px solid #000; padding: 10px; font-size: 11px; white-space: pre-wrap;">${sign}</td>
            </tr>
        `;
    });

    const dateCommence = document.getElementById('hormonalContraDateCommence').value;
    const tutorName = document.getElementById('hormonalContraTutorName').value;
    const tutorSignature = document.getElementById('hormonalContraTutorSignature').value;
    const tutorDate = document.getElementById('hormonalContraTutorDate').value;
    const traineeName = document.getElementById('hormonalContraTraineeName').value;
    const traineeSignature = document.getElementById('hormonalContraTraineeSignature').value;
    const traineeDate = document.getElementById('hormonalContraTraineeDate').value;

    const printWindow = window.open('', '_blank');
    if (!printWindow) return;

    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
            <head>
                <title>Hormonal Contraception - Competency Assessment</title>
                <style>
                    body {
                        font-family: Arial, sans-serif;
                        margin: 20px;
                    }
                    h1 {
                        text-align: center;
                        background: #4472C4;
                        color: white;
                        padding: 12px;
                        margin: 0 0 20px 0;
                    }
                    .date-field {
                        margin-bottom: 20px;
                        border: 1px solid #999;
                        padding: 10px;
                    }
                    .date-field span {
                        font-weight: bold;
                        display: inline-block;
                        width: 150px;
                    }
                    table {
                        width: 100%;
                        border-collapse: collapse;
                        margin-bottom: 20px;
                    }
                    th, td {
                        border: 1px solid #000;
                        padding: 8px;
                        text-align: left;
                        font-size: 11px;
                    }
                    th {
                        background: #ffd700;
                        font-weight: bold;
                    }
                    .signature-table th {
                        background: #f5f5f5;
                        font-weight: bold;
                    }
                    .signature-table td {
                        height: 60px;
                        vertical-align: top;
                        font-size: 10px;
                    }
                </style>
            </head>
            <body>
                <h1>HORMONAL CONTRACEPTION</h1>
                
                <div class="date-field">
                    <span>Date of commence:</span> <strong>${dateCommence}</strong>
                </div>

                <table>
                    <thead>
                        <tr style="background: #ffd700;">
                            <th colspan="5" style="text-align: center; background: #ffd700;">REPRODUCTIVE ENDOCRINOLOGY OUTPATIENT CLINIC</th>
                        </tr>
                        <tr style="background: #ffd700;">
                            <th style="width: 45%;">TARGET REQUIRING SIGNATURE</th>
                            <th colspan="3" style="text-align: center;">EXPECTED COMPETENCE LEVEL</th>
                            <th style="text-align: center;">CERTIFICATION</th>
                        </tr>
                        <tr style="background: #ffd700;">
                            <th></th>
                            <th style="text-align: center;">1</th>
                            <th style="text-align: center;">2</th>
                            <th style="text-align: center;">3</th>
                            <th style="text-align: center;">Sign & Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${tableRows}
                    </tbody>
                </table>

                <table class="signature-table">
                    <thead>
                        <tr>
                            <th colspan="3" style="text-align: center;">SIGNATURE TO CONFIRM COMPLETION</th>
                        </tr>
                        <tr>
                            <th>Name of Academic Tutor</th>
                            <th>Signature of Academic Tutor</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>${tutorName}</td>
                            <td style="white-space: pre-wrap; font-size: 10px;">${tutorSignature}</td>
                            <td>${tutorDate}</td>
                        </tr>
                        <tr style="background: #f5f5f5;">
                            <th>Name of Trainee</th>
                            <th>Signature of Trainee</th>
                            <th>Date</th>
                        </tr>
                        <tr>
                            <td>${traineeName}</td>
                            <td style="white-space: pre-wrap; font-size: 10px;">${traineeSignature}</td>
                            <td>${traineeDate}</td>
                        </tr>
                    </tbody>
                </table>
            </body>
        </html>
    `);

    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => {
        printWindow.print();
    }, 250);
}

// Load Hormonal Contraception data when document is ready
document.addEventListener('DOMContentLoaded', function() {
    loadHormonalContraData();
    
    // Auto-save form fields for Hormonal Contraception
    const formInputs = ['hormonalContraDateCommence', 'hormonalContraTutorName', 'hormonalContraTutorSignature', 'hormonalContraTutorDate', 'hormonalContraTraineeName', 'hormonalContraTraineeSignature', 'hormonalContraTraineeDate'];
    formInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', saveHormonalContraData);
            element.addEventListener('change', saveHormonalContraData);
        }
    });
});

// ========== EARLY PREGNANCY PROBLEMS COMPETENCY ASSESSMENT ==========
const earlyPregItems = [
    'History and examination',
    'Organize appropriate investigations',
    'Interpret endocrine assessment',
    'Interpret immunological assessment',
    'Formulate management plan',
    'Liaise with colleagues in other disciplines'
];

let earlyPregData = {};

function openEarlyPregnancyProblems() {
    showSection('early-pregnancy-problems');
    loadEarlyPregData();
}

function loadEarlyPregData() {
    try {
        const saved = JSON.parse(localStorage.getItem('earlyPregData'));
        earlyPregData = saved || {};
    } catch (error) {
        earlyPregData = {};
    }

    renderEarlyPregTable();
    
    // Load other fields
    const dateCommence = localStorage.getItem('earlyPreg_dateCommence');
    if (dateCommence) document.getElementById('earlyPregDateCommence').value = dateCommence;
    
    const tutorName = localStorage.getItem('earlyPreg_tutorName');
    if (tutorName) document.getElementById('earlyPregTutorName').value = tutorName;
    
    const tutorSignature = localStorage.getItem('earlyPreg_tutorSignature');
    if (tutorSignature) document.getElementById('earlyPregTutorSignature').value = tutorSignature;
    
    const tutorDate = localStorage.getItem('earlyPreg_tutorDate');
    if (tutorDate) document.getElementById('earlyPregTutorDate').value = tutorDate;
    
    const traineeName = localStorage.getItem('earlyPreg_traineeName');
    if (traineeName) document.getElementById('earlyPregTraineeName').value = traineeName;
    
    const traineeSignature = localStorage.getItem('earlyPreg_traineeSignature');
    if (traineeSignature) document.getElementById('earlyPregTraineeSignature').value = traineeSignature;
    
    const traineeDate = localStorage.getItem('earlyPreg_traineeDate');
    if (traineeDate) document.getElementById('earlyPregTraineeDate').value = traineeDate;
}

function saveEarlyPregData() {
    localStorage.setItem('earlyPregData', JSON.stringify(earlyPregData));
    localStorage.setItem('earlyPreg_dateCommence', document.getElementById('earlyPregDateCommence').value);
    localStorage.setItem('earlyPreg_tutorName', document.getElementById('earlyPregTutorName').value);
    localStorage.setItem('earlyPreg_tutorSignature', document.getElementById('earlyPregTutorSignature').value);
    localStorage.setItem('earlyPreg_tutorDate', document.getElementById('earlyPregTutorDate').value);
    localStorage.setItem('earlyPreg_traineeName', document.getElementById('earlyPregTraineeName').value);
    localStorage.setItem('earlyPreg_traineeSignature', document.getElementById('earlyPregTraineeSignature').value);
    localStorage.setItem('earlyPreg_traineeDate', document.getElementById('earlyPregTraineeDate').value);
}

function renderEarlyPregTable() {
    const tbody = document.getElementById('earlyPregTableBody');
    if (!tbody) return;
    
    tbody.innerHTML = '';

    // Add category header
    const categoryRow = document.createElement('tr');
    categoryRow.innerHTML = `
        <td colspan="5" style="border: 1px solid #333; padding: 10px; background: #8B7355; color: white; font-weight: bold; text-align: left;">
            RECURRENT MISCARRIAGE
        </td>
    `;
    tbody.appendChild(categoryRow);

    earlyPregItems.forEach((item, index) => {
        const rowNum = index + 1;
        const dataKey = `item_${rowNum}`;
        const checked1 = earlyPregData[`${dataKey}_1`] || '';
        const checked2 = earlyPregData[`${dataKey}_2`] || '';
        const checked3 = earlyPregData[`${dataKey}_3`] || '';
        const sign = earlyPregData[`${dataKey}_sign`] || '';

        const row = document.createElement('tr');
        row.innerHTML = `
            <td style="border: 1px solid #333; padding: 10px; min-width: 300px;">
                <span>${rowNum}</span>. ${item}
            </td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;">
                <input type="checkbox" class="earlypreg-checkbox" data-key="${dataKey}_1" ${checked1 ? 'checked' : ''}>
            </td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;">
                <input type="checkbox" class="earlypreg-checkbox" data-key="${dataKey}_2" ${checked2 ? 'checked' : ''}>
            </td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;">
                <input type="checkbox" class="earlypreg-checkbox" data-key="${dataKey}_3" ${checked3 ? 'checked' : ''}>
            </td>
            <td style="border: 1px solid #333; padding: 10px; min-width: 200px; height: 60px;">
                <textarea class="earlypreg-input" data-key="${dataKey}_sign" rows="3" style="width: 100%; border: none; padding: 6px; resize: none; font-size: 12px;">${sign}</textarea>
            </td>
        `;
        tbody.appendChild(row);
    });

    // Add event listeners
    tbody.querySelectorAll('.earlypreg-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', handleEarlyPregChange);
    });

    tbody.querySelectorAll('.earlypreg-input').forEach(input => {
        input.addEventListener('input', handleEarlyPregChange);
    });
}

function handleEarlyPregChange(event) {
    const key = event.target.dataset.key;
    
    if (event.target.type === 'checkbox') {
        earlyPregData[key] = event.target.checked ? '1' : '';
    } else {
        earlyPregData[key] = event.target.value;
    }
    
    saveEarlyPregData();
}

function printEarlyPregnancyProblems() {
    let tableRows = '';

    // Add category header
    tableRows += `
        <tr>
            <td colspan="5" style="border: 1px solid #000; padding: 10px; background: #8B7355; color: white; font-weight: bold;">RECURRENT MISCARRIAGE</td>
        </tr>
    `;

    earlyPregItems.forEach((item, index) => {
        const rowNum = index + 1;
        const dataKey = `item_${rowNum}`;
        const checked1 = earlyPregData[`${dataKey}_1`] ? '☑' : '☐';
        const checked2 = earlyPregData[`${dataKey}_2`] ? '☑' : '☐';
        const checked3 = earlyPregData[`${dataKey}_3`] ? '☑' : '☐';
        const sign = earlyPregData[`${dataKey}_sign`] || '';

        tableRows += `
            <tr>
                <td style="border: 1px solid #000; padding: 10px;">${rowNum}. ${item}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked1}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked2}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked3}</td>
                <td style="border: 1px solid #000; padding: 10px; font-size: 11px; white-space: pre-wrap;">${sign}</td>
            </tr>
        `;
    });

    const dateCommence = document.getElementById('earlyPregDateCommence').value;
    const tutorName = document.getElementById('earlyPregTutorName').value;
    const tutorSignature = document.getElementById('earlyPregTutorSignature').value;
    const tutorDate = document.getElementById('earlyPregTutorDate').value;
    const traineeName = document.getElementById('earlyPregTraineeName').value;
    const traineeSignature = document.getElementById('earlyPregTraineeSignature').value;
    const traineeDate = document.getElementById('earlyPregTraineeDate').value;

    const printWindow = window.open('', '_blank');
    if (!printWindow) return;

    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
            <head>
                <title>Early Pregnancy Problems - Competency Assessment</title>
                <style>
                    body {
                        font-family: Arial, sans-serif;
                        margin: 20px;
                    }
                    h1 {
                        text-align: center;
                        background: #4472C4;
                        color: white;
                        padding: 12px;
                        margin: 0 0 20px 0;
                    }
                    .date-field {
                        margin-bottom: 20px;
                        border: 1px solid #999;
                        padding: 10px;
                    }
                    .date-field span {
                        font-weight: bold;
                        display: inline-block;
                        width: 150px;
                    }
                    table {
                        width: 100%;
                        border-collapse: collapse;
                        margin-bottom: 20px;
                    }
                    th, td {
                        border: 1px solid #000;
                        padding: 8px;
                        text-align: left;
                        font-size: 11px;
                    }
                    th {
                        background: #ffd700;
                        font-weight: bold;
                    }
                    .signature-table th {
                        background: #f5f5f5;
                        font-weight: bold;
                    }
                    .signature-table td {
                        height: 60px;
                        vertical-align: top;
                        font-size: 10px;
                    }
                </style>
            </head>
            <body>
                <h1>EARLY PREGNANCY PROBLEMS</h1>
                
                <div class="date-field">
                    <span>Date of commence:</span> <strong>${dateCommence}</strong>
                </div>

                <table>
                    <thead>
                        <tr style="background: #ffd700;">
                            <th colspan="5" style="text-align: center; background: #ffd700;">REPRODUCTIVE ENDOCRINOLOGY OUTPATIENT CLINIC</th>
                        </tr>
                        <tr style="background: #ffd700;">
                            <th style="width: 45%;">TARGET REQUIRING SIGNATURE</th>
                            <th colspan="3" style="text-align: center;">EXPECTED COMPETENCE LEVEL</th>
                            <th style="text-align: center;">CERTIFICATION</th>
                        </tr>
                        <tr style="background: #ffd700;">
                            <th></th>
                            <th style="text-align: center;">1</th>
                            <th style="text-align: center;">2</th>
                            <th style="text-align: center;">3</th>
                            <th style="text-align: center;">Sign & Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${tableRows}
                    </tbody>
                </table>

                <table class="signature-table">
                    <thead>
                        <tr>
                            <th colspan="3" style="text-align: center;">SIGNATURE TO CONFIRM COMPLETION</th>
                        </tr>
                        <tr>
                            <th>Name of Academic Tutor</th>
                            <th>Signature of Academic Tutor</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>${tutorName}</td>
                            <td style="white-space: pre-wrap; font-size: 10px;">${tutorSignature}</td>
                            <td>${tutorDate}</td>
                        </tr>
                        <tr style="background: #f5f5f5;">
                            <th>Name of Trainee</th>
                            <th>Signature of Trainee</th>
                            <th>Date</th>
                        </tr>
                        <tr>
                            <td>${traineeName}</td>
                            <td style="white-space: pre-wrap; font-size: 10px;">${traineeSignature}</td>
                            <td>${traineeDate}</td>
                        </tr>
                    </tbody>
                </table>
            </body>
        </html>
    `);

    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => {
        printWindow.print();
    }, 250);
}

// Load Early Pregnancy Problems data when document is ready
document.addEventListener('DOMContentLoaded', function() {
    loadEarlyPregData();
    
    // Auto-save form fields for Early Pregnancy Problems
    const formInputs = ['earlyPregDateCommence', 'earlyPregTutorName', 'earlyPregTutorSignature', 'earlyPregTutorDate', 'earlyPregTraineeName', 'earlyPregTraineeSignature', 'earlyPregTraineeDate'];
    formInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', saveEarlyPregData);
            element.addEventListener('change', saveEarlyPregData);
        }
    });
});

// ========== RESEARCH COMPETENCY ASSESSMENT ==========
const researchItems = [
    'Capable of using presentation maker/program',
    'Capable of using data tabulation program',
    'Capable of using statistical research/program',
    'Finalizing dissertation',
    'Capable of presenting dissertation'
];

let researchData = {};

function openResearch() {
    showSection('research');
    loadResearchData();
}

function loadResearchData() {
    try {
        const saved = JSON.parse(localStorage.getItem('researchData'));
        researchData = saved || {};
    } catch (error) {
        researchData = {};
    }

    renderResearchTable();
    
    // Load other fields
    const dateCommence = localStorage.getItem('research_dateCommence');
    if (dateCommence) document.getElementById('researchDateCommence').value = dateCommence;
    
    const tutorName = localStorage.getItem('research_tutorName');
    if (tutorName) document.getElementById('researchTutorName').value = tutorName;
    
    const tutorSignature = localStorage.getItem('research_tutorSignature');
    if (tutorSignature) document.getElementById('researchTutorSignature').value = tutorSignature;
    
    const tutorDate = localStorage.getItem('research_tutorDate');
    if (tutorDate) document.getElementById('researchTutorDate').value = tutorDate;
    
    const traineeName = localStorage.getItem('research_traineeName');
    if (traineeName) document.getElementById('researchTraineeName').value = traineeName;
    
    const traineeSignature = localStorage.getItem('research_traineeSignature');
    if (traineeSignature) document.getElementById('researchTraineeSignature').value = traineeSignature;
    
    const traineeDate = localStorage.getItem('research_traineeDate');
    if (traineeDate) document.getElementById('researchTraineeDate').value = traineeDate;
}

function saveResearchData() {
    localStorage.setItem('researchData', JSON.stringify(researchData));
    localStorage.setItem('research_dateCommence', document.getElementById('researchDateCommence').value);
    localStorage.setItem('research_tutorName', document.getElementById('researchTutorName').value);
    localStorage.setItem('research_tutorSignature', document.getElementById('researchTutorSignature').value);
    localStorage.setItem('research_tutorDate', document.getElementById('researchTutorDate').value);
    localStorage.setItem('research_traineeName', document.getElementById('researchTraineeName').value);
    localStorage.setItem('research_traineeSignature', document.getElementById('researchTraineeSignature').value);
    localStorage.setItem('research_traineeDate', document.getElementById('researchTraineeDate').value);
}

function renderResearchTable() {
    const tbody = document.getElementById('researchTableBody');
    if (!tbody) return;
    
    tbody.innerHTML = '';

    // Add category header
    const categoryRow = document.createElement('tr');
    categoryRow.innerHTML = `
        <td colspan="5" style="border: 1px solid #333; padding: 10px; background: #8B7355; color: white; font-weight: bold; text-align: left;">
            USE INFORMATION & TECHNOLOGY RELATED TO RESEARCH
        </td>
    `;
    tbody.appendChild(categoryRow);

    researchItems.forEach((item, index) => {
        const rowNum = index + 1;
        const dataKey = `item_${rowNum}`;
        const checked1 = researchData[`${dataKey}_1`] || '';
        const checked2 = researchData[`${dataKey}_2`] || '';
        const checked3 = researchData[`${dataKey}_3`] || '';
        const sign = researchData[`${dataKey}_sign`] || '';

        const row = document.createElement('tr');
        row.innerHTML = `
            <td style="border: 1px solid #333; padding: 10px; min-width: 300px;">
                <span>${rowNum}</span>. ${item}
            </td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;">
                <input type="checkbox" class="research-checkbox" data-key="${dataKey}_1" ${checked1 ? 'checked' : ''}>
            </td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;">
                <input type="checkbox" class="research-checkbox" data-key="${dataKey}_2" ${checked2 ? 'checked' : ''}>
            </td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;">
                <input type="checkbox" class="research-checkbox" data-key="${dataKey}_3" ${checked3 ? 'checked' : ''}>
            </td>
            <td style="border: 1px solid #333; padding: 10px; min-width: 200px; height: 60px;">
                <textarea class="research-input" data-key="${dataKey}_sign" rows="3" style="width: 100%; border: none; padding: 6px; resize: none; font-size: 12px;">${sign}</textarea>
            </td>
        `;
        tbody.appendChild(row);
    });

    // Add event listeners
    tbody.querySelectorAll('.research-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', handleResearchChange);
    });

    tbody.querySelectorAll('.research-input').forEach(input => {
        input.addEventListener('input', handleResearchChange);
    });
}

function handleResearchChange(event) {
    const key = event.target.dataset.key;
    
    if (event.target.type === 'checkbox') {
        researchData[key] = event.target.checked ? '1' : '';
    } else {
        researchData[key] = event.target.value;
    }
    
    saveResearchData();
}

function printResearch() {
    let tableRows = '';

    // Add category header
    tableRows += `
        <tr>
            <td colspan="5" style="border: 1px solid #000; padding: 10px; background: #8B7355; color: white; font-weight: bold;">USE INFORMATION & TECHNOLOGY RELATED TO RESEARCH</td>
        </tr>
    `;

    researchItems.forEach((item, index) => {
        const rowNum = index + 1;
        const dataKey = `item_${rowNum}`;
        const checked1 = researchData[`${dataKey}_1`] ? '☑' : '☐';
        const checked2 = researchData[`${dataKey}_2`] ? '☑' : '☐';
        const checked3 = researchData[`${dataKey}_3`] ? '☑' : '☐';
        const sign = researchData[`${dataKey}_sign`] || '';

        tableRows += `
            <tr>
                <td style="border: 1px solid #000; padding: 10px;">${rowNum}. ${item}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked1}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked2}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked3}</td>
                <td style="border: 1px solid #000; padding: 10px; font-size: 11px; white-space: pre-wrap;">${sign}</td>
            </tr>
        `;
    });

    const dateCommence = document.getElementById('researchDateCommence').value;
    const tutorName = document.getElementById('researchTutorName').value;
    const tutorSignature = document.getElementById('researchTutorSignature').value;
    const tutorDate = document.getElementById('researchTutorDate').value;
    const traineeName = document.getElementById('researchTraineeName').value;
    const traineeSignature = document.getElementById('researchTraineeSignature').value;
    const traineeDate = document.getElementById('researchTraineeDate').value;

    const printWindow = window.open('', '_blank');
    if (!printWindow) return;

    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
            <head>
                <title>Research - Competency Assessment</title>
                <style>
                    body {
                        font-family: Arial, sans-serif;
                        margin: 20px;
                    }
                    h1 {
                        text-align: center;
                        background: #CD7F57;
                        color: white;
                        padding: 12px;
                        margin: 0 0 20px 0;
                    }
                    .date-field {
                        margin-bottom: 20px;
                        border: 1px solid #999;
                        padding: 10px;
                    }
                    .date-field span {
                        font-weight: bold;
                        display: inline-block;
                        width: 150px;
                    }
                    table {
                        width: 100%;
                        border-collapse: collapse;
                        margin-bottom: 20px;
                    }
                    th, td {
                        border: 1px solid #000;
                        padding: 8px;
                        text-align: left;
                        font-size: 11px;
                    }
                    th {
                        background: #ffd700;
                        font-weight: bold;
                    }
                    .signature-table th {
                        background: #f5f5f5;
                        font-weight: bold;
                    }
                    .signature-table td {
                        height: 60px;
                        vertical-align: top;
                        font-size: 10px;
                    }
                </style>
            </head>
            <body>
                <h1>RESEARCH</h1>
                
                <div class="date-field">
                    <span>Date of commence:</span> <strong>${dateCommence}</strong>
                </div>

                <table>
                    <thead>
                        <tr style="background: #ffd700;">
                            <th colspan="5" style="text-align: center; background: #ffd700;">REPRODUCTIVE ENDOCRINOLOGY OUTPATIENT CLINIC</th>
                        </tr>
                        <tr style="background: #ffd700;">
                            <th style="width: 45%;">TARGET REQUIRING SIGNATURE</th>
                            <th colspan="3" style="text-align: center;">EXPECTED COMPETENCE LEVEL</th>
                            <th style="text-align: center;">CERTIFICATION</th>
                        </tr>
                        <tr style="background: #ffd700;">
                            <th></th>
                            <th style="text-align: center;">1</th>
                            <th style="text-align: center;">2</th>
                            <th style="text-align: center;">3</th>
                            <th style="text-align: center;">Sign & Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${tableRows}
                    </tbody>
                </table>

                <table class="signature-table">
                    <thead>
                        <tr>
                            <th colspan="3" style="text-align: center;">SIGNATURE TO CONFIRM COMPLETION</th>
                        </tr>
                        <tr>
                            <th>Name of Academic Tutor</th>
                            <th>Signature of Academic Tutor</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>${tutorName}</td>
                            <td style="white-space: pre-wrap; font-size: 10px;">${tutorSignature}</td>
                            <td>${tutorDate}</td>
                        </tr>
                        <tr style="background: #f5f5f5;">
                            <th>Name of Trainee</th>
                            <th>Signature of Trainee</th>
                            <th>Date</th>
                        </tr>
                        <tr>
                            <td>${traineeName}</td>
                            <td style="white-space: pre-wrap; font-size: 10px;">${traineeSignature}</td>
                            <td>${traineeDate}</td>
                        </tr>
                    </tbody>
                </table>
            </body>
        </html>
    `);

    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => {
        printWindow.print();
    }, 250);
}

// Load Research data when document is ready
document.addEventListener('DOMContentLoaded', function() {
    loadResearchData();
    
    // Auto-save form fields for Research
    const formInputs = ['researchDateCommence', 'researchTutorName', 'researchTutorSignature', 'researchTutorDate', 'researchTraineeName', 'researchTraineeSignature', 'researchTraineeDate'];
    formInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', saveResearchData);
            element.addEventListener('change', saveResearchData);
        }
    });
});

// ========== SUBFERTILITY II COMPETENCY ASSESSMENT ==========
const subfertilityII_items = [
    'Ovulation induction (gonadotrophing, GnRH agonist, GnRH antagonists)',
    'IUI + superovulation',
    'IVF',
    'IVF + ICSI',
    'Use donors (oocyte, sperm, and embryos)',
    'Gamete storage (fertility preservation)'
];

let subfertilityII_data = {};

function openSubfertilityII() {
    showSection('subfertility-ii');
    loadSubfertilityII_Data();
}

function loadSubfertilityII_Data() {
    try {
        const saved = JSON.parse(localStorage.getItem('subfertilityII_data'));
        subfertilityII_data = saved || {};
    } catch (error) {
        subfertilityII_data = {};
    }
    renderSubfertilityII_Table();
    const dateCommence = localStorage.getItem('subfertilityII_dateCommence');
    if (dateCommence) document.getElementById('subfertilityII_dateCommence').value = dateCommence;
    const tutorName = localStorage.getItem('subfertilityII_tutorName');
    if (tutorName) document.getElementById('subfertilityII_tutorName').value = tutorName;
    const tutorSignature = localStorage.getItem('subfertilityII_tutorSignature');
    if (tutorSignature) document.getElementById('subfertilityII_tutorSignature').value = tutorSignature;
    const tutorDate = localStorage.getItem('subfertilityII_tutorDate');
    if (tutorDate) document.getElementById('subfertilityII_tutorDate').value = tutorDate;
    const traineeName = localStorage.getItem('subfertilityII_traineeName');
    if (traineeName) document.getElementById('subfertilityII_traineeName').value = traineeName;
    const traineeSignature = localStorage.getItem('subfertilityII_traineeSignature');
    if (traineeSignature) document.getElementById('subfertilityII_traineeSignature').value = traineeSignature;
    const traineeDate = localStorage.getItem('subfertilityII_traineeDate');
    if (traineeDate) document.getElementById('subfertilityII_traineeDate').value = traineeDate;
}

function saveSubfertilityII_Data() {
    localStorage.setItem('subfertilityII_data', JSON.stringify(subfertilityII_data));
    localStorage.setItem('subfertilityII_dateCommence', document.getElementById('subfertilityII_dateCommence').value);
    localStorage.setItem('subfertilityII_tutorName', document.getElementById('subfertilityII_tutorName').value);
    localStorage.setItem('subfertilityII_tutorSignature', document.getElementById('subfertilityII_tutorSignature').value);
    localStorage.setItem('subfertilityII_tutorDate', document.getElementById('subfertilityII_tutorDate').value);
    localStorage.setItem('subfertilityII_traineeName', document.getElementById('subfertilityII_traineeName').value);
    localStorage.setItem('subfertilityII_traineeSignature', document.getElementById('subfertilityII_traineeSignature').value);
    localStorage.setItem('subfertilityII_traineeDate', document.getElementById('subfertilityII_traineeDate').value);
}

function renderSubfertilityII_Table() {
    const tbody = document.getElementById('subfertilityII_tableBody');
    if (!tbody) return;
    tbody.innerHTML = '';
    const categoryRow = document.createElement('tr');
    categoryRow.innerHTML = `<td colspan="5" style="border: 1px solid #333; padding: 10px; background: #8B7355; color: white; font-weight: bold; text-align: left;">DISCUSS WITH COUPLE AND COUNSEL TOWARDS APPROPRIATE TREATMENT</td>`;
    tbody.appendChild(categoryRow);
    subfertilityII_items.forEach((item, index) => {
        const rowNum = index + 1;
        const dataKey = `item_${rowNum}`;
        const checked1 = subfertilityII_data[`${dataKey}_1`] || '';
        const checked2 = subfertilityII_data[`${dataKey}_2`] || '';
        const checked3 = subfertilityII_data[`${dataKey}_3`] || '';
        const sign = subfertilityII_data[`${dataKey}_sign`] || '';
        const row = document.createElement('tr');
        row.innerHTML = `<td style="border: 1px solid #333; padding: 10px; min-width: 300px;"><span>${rowNum}</span>. ${item}</td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="subfertilityii-checkbox" data-key="${dataKey}_1" ${checked1 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="subfertilityii-checkbox" data-key="${dataKey}_2" ${checked2 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="subfertilityii-checkbox" data-key="${dataKey}_3" ${checked3 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; min-width: 200px; height: 60px;"><textarea class="subfertilityii-input" data-key="${dataKey}_sign" rows="3" style="width: 100%; border: none; padding: 6px; resize: none; font-size: 12px;">${sign}</textarea></td>`;
        tbody.appendChild(row);
    });
    tbody.querySelectorAll('.subfertilityii-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', handleSubfertilityII_Change);
    });
    tbody.querySelectorAll('.subfertilityii-input').forEach(input => {
        input.addEventListener('input', handleSubfertilityII_Change);
    });
}

function handleSubfertilityII_Change(event) {
    const key = event.target.dataset.key;
    if (event.target.type === 'checkbox') {
        subfertilityII_data[key] = event.target.checked ? '1' : '';
    } else {
        subfertilityII_data[key] = event.target.value;
    }
    saveSubfertilityII_Data();
}

function printSubfertilityII() {
    let tableRows = `<tr><td colspan="5" style="border: 1px solid #000; padding: 10px; background: #8B7355; color: white; font-weight: bold;">DISCUSS WITH COUPLE AND COUNSEL TOWARDS APPROPRIATE TREATMENT</td></tr>`;
    subfertilityII_items.forEach((item, index) => {
        const rowNum = index + 1;
        const dataKey = `item_${rowNum}`;
        const checked1 = subfertilityII_data[`${dataKey}_1`] ? '☑' : '☐';
        const checked2 = subfertilityII_data[`${dataKey}_2`] ? '☑' : '☐';
        const checked3 = subfertilityII_data[`${dataKey}_3`] ? '☑' : '☐';
        const sign = subfertilityII_data[`${dataKey}_sign`] || '';
        tableRows += `<tr><td style="border: 1px solid #000; padding: 10px;">${rowNum}. ${item}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked1}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked2}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked3}</td>
                <td style="border: 1px solid #000; padding: 10px; font-size: 11px; white-space: pre-wrap;">${sign}</td></tr>`;
    });
    const dateCommence = document.getElementById('subfertilityII_dateCommence').value;
    const tutorName = document.getElementById('subfertilityII_tutorName').value;
    const tutorSignature = document.getElementById('subfertilityII_tutorSignature').value;
    const tutorDate = document.getElementById('subfertilityII_tutorDate').value;
    const traineeName = document.getElementById('subfertilityII_traineeName').value;
    const traineeSignature = document.getElementById('subfertilityII_traineeSignature').value;
    const traineeDate = document.getElementById('subfertilityII_traineeDate').value;
    const printWindow = window.open('', '_blank');
    if (!printWindow) return;
    printWindow.document.write(`<!DOCTYPE html><html><head><title>Subfertility II - Competency Assessment</title><style>body{font-family:Arial,sans-serif;margin:20px;}h1{text-align:center;background:#4a7c59;color:white;padding:12px;margin:0 0 20px 0;}.date-field{margin-bottom:20px;border:1px solid #999;padding:10px;}.date-field span{font-weight:bold;display:inline-block;width:150px;}table{width:100%;border-collapse:collapse;margin-bottom:20px;}th,td{border:1px solid #000;padding:8px;text-align:left;font-size:11px;}th{background:#ffd700;font-weight:bold;}.signature-table th{background:#f5f5f5;font-weight:bold;}.signature-table td{height:60px;vertical-align:top;font-size:10px;}</style></head><body><h1>SUBFERTILITY II</h1><div class="date-field"><span>Date of commence:</span> <strong>${dateCommence}</strong></div><table><thead><tr style="background:#ffd700;"><th colspan="5" style="text-align:center;background:#ffd700;">REPRODUCTIVE ENDOCRINOLOGY OUTPATIENT CLINIC</th></tr><tr style="background:#ffd700;"><th style="width:45%;">TARGET REQUIRING SIGNATURE</th><th colspan="3" style="text-align:center;">EXPECTED COMPETENCE LEVEL</th><th style="text-align:center;">CERTIFICATION</th></tr><tr style="background:#ffd700;"><th></th><th style="text-align:center;">1</th><th style="text-align:center;">2</th><th style="text-align:center;">3</th><th style="text-align:center;">Sign & Date</th></tr></thead><tbody>${tableRows}</tbody></table><table class="signature-table"><thead><tr><th colspan="3" style="text-align:center;">SIGNATURE TO CONFIRM COMPLETION</th></tr><tr><th>Name of Academic Tutor</th><th>Signature of Academic Tutor</th><th>Date</th></tr></thead><tbody><tr><td>${tutorName}</td><td style="white-space:pre-wrap;font-size:10px;">${tutorSignature}</td><td>${tutorDate}</td></tr><tr style="background:#f5f5f5;"><th>Name of Trainee</th><th>Signature of Trainee</th><th>Date</th></tr><tr><td>${traineeName}</td><td style="white-space:pre-wrap;font-size:10px;">${traineeSignature}</td><td>${traineeDate}</td></tr></tbody></table></body></html>`);
    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => { printWindow.print(); }, 250);
}

document.addEventListener('DOMContentLoaded', function() {
    loadSubfertilityII_Data();
    const formInputs = ['subfertilityII_dateCommence', 'subfertilityII_tutorName', 'subfertilityII_tutorSignature', 'subfertilityII_tutorDate', 'subfertilityII_traineeName', 'subfertilityII_traineeSignature', 'subfertilityII_traineeDate'];
    formInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', saveSubfertilityII_Data);
            element.addEventListener('change', saveSubfertilityII_Data);
        }
    });
});

// ========== REPRODUCTIVE SURGERY I & II COMPETENCY ASSESSMENT ==========
const reprodSurgery_items = [
    { text: 'Diagnostic hysteroscopy', category: 'HYSTEROSCOPIC SURGERY' },
    { text: 'Outpatient hysteroscopy', category: null },
    { text: 'Resection of polyp', category: null },
    { text: 'Diagnostic laparoscopy', category: 'LAPAROSCOPIC SURGERY' },
    { text: 'Treatment of minimal/mild endometriosis', category: null },
    { text: 'Ovarian diathermy', category: null },
    { text: 'Treatment of ovarian endometrioma(s)', category: null },
    { text: 'Laparoscopic Cystectomy', category: null },
    { text: 'Salpingostomy for hydrosalpinx', category: null },
    { text: 'Salpingostomy', category: null },
    { text: 'Salpingostomy or aspiration/frenectomy pregnancy', category: null },
    { text: 'Myomectomy', category: null },
    { text: 'Reversal of sterilization', category: 'OPEN FERTILITY SURGERY' },
    { text: 'Myomectomy', category: null },
    { text: 'Adhesiolysis/ resection', category: null }
];

let reprodSurgery_data = {};

function openReprodSurgeryI() {
    showSection('reprod-surgery-i');
    loadReprodSurgery_Data();
}

function loadReprodSurgery_Data() {
    try {
        const saved = JSON.parse(localStorage.getItem('reprodSurgery_data'));
        reprodSurgery_data = saved || {};
    } catch (error) {
        reprodSurgery_data = {};
    }
    renderReprodSurgery_Table();
    const dateCommence = localStorage.getItem('reprodSurgery_dateCommence');
    if (dateCommence) document.getElementById('reprodSurgery_dateCommence').value = dateCommence;
    const tutorName = localStorage.getItem('reprodSurgery_tutorName');
    if (tutorName) document.getElementById('reprodSurgery_tutorName').value = tutorName;
    const tutorSignature = localStorage.getItem('reprodSurgery_tutorSignature');
    if (tutorSignature) document.getElementById('reprodSurgery_tutorSignature').value = tutorSignature;
    const tutorDate = localStorage.getItem('reprodSurgery_tutorDate');
    if (tutorDate) document.getElementById('reprodSurgery_tutorDate').value = tutorDate;
    const traineeName = localStorage.getItem('reprodSurgery_traineeName');
    if (traineeName) document.getElementById('reprodSurgery_traineeName').value = traineeName;
    const traineeSignature = localStorage.getItem('reprodSurgery_traineeSignature');
    if (traineeSignature) document.getElementById('reprodSurgery_traineeSignature').value = traineeSignature;
    const traineeDate = localStorage.getItem('reprodSurgery_traineeDate');
    if (traineeDate) document.getElementById('reprodSurgery_traineeDate').value = traineeDate;
}

function saveReprodSurgery_Data() {
    localStorage.setItem('reprodSurgery_data', JSON.stringify(reprodSurgery_data));
    localStorage.setItem('reprodSurgery_dateCommence', document.getElementById('reprodSurgery_dateCommence').value);
    localStorage.setItem('reprodSurgery_tutorName', document.getElementById('reprodSurgery_tutorName').value);
    localStorage.setItem('reprodSurgery_tutorSignature', document.getElementById('reprodSurgery_tutorSignature').value);
    localStorage.setItem('reprodSurgery_tutorDate', document.getElementById('reprodSurgery_tutorDate').value);
    localStorage.setItem('reprodSurgery_traineeName', document.getElementById('reprodSurgery_traineeName').value);
    localStorage.setItem('reprodSurgery_traineeSignature', document.getElementById('reprodSurgery_traineeSignature').value);
    localStorage.setItem('reprodSurgery_traineeDate', document.getElementById('reprodSurgery_traineeDate').value);
}

function renderReprodSurgery_Table() {
    const tbody = document.getElementById('reprodSurgery_tableBody');
    if (!tbody) return;
    tbody.innerHTML = '';
    let currentCategory = null;
    reprodSurgery_items.forEach((item, index) => {
        if (item.category && item.category !== currentCategory) {
            currentCategory = item.category;
            const categoryRow = document.createElement('tr');
            categoryRow.innerHTML = `<td colspan="5" style="border: 1px solid #333; padding: 10px; background: #8B7355; color: white; font-weight: bold; text-align: left;">${currentCategory}</td>`;
            tbody.appendChild(categoryRow);
        }
        const rowNum = index + 1;
        const dataKey = `item_${rowNum}`;
        const checked1 = reprodSurgery_data[`${dataKey}_1`] || '';
        const checked2 = reprodSurgery_data[`${dataKey}_2`] || '';
        const checked3 = reprodSurgery_data[`${dataKey}_3`] || '';
        const sign = reprodSurgery_data[`${dataKey}_sign`] || '';
        const row = document.createElement('tr');
        row.innerHTML = `<td style="border: 1px solid #333; padding: 10px; min-width: 300px;"><span>${rowNum}</span>. ${item.text}</td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="reprodsurgery-checkbox" data-key="${dataKey}_1" ${checked1 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="reprodsurgery-checkbox" data-key="${dataKey}_2" ${checked2 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="reprodsurgery-checkbox" data-key="${dataKey}_3" ${checked3 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; min-width: 200px; height: 60px;"><textarea class="reprodsurgery-input" data-key="${dataKey}_sign" rows="3" style="width: 100%; border: none; padding: 6px; resize: none; font-size: 12px;">${sign}</textarea></td>`;
        tbody.appendChild(row);
    });
    tbody.querySelectorAll('.reprodsurgery-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', handleReprodSurgery_Change);
    });
    tbody.querySelectorAll('.reprodsurgery-input').forEach(input => {
        input.addEventListener('input', handleReprodSurgery_Change);
    });
}

function handleReprodSurgery_Change(event) {
    const key = event.target.dataset.key;
    if (event.target.type === 'checkbox') {
        reprodSurgery_data[key] = event.target.checked ? '1' : '';
    } else {
        reprodSurgery_data[key] = event.target.value;
    }
    saveReprodSurgery_Data();
}

function printReprodSurgeryI() {
    let tableRows = '';
    let currentCategory = null;
    reprodSurgery_items.forEach((item, index) => {
        if (item.category && item.category !== currentCategory) {
            currentCategory = item.category;
            tableRows += `<tr><td colspan="5" style="border: 1px solid #000; padding: 10px; background: #8B7355; color: white; font-weight: bold;">${currentCategory}</td></tr>`;
        }
        const rowNum = index + 1;
        const dataKey = `item_${rowNum}`;
        const checked1 = reprodSurgery_data[`${dataKey}_1`] ? '☑' : '☐';
        const checked2 = reprodSurgery_data[`${dataKey}_2`] ? '☑' : '☐';
        const checked3 = reprodSurgery_data[`${dataKey}_3`] ? '☑' : '☐';
        const sign = reprodSurgery_data[`${dataKey}_sign`] || '';
        tableRows += `<tr><td style="border: 1px solid #000; padding: 10px;">${rowNum}. ${item.text}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked1}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked2}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked3}</td>
                <td style="border: 1px solid #000; padding: 10px; font-size: 11px; white-space: pre-wrap;">${sign}</td></tr>`;
    });
    const dateCommence = document.getElementById('reprodSurgery_dateCommence').value;
    const tutorName = document.getElementById('reprodSurgery_tutorName').value;
    const tutorSignature = document.getElementById('reprodSurgery_tutorSignature').value;
    const tutorDate = document.getElementById('reprodSurgery_tutorDate').value;
    const traineeName = document.getElementById('reprodSurgery_traineeName').value;
    const traineeSignature = document.getElementById('reprodSurgery_traineeSignature').value;
    const traineeDate = document.getElementById('reprodSurgery_traineeDate').value;
    const printWindow = window.open('', '_blank');
    if (!printWindow) return;
    printWindow.document.write(`<!DOCTYPE html><html><head><title>Reproductive Surgery I & II - Competency Assessment</title><style>body{font-family:Arial,sans-serif;margin:20px;}h1{text-align:center;background:#4a7c59;color:white;padding:12px;margin:0 0 20px 0;}.date-field{margin-bottom:20px;border:1px solid #999;padding:10px;}.date-field span{font-weight:bold;display:inline-block;width:150px;}table{width:100%;border-collapse:collapse;margin-bottom:20px;}th,td{border:1px solid #000;padding:8px;text-align:left;font-size:11px;}th{background:#ffd700;font-weight:bold;}.signature-table th{background:#f5f5f5;font-weight:bold;}.signature-table td{height:60px;vertical-align:top;font-size:10px;}</style></head><body><h1>REPRODUCTIVE SURGERY I & II</h1><div class="date-field"><span>Date of commence:</span> <strong>${dateCommence}</strong></div><table><thead><tr style="background:#ffd700;"><th colspan="5" style="text-align:center;background:#ffd700;">REPRODUCTIVE ENDOCRINOLOGY OUTPATIENT CLINIC</th></tr><tr style="background:#ffd700;"><th style="width:45%;">TARGET REQUIRING SIGNATURE</th><th colspan="3" style="text-align:center;">EXPECTED COMPETENCE LEVEL</th><th style="text-align:center;">CERTIFICATION</th></tr><tr style="background:#ffd700;"><th></th><th style="text-align:center;">1</th><th style="text-align:center;">2</th><th style="text-align:center;">3</th><th style="text-align:center;">Sign & Date</th></tr></thead><tbody>${tableRows}</tbody></table><table class="signature-table"><thead><tr><th colspan="3" style="text-align:center;">SIGNATURE TO CONFIRM COMPLETION</th></tr><tr><th>Name of Academic Tutor</th><th>Signature of Academic Tutor</th><th>Date</th></tr></thead><tbody><tr><td>${tutorName}</td><td style="white-space:pre-wrap;font-size:10px;">${tutorSignature}</td><td>${tutorDate}</td></tr><tr style="background:#f5f5f5;"><th>Name of Trainee</th><th>Signature of Trainee</th><th>Date</th></tr><tr><td>${traineeName}</td><td style="white-space:pre-wrap;font-size:10px;">${traineeSignature}</td><td>${traineeDate}</td></tr></tbody></table></body></html>`);
    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => { printWindow.print(); }, 250);
}

document.addEventListener('DOMContentLoaded', function() {
    loadReprodSurgery_Data();
    const formInputs = ['reprodSurgery_dateCommence', 'reprodSurgery_tutorName', 'reprodSurgery_tutorSignature', 'reprodSurgery_tutorDate', 'reprodSurgery_traineeName', 'reprodSurgery_traineeSignature', 'reprodSurgery_traineeDate'];
    formInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', saveReprodSurgery_Data);
            element.addEventListener('change', saveReprodSurgery_Data);
        }
    });
});

// ========== METABOLIC ENDOCRINOLOGY COMPETENCY ASSESSMENT ==========
const metabolic_items = [
    { text: 'Cushing syndrome', category: 'ADRENAL DYSFUNCTION' },
    { text: 'Nelson syndrome', category: null },
    { text: 'Addison\'s disease', category: null },
    { text: 'Adrenal hyperplasia', category: null },
    { text: 'Hypothyroidism', category: 'THYROID DISORDERS' },
    { text: 'Hyperthyroidism', category: null },
    { text: 'Diabetes Mellitus', category: 'OTHER' }
];

let metabolic_data = {};

function openMetabolicEndocrinology() {
    showSection('metabolic-endocrinology');
    loadMetabolic_Data();
}

function loadMetabolic_Data() {
    try {
        const saved = JSON.parse(localStorage.getItem('metabolic_data'));
        metabolic_data = saved || {};
    } catch (error) {
        metabolic_data = {};
    }
    renderMetabolic_Table();
    const dateCommence = localStorage.getItem('metabolic_dateCommence');
    if (dateCommence) document.getElementById('metabolic_dateCommence').value = dateCommence;
    const tutorName = localStorage.getItem('metabolic_tutorName');
    if (tutorName) document.getElementById('metabolic_tutorName').value = tutorName;
    const tutorSignature = localStorage.getItem('metabolic_tutorSignature');
    if (tutorSignature) document.getElementById('metabolic_tutorSignature').value = tutorSignature;
    const tutorDate = localStorage.getItem('metabolic_tutorDate');
    if (tutorDate) document.getElementById('metabolic_tutorDate').value = tutorDate;
    const traineeName = localStorage.getItem('metabolic_traineeName');
    if (traineeName) document.getElementById('metabolic_traineeName').value = traineeName;
    const traineeSignature = localStorage.getItem('metabolic_traineeSignature');
    if (traineeSignature) document.getElementById('metabolic_traineeSignature').value = traineeSignature;
    const traineeDate = localStorage.getItem('metabolic_traineeDate');
    if (traineeDate) document.getElementById('metabolic_traineeDate').value = traineeDate;
}

function saveMetabolic_Data() {
    localStorage.setItem('metabolic_data', JSON.stringify(metabolic_data));
    localStorage.setItem('metabolic_dateCommence', document.getElementById('metabolic_dateCommence').value);
    localStorage.setItem('metabolic_tutorName', document.getElementById('metabolic_tutorName').value);
    localStorage.setItem('metabolic_tutorSignature', document.getElementById('metabolic_tutorSignature').value);
    localStorage.setItem('metabolic_tutorDate', document.getElementById('metabolic_tutorDate').value);
    localStorage.setItem('metabolic_traineeName', document.getElementById('metabolic_traineeName').value);
    localStorage.setItem('metabolic_traineeSignature', document.getElementById('metabolic_traineeSignature').value);
    localStorage.setItem('metabolic_traineeDate', document.getElementById('metabolic_traineeDate').value);
}

function renderMetabolic_Table() {
    const tbody = document.getElementById('metabolic_tableBody');
    if (!tbody) return;
    tbody.innerHTML = '';
    let currentCategory = null;
    metabolic_items.forEach((item, index) => {
        if (item.category && item.category !== currentCategory) {
            currentCategory = item.category;
            const categoryRow = document.createElement('tr');
            categoryRow.innerHTML = `<td colspan="5" style="border: 1px solid #333; padding: 10px; background: #8B7355; color: white; font-weight: bold; text-align: left;">${currentCategory}</td>`;
            tbody.appendChild(categoryRow);
        }
        const rowNum = index + 1;
        const dataKey = `item_${rowNum}`;
        const checked1 = metabolic_data[`${dataKey}_1`] || '';
        const checked2 = metabolic_data[`${dataKey}_2`] || '';
        const checked3 = metabolic_data[`${dataKey}_3`] || '';
        const sign = metabolic_data[`${dataKey}_sign`] || '';
        const row = document.createElement('tr');
        row.innerHTML = `<td style="border: 1px solid #333; padding: 10px; min-width: 300px;"><span>${rowNum}</span>. ${item.text}</td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="metabolic-checkbox" data-key="${dataKey}_1" ${checked1 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="metabolic-checkbox" data-key="${dataKey}_2" ${checked2 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="metabolic-checkbox" data-key="${dataKey}_3" ${checked3 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; min-width: 200px; height: 60px;"><textarea class="metabolic-input" data-key="${dataKey}_sign" rows="3" style="width: 100%; border: none; padding: 6px; resize: none; font-size: 12px;">${sign}</textarea></td>`;
        tbody.appendChild(row);
    });
    tbody.querySelectorAll('.metabolic-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', handleMetabolic_Change);
    });
    tbody.querySelectorAll('.metabolic-input').forEach(input => {
        input.addEventListener('input', handleMetabolic_Change);
    });
}

function handleMetabolic_Change(event) {
    const key = event.target.dataset.key;
    if (event.target.type === 'checkbox') {
        metabolic_data[key] = event.target.checked ? '1' : '';
    } else {
        metabolic_data[key] = event.target.value;
    }
    saveMetabolic_Data();
}

function printMetabolicEndocrinology() {
    let tableRows = '';
    let currentCategory = null;
    metabolic_items.forEach((item, index) => {
        if (item.category && item.category !== currentCategory) {
            currentCategory = item.category;
            tableRows += `<tr><td colspan="5" style="border: 1px solid #000; padding: 10px; background: #8B7355; color: white; font-weight: bold;">${currentCategory}</td></tr>`;
        }
        const rowNum = index + 1;
        const dataKey = `item_${rowNum}`;
        const checked1 = metabolic_data[`${dataKey}_1`] ? '☑' : '☐';
        const checked2 = metabolic_data[`${dataKey}_2`] ? '☑' : '☐';
        const checked3 = metabolic_data[`${dataKey}_3`] ? '☑' : '☐';
        const sign = metabolic_data[`${dataKey}_sign`] || '';
        tableRows += `<tr><td style="border: 1px solid #000; padding: 10px;">${rowNum}. ${item.text}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked1}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked2}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked3}</td>
                <td style="border: 1px solid #000; padding: 10px; font-size: 11px; white-space: pre-wrap;">${sign}</td></tr>`;
    });
    const dateCommence = document.getElementById('metabolic_dateCommence').value;
    const tutorName = document.getElementById('metabolic_tutorName').value;
    const tutorSignature = document.getElementById('metabolic_tutorSignature').value;
    const tutorDate = document.getElementById('metabolic_tutorDate').value;
    const traineeName = document.getElementById('metabolic_traineeName').value;
    const traineeSignature = document.getElementById('metabolic_traineeSignature').value;
    const traineeDate = document.getElementById('metabolic_traineeDate').value;
    const printWindow = window.open('', '_blank');
    if (!printWindow) return;
    printWindow.document.write(`<!DOCTYPE html><html><head><title>Metabolic Endocrinology - Competency Assessment</title><style>body{font-family:Arial,sans-serif;margin:20px;}h1{text-align:center;background:#4a7c59;color:white;padding:12px;margin:0 0 20px 0;}.date-field{margin-bottom:20px;border:1px solid #999;padding:10px;}.date-field span{font-weight:bold;display:inline-block;width:150px;}table{width:100%;border-collapse:collapse;margin-bottom:20px;}th,td{border:1px solid #000;padding:8px;text-align:left;font-size:11px;}th{background:#ffd700;font-weight:bold;}.signature-table th{background:#f5f5f5;font-weight:bold;}.signature-table td{height:60px;vertical-align:top;font-size:10px;}</style></head><body><h1>METABOLIC ENDOCRINOLOGY</h1><div class="date-field"><span>Date of commence:</span> <strong>${dateCommence}</strong></div><table><thead><tr style="background:#ffd700;"><th colspan="5" style="text-align:center;background:#ffd700;">REPRODUCTIVE ENDOCRINOLOGY OUTPATIENT CLINIC</th></tr><tr style="background:#ffd700;"><th style="width:45%;">TARGET REQUIRING SIGNATURE</th><th colspan="3" style="text-align:center;">EXPECTED COMPETENCE LEVEL</th><th style="text-align:center;">CERTIFICATION</th></tr><tr style="background:#ffd700;"><th></th><th style="text-align:center;">1</th><th style="text-align:center;">2</th><th style="text-align:center;">3</th><th style="text-align:center;">Sign & Date</th></tr></thead><tbody>${tableRows}</tbody></table><table class="signature-table"><thead><tr><th colspan="3" style="text-align:center;">SIGNATURE TO CONFIRM COMPLETION</th></tr><tr><th>Name of Academic Tutor</th><th>Signature of Academic Tutor</th><th>Date</th></tr></thead><tbody><tr><td>${tutorName}</td><td style="white-space:pre-wrap;font-size:10px;">${tutorSignature}</td><td>${tutorDate}</td></tr><tr style="background:#f5f5f5;"><th>Name of Trainee</th><th>Signature of Trainee</th><th>Date</th></tr><tr><td>${traineeName}</td><td style="white-space:pre-wrap;font-size:10px;">${traineeSignature}</td><td>${traineeDate}</td></tr></tbody></table></body></html>`);
    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => { printWindow.print(); }, 250);
}

document.addEventListener('DOMContentLoaded', function() {
    loadMetabolic_Data();
    const formInputs = ['metabolic_dateCommence', 'metabolic_tutorName', 'metabolic_tutorSignature', 'metabolic_tutorDate', 'metabolic_traineeName', 'metabolic_traineeSignature', 'metabolic_traineeDate'];
    formInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', saveMetabolic_Data);
            element.addEventListener('change', saveMetabolic_Data);
        }
    });
});

// ========== PAEDIATRIC & ADOLESCENT GYNECOLOGY COMPETENCY ASSESSMENT ==========
const paediatric_items = [
    { text: 'Sonographic finding', category: 'SCREENING AND DIAGNOSIS' },
    { text: 'Normal growth and development', category: 'DEVELOPMENT DISORDERS' },
    { text: 'Ambiguous genitalia', category: null },
    { text: 'Genital anomalies', category: null },
    { text: 'Disorders of sex development (DSD)', category: null },
    { text: 'Precocious puberty', category: 'ENDOCRINE DISTURBANCE' },
    { text: 'Delayed puberty', category: null },
    { text: 'Late-onset congenital adrenal hyperplasia', category: null },
    { text: 'primary amenorrhea', category: null },
    { text: 'Management of survivors of childhood cancer', category: null }
];

let paediatric_data = {};

function openPaediatricGynecology() {
    showSection('paediatric-gynecology');
    loadPaediatric_Data();
}

function loadPaediatric_Data() {
    try {
        const saved = JSON.parse(localStorage.getItem('paediatric_data'));
        paediatric_data = saved || {};
    } catch (error) {
        paediatric_data = {};
    }
    renderPaediatric_Table();
    const dateCommence = localStorage.getItem('paediatric_dateCommence');
    if (dateCommence) document.getElementById('paediatric_dateCommence').value = dateCommence;
    const tutorName = localStorage.getItem('paediatric_tutorName');
    if (tutorName) document.getElementById('paediatric_tutorName').value = tutorName;
    const tutorSignature = localStorage.getItem('paediatric_tutorSignature');
    if (tutorSignature) document.getElementById('paediatric_tutorSignature').value = tutorSignature;
    const tutorDate = localStorage.getItem('paediatric_tutorDate');
    if (tutorDate) document.getElementById('paediatric_tutorDate').value = tutorDate;
    const traineeName = localStorage.getItem('paediatric_traineeName');
    if (traineeName) document.getElementById('paediatric_traineeName').value = traineeName;
    const traineeSignature = localStorage.getItem('paediatric_traineeSignature');
    if (traineeSignature) document.getElementById('paediatric_traineeSignature').value = traineeSignature;
    const traineeDate = localStorage.getItem('paediatric_traineeDate');
    if (traineeDate) document.getElementById('paediatric_traineeDate').value = traineeDate;
}

function savePaediatric_Data() {
    localStorage.setItem('paediatric_data', JSON.stringify(paediatric_data));
    localStorage.setItem('paediatric_dateCommence', document.getElementById('paediatric_dateCommence').value);
    localStorage.setItem('paediatric_tutorName', document.getElementById('paediatric_tutorName').value);
    localStorage.setItem('paediatric_tutorSignature', document.getElementById('paediatric_tutorSignature').value);
    localStorage.setItem('paediatric_tutorDate', document.getElementById('paediatric_tutorDate').value);
    localStorage.setItem('paediatric_traineeName', document.getElementById('paediatric_traineeName').value);
    localStorage.setItem('paediatric_traineeSignature', document.getElementById('paediatric_traineeSignature').value);
    localStorage.setItem('paediatric_traineeDate', document.getElementById('paediatric_traineeDate').value);
}

function renderPaediatric_Table() {
    const tbody = document.getElementById('paediatric_tableBody');
    if (!tbody) return;
    tbody.innerHTML = '';
    let currentCategory = null;
    paediatric_items.forEach((item, index) => {
        if (item.category && item.category !== currentCategory) {
            currentCategory = item.category;
            const categoryRow = document.createElement('tr');
            categoryRow.innerHTML = `<td colspan="5" style="border: 1px solid #333; padding: 10px; background: #8B7355; color: white; font-weight: bold; text-align: left;">${currentCategory}</td>`;
            tbody.appendChild(categoryRow);
        }
        const rowNum = index + 1;
        const dataKey = `item_${rowNum}`;
        const checked1 = paediatric_data[`${dataKey}_1`] || '';
        const checked2 = paediatric_data[`${dataKey}_2`] || '';
        const checked3 = paediatric_data[`${dataKey}_3`] || '';
        const sign = paediatric_data[`${dataKey}_sign`] || '';
        const row = document.createElement('tr');
        row.innerHTML = `<td style="border: 1px solid #333; padding: 10px; min-width: 300px;"><span>${rowNum}</span>. ${item.text}</td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="paediatric-checkbox" data-key="${dataKey}_1" ${checked1 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="paediatric-checkbox" data-key="${dataKey}_2" ${checked2 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="paediatric-checkbox" data-key="${dataKey}_3" ${checked3 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; min-width: 200px; height: 60px;"><textarea class="paediatric-input" data-key="${dataKey}_sign" rows="3" style="width: 100%; border: none; padding: 6px; resize: none; font-size: 12px;">${sign}</textarea></td>`;
        tbody.appendChild(row);
    });
    tbody.querySelectorAll('.paediatric-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', handlePaediatric_Change);
    });
    tbody.querySelectorAll('.paediatric-input').forEach(input => {
        input.addEventListener('input', handlePaediatric_Change);
    });
}

function handlePaediatric_Change(event) {
    const key = event.target.dataset.key;
    if (event.target.type === 'checkbox') {
        paediatric_data[key] = event.target.checked ? '1' : '';
    } else {
        paediatric_data[key] = event.target.value;
    }
    savePaediatric_Data();
}

function printPaediatricGynecology() {
    let tableRows = '';
    let currentCategory = null;
    paediatric_items.forEach((item, index) => {
        if (item.category && item.category !== currentCategory) {
            currentCategory = item.category;
            tableRows += `<tr><td colspan="5" style="border: 1px solid #000; padding: 10px; background: #8B7355; color: white; font-weight: bold;">${currentCategory}</td></tr>`;
        }
        const rowNum = index + 1;
        const dataKey = `item_${rowNum}`;
        const checked1 = paediatric_data[`${dataKey}_1`] ? '☑' : '☐';
        const checked2 = paediatric_data[`${dataKey}_2`] ? '☑' : '☐';
        const checked3 = paediatric_data[`${dataKey}_3`] ? '☑' : '☐';
        const sign = paediatric_data[`${dataKey}_sign`] || '';
        tableRows += `<tr><td style="border: 1px solid #000; padding: 10px;">${rowNum}. ${item.text}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked1}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked2}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked3}</td>
                <td style="border: 1px solid #000; padding: 10px; font-size: 11px; white-space: pre-wrap;">${sign}</td></tr>`;
    });
    const dateCommence = document.getElementById('paediatric_dateCommence').value;
    const tutorName = document.getElementById('paediatric_tutorName').value;
    const tutorSignature = document.getElementById('paediatric_tutorSignature').value;
    const tutorDate = document.getElementById('paediatric_tutorDate').value;
    const traineeName = document.getElementById('paediatric_traineeName').value;
    const traineeSignature = document.getElementById('paediatric_traineeSignature').value;
    const traineeDate = document.getElementById('paediatric_traineeDate').value;
    const printWindow = window.open('', '_blank');
    if (!printWindow) return;
    printWindow.document.write(`<!DOCTYPE html><html><head><title>Paediatric & Adolescent Gynecology - Competency Assessment</title><style>body{font-family:Arial,sans-serif;margin:20px;}h1{text-align:center;background:#4a7c59;color:white;padding:12px;margin:0 0 20px 0;}.date-field{margin-bottom:20px;border:1px solid #999;padding:10px;}.date-field span{font-weight:bold;display:inline-block;width:150px;}table{width:100%;border-collapse:collapse;margin-bottom:20px;}th,td{border:1px solid #000;padding:8px;text-align:left;font-size:11px;}th{background:#ffd700;font-weight:bold;}.signature-table th{background:#f5f5f5;font-weight:bold;}.signature-table td{height:60px;vertical-align:top;font-size:10px;}</style></head><body><h1>PAEDIATRIC AND ADOLESCENT GYNECOLOGY</h1><div class="date-field"><span>Date of commence:</span> <strong>${dateCommence}</strong></div><table><thead><tr style="background:#ffd700;"><th colspan="5" style="text-align:center;background:#ffd700;">PEDIATRIC ENDOCRINOLOGY OUTPATIENT CLINIC REPRODUCTIVE ENDOCRINOLOGY OUTPATIENT CLINIC</th></tr><tr style="background:#ffd700;"><th style="width:45%;">TARGET REQUIRING SIGNATURE</th><th colspan="3" style="text-align:center;">EXPECTED COMPETENCE LEVEL</th><th style="text-align:center;">CERTIFICATION</th></tr><tr style="background:#ffd700;"><th></th><th style="text-align:center;">1</th><th style="text-align:center;">2</th><th style="text-align:center;">3</th><th style="text-align:center;">Sign & Date</th></tr></thead><tbody>${tableRows}</tbody></table><table class="signature-table"><thead><tr><th colspan="3" style="text-align:center;">SIGNATURE TO CONFIRM COMPLETION</th></tr><tr><th>Name of Academic Tutor</th><th>Signature of Academic Tutor</th><th>Date</th></tr></thead><tbody><tr><td>${tutorName}</td><td style="white-space:pre-wrap;font-size:10px;">${tutorSignature}</td><td>${tutorDate}</td></tr><tr style="background:#f5f5f5;"><th>Name of Trainee</th><th>Signature of Trainee</th><th>Date</th></tr><tr><td>${traineeName}</td><td style="white-space:pre-wrap;font-size:10px;">${traineeSignature}</td><td>${traineeDate}</td></tr></tbody></table></body></html>`);
    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => { printWindow.print(); }, 250);
}

document.addEventListener('DOMContentLoaded', function() {
    loadPaediatric_Data();
    const formInputs = ['paediatric_dateCommence', 'paediatric_tutorName', 'paediatric_tutorSignature', 'paediatric_tutorDate', 'paediatric_traineeName', 'paediatric_traineeSignature', 'paediatric_traineeDate'];
    formInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', savePaediatric_Data);
            element.addEventListener('change', savePaediatric_Data);
        }
    });
});

// ========== ASSISTED REPRODUCTIVE TECHNOLOGY I COMPETENCY ASSESSMENT ==========
const art1_items = [
    'Sperm preparation',
    'Oocyte culture',
    'Oocyte insemination',
    'Oocyte sperm injection',
    'Embryo culture',
    'Embryo freezing and thawing',
    'Assisted hatching',
    'Polymerase chain reaction / DNA, RNA, protein amplification techniques / Immuno-flowcytometry'
];

let art1_data = {};

function openART1() {
    showSection('art-i');
    loadART1_Data();
}

function loadART1_Data() {
    try {
        const saved = JSON.parse(localStorage.getItem('art1_data'));
        art1_data = saved || {};
    } catch (error) {
        art1_data = {};
    }
    renderART1_Table();
    const dateCommence = localStorage.getItem('art1_dateCommence');
    if (dateCommence) document.getElementById('art1_dateCommence').value = dateCommence;
    const tutorName = localStorage.getItem('art1_tutorName');
    if (tutorName) document.getElementById('art1_tutorName').value = tutorName;
    const tutorSignature = localStorage.getItem('art1_tutorSignature');
    if (tutorSignature) document.getElementById('art1_tutorSignature').value = tutorSignature;
    const tutorDate = localStorage.getItem('art1_tutorDate');
    if (tutorDate) document.getElementById('art1_tutorDate').value = tutorDate;
    const traineeName = localStorage.getItem('art1_traineeName');
    if (traineeName) document.getElementById('art1_traineeName').value = traineeName;
    const traineeSignature = localStorage.getItem('art1_traineeSignature');
    if (traineeSignature) document.getElementById('art1_traineeSignature').value = traineeSignature;
    const traineeDate = localStorage.getItem('art1_traineeDate');
    if (traineeDate) document.getElementById('art1_traineeDate').value = traineeDate;
}

function saveART1_Data() {
    localStorage.setItem('art1_data', JSON.stringify(art1_data));
    localStorage.setItem('art1_dateCommence', document.getElementById('art1_dateCommence').value);
    localStorage.setItem('art1_tutorName', document.getElementById('art1_tutorName').value);
    localStorage.setItem('art1_tutorSignature', document.getElementById('art1_tutorSignature').value);
    localStorage.setItem('art1_tutorDate', document.getElementById('art1_tutorDate').value);
    localStorage.setItem('art1_traineeName', document.getElementById('art1_traineeName').value);
    localStorage.setItem('art1_traineeSignature', document.getElementById('art1_traineeSignature').value);
    localStorage.setItem('art1_traineeDate', document.getElementById('art1_traineeDate').value);
}

function renderART1_Table() {
    const tbody = document.getElementById('art1_tableBody');
    if (!tbody) return;
    tbody.innerHTML = '';
    const categoryRow = document.createElement('tr');
    categoryRow.innerHTML = `<td colspan="5" style="border: 1px solid #333; padding: 10px; background: #8B7355; color: white; font-weight: bold; text-align: left;">LABORATORY PROCEDURE</td>`;
    tbody.appendChild(categoryRow);
    art1_items.forEach((item, index) => {
        const rowNum = index + 1;
        const dataKey = `item_${rowNum}`;
        const checked1 = art1_data[`${dataKey}_1`] || '';
        const checked2 = art1_data[`${dataKey}_2`] || '';
        const checked3 = art1_data[`${dataKey}_3`] || '';
        const sign = art1_data[`${dataKey}_sign`] || '';
        const row = document.createElement('tr');
        row.innerHTML = `<td style="border: 1px solid #333; padding: 10px; min-width: 300px;"><span>${rowNum}</span>. ${item}</td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="art1-checkbox" data-key="${dataKey}_1" ${checked1 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="art1-checkbox" data-key="${dataKey}_2" ${checked2 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="art1-checkbox" data-key="${dataKey}_3" ${checked3 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; min-width: 200px; height: 60px;"><textarea class="art1-input" data-key="${dataKey}_sign" rows="3" style="width: 100%; border: none; padding: 6px; resize: none; font-size: 12px;">${sign}</textarea></td>`;
        tbody.appendChild(row);
    });
    tbody.querySelectorAll('.art1-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', handleART1_Change);
    });
    tbody.querySelectorAll('.art1-input').forEach(input => {
        input.addEventListener('input', handleART1_Change);
    });
}

function handleART1_Change(event) {
    const key = event.target.dataset.key;
    if (event.target.type === 'checkbox') {
        art1_data[key] = event.target.checked ? '1' : '';
    } else {
        art1_data[key] = event.target.value;
    }
    saveART1_Data();
}

function printART1() {
    let tableRows = `<tr><td colspan="5" style="border: 1px solid #000; padding: 10px; background: #8B7355; color: white; font-weight: bold;">LABORATORY PROCEDURE</td></tr>`;
    art1_items.forEach((item, index) => {
        const rowNum = index + 1;
        const dataKey = `item_${rowNum}`;
        const checked1 = art1_data[`${dataKey}_1`] ? '☑' : '☐';
        const checked2 = art1_data[`${dataKey}_2`] ? '☑' : '☐';
        const checked3 = art1_data[`${dataKey}_3`] ? '☑' : '☐';
        const sign = art1_data[`${dataKey}_sign`] || '';
        tableRows += `<tr><td style="border: 1px solid #000; padding: 10px;">${rowNum}. ${item}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked1}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked2}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked3}</td>
                <td style="border: 1px solid #000; padding: 10px; font-size: 11px; white-space: pre-wrap;">${sign}</td></tr>`;
    });
    const dateCommence = document.getElementById('art1_dateCommence').value;
    const tutorName = document.getElementById('art1_tutorName').value;
    const tutorSignature = document.getElementById('art1_tutorSignature').value;
    const tutorDate = document.getElementById('art1_tutorDate').value;
    const traineeName = document.getElementById('art1_traineeName').value;
    const traineeSignature = document.getElementById('art1_traineeSignature').value;
    const traineeDate = document.getElementById('art1_traineeDate').value;
    const printWindow = window.open('', '_blank');
    if (!printWindow) return;
    printWindow.document.write(`<!DOCTYPE html><html><head><title>Assisted Reproductive Technology I - Competency Assessment</title><style>body{font-family:Arial,sans-serif;margin:20px;}h1{text-align:center;background:#4a7c59;color:white;padding:12px;margin:0 0 20px 0;}.date-field{margin-bottom:20px;border:1px solid #999;padding:10px;}.date-field span{font-weight:bold;display:inline-block;width:150px;}table{width:100%;border-collapse:collapse;margin-bottom:20px;}th,td{border:1px solid #000;padding:8px;text-align:left;font-size:11px;}th{background:#ffd700;font-weight:bold;}.signature-table th{background:#f5f5f5;font-weight:bold;}.signature-table td{height:60px;vertical-align:top;font-size:10px;}</style></head><body><h1>ASSISTED REPRODUCTIVE TECHNOLOGY I</h1><div class="date-field"><span>Date of commence:</span> <strong>${dateCommence}</strong></div><table><thead><tr style="background:#ffd700;"><th colspan="5" style="text-align:center;background:#ffd700;">REPRODUCTIVE ENDOCRINOLOGY OUTPATIENT CLINIC</th></tr><tr style="background:#ffd700;"><th style="width:45%;">TARGET REQUIRING SIGNATURE</th><th colspan="3" style="text-align:center;">EXPECTED COMPETENCE LEVEL</th><th style="text-align:center;">CERTIFICATION</th></tr><tr style="background:#ffd700;"><th></th><th style="text-align:center;">1</th><th style="text-align:center;">2</th><th style="text-align:center;">3</th><th style="text-align:center;">Sign & Date</th></tr></thead><tbody>${tableRows}</tbody></table><table class="signature-table"><thead><tr><th colspan="3" style="text-align:center;">SIGNATURE TO CONFIRM COMPLETION</th></tr><tr><th>Name of Academic Tutor</th><th>Signature of Academic Tutor</th><th>Date</th></tr></thead><tbody><tr><td>${tutorName}</td><td style="white-space:pre-wrap;font-size:10px;">${tutorSignature}</td><td>${tutorDate}</td></tr><tr style="background:#f5f5f5;"><th>Name of Trainee</th><th>Signature of Trainee</th><th>Date</th></tr><tr><td>${traineeName}</td><td style="white-space:pre-wrap;font-size:10px;">${traineeSignature}</td><td>${traineeDate}</td></tr></tbody></table></body></html>`);
    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => { printWindow.print(); }, 250);
}

document.addEventListener('DOMContentLoaded', function() {
    loadART1_Data();
    const formInputs = ['art1_dateCommence', 'art1_tutorName', 'art1_tutorSignature', 'art1_tutorDate', 'art1_traineeName', 'art1_traineeSignature', 'art1_traineeDate'];
    formInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', saveART1_Data);
            element.addEventListener('change', saveART1_Data);
        }
    });
});

function openCPL() {
    showSection('cpl');
    const cplLink = document.querySelector('.menu-link[href="#cpl"]');
    if (cplLink) {
        document.querySelectorAll('.menu-link').forEach(l => l.classList.remove('active'));
        cplLink.classList.add('active');
    }
}

document.addEventListener('DOMContentLoaded', function() {
    loadCPLData();
});

// ============ ASSISTED REPRODUCTIVE TECHNOLOGY I - SEMESTER III ============
const art1s3_items = [
    { text: 'Anatomy and physiology of testis', category: 'ANATOMY/PHYSIOLOGY OF TESTIS' },
    'Hormonal role in spermatogenesis',
    'Ultrasound assessment of testis',
    'Semen analysis interpretation',
    'Sperm processing techniques',
    'Sperm washing and concentration',
    'Sperm freezing and thawing procedures',
    'Sperm vitality assessment',
    'Testicular biopsy and TESA techniques',
    { text: 'Sperm banking for fertility preservation', category: 'COUNSELLING' },
    { text: 'Endocrine therapy for male infertility', category: 'MEDICAL TREATMENT' },
    { text: 'Vasectomy reversal counselling', category: 'MALE SURGERY' },
    'Microsurgical techniques for vas reconnection',
    'Post-vasectomy reversal assessment',
    'Surgical outcomes and complications',
    'Male factor infertility management',
    'Genetic counselling for male infertility'
];
const art1s3_data = {};

function openART1_sem3() {
    showSection('art1-sem3');
    loadART1s3_Data();
}

function loadART1s3_Data() {
    for (let key in localStorage) {
        if (key.startsWith('art1s3_')) {
            const itemKey = key.replace('art1s3_', '');
            art1s3_data[itemKey] = localStorage.getItem(key);
        }
    }
    const dateCommence = localStorage.getItem('art1s3_dateCommence') || '';
    const tutorName = localStorage.getItem('art1s3_tutorName') || '';
    const tutorSignature = localStorage.getItem('art1s3_tutorSignature') || '';
    const tutorDate = localStorage.getItem('art1s3_tutorDate') || '';
    const traineeName = localStorage.getItem('art1s3_traineeName') || '';
    const traineeSignature = localStorage.getItem('art1s3_traineeSignature') || '';
    const traineeDate = localStorage.getItem('art1s3_traineeDate') || '';
    if (dateCommence) document.getElementById('art1s3_dateCommence').value = dateCommence;
    if (tutorName) document.getElementById('art1s3_tutorName').value = tutorName;
    if (tutorSignature) document.getElementById('art1s3_tutorSignature').value = tutorSignature;
    if (tutorDate) document.getElementById('art1s3_tutorDate').value = tutorDate;
    if (traineeName) document.getElementById('art1s3_traineeName').value = traineeName;
    if (traineeSignature) document.getElementById('art1s3_traineeSignature').value = traineeSignature;
    if (traineeDate) document.getElementById('art1s3_traineeDate').value = traineeDate;
    renderART1s3_Table();
}

function saveART1s3_Data() {
    for (let key in art1s3_data) {
        localStorage.setItem(`art1s3_${key}`, art1s3_data[key]);
    }
    const dateCommence = document.getElementById('art1s3_dateCommence').value;
    const tutorName = document.getElementById('art1s3_tutorName').value;
    const tutorSignature = document.getElementById('art1s3_tutorSignature').value;
    const tutorDate = document.getElementById('art1s3_tutorDate').value;
    const traineeName = document.getElementById('art1s3_traineeName').value;
    const traineeSignature = document.getElementById('art1s3_traineeSignature').value;
    const traineeDate = document.getElementById('art1s3_traineeDate').value;
    localStorage.setItem('art1s3_dateCommence', dateCommence);
    localStorage.setItem('art1s3_tutorName', tutorName);
    localStorage.setItem('art1s3_tutorSignature', tutorSignature);
    localStorage.setItem('art1s3_tutorDate', tutorDate);
    localStorage.setItem('art1s3_traineeName', traineeName);
    localStorage.setItem('art1s3_traineeSignature', traineeSignature);
    localStorage.setItem('art1s3_traineeDate', traineeDate);
}

function renderART1s3_Table() {
    const tbody = document.getElementById('art1s3_tableBody');
    if (!tbody) return;
    tbody.innerHTML = '';
    let currentCategory = '';
    art1s3_items.forEach((item, index) => {
        const rowNum = index + 1;
        const category = typeof item === 'object' ? item.category : null;
        const itemText = typeof item === 'object' ? item.text : item;
        if (category && category !== currentCategory) {
            currentCategory = category;
            const categoryRow = document.createElement('tr');
            categoryRow.innerHTML = `<td colspan="5" style="border: 1px solid #333; padding: 10px; background: #8B7355; color: white; font-weight: bold; text-align: left;">${category}</td>`;
            tbody.appendChild(categoryRow);
        }
        const dataKey = `item_${rowNum}`;
        const checked1 = art1s3_data[`${dataKey}_1`] || '';
        const checked2 = art1s3_data[`${dataKey}_2`] || '';
        const checked3 = art1s3_data[`${dataKey}_3`] || '';
        const sign = art1s3_data[`${dataKey}_sign`] || '';
        const row = document.createElement('tr');
        row.innerHTML = `<td style="border: 1px solid #333; padding: 10px; min-width: 300px;"><span>${rowNum}</span>. ${itemText}</td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="art1s3-checkbox" data-key="${dataKey}_1" ${checked1 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="art1s3-checkbox" data-key="${dataKey}_2" ${checked2 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="art1s3-checkbox" data-key="${dataKey}_3" ${checked3 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; min-width: 200px; height: 60px;"><textarea class="art1s3-input" data-key="${dataKey}_sign" rows="3" style="width: 100%; border: none; padding: 6px; resize: none; font-size: 12px;">${sign}</textarea></td>`;
        tbody.appendChild(row);
    });
    tbody.querySelectorAll('.art1s3-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', handleART1s3_Change);
    });
    tbody.querySelectorAll('.art1s3-input').forEach(input => {
        input.addEventListener('input', handleART1s3_Change);
    });
}

function handleART1s3_Change(event) {
    const key = event.target.dataset.key;
    if (event.target.type === 'checkbox') {
        art1s3_data[key] = event.target.checked ? '1' : '';
    } else {
        art1s3_data[key] = event.target.value;
    }
    saveART1s3_Data();
}

function printART1_sem3() {
    let tableRows = '';
    let currentCategory = '';
    art1s3_items.forEach((item, index) => {
        const rowNum = index + 1;
        const category = typeof item === 'object' ? item.category : null;
        const itemText = typeof item === 'object' ? item.text : item;
        if (category && category !== currentCategory) {
            currentCategory = category;
            tableRows += `<tr><td colspan="5" style="border: 1px solid #000; padding: 10px; background: #8B7355; color: white; font-weight: bold;">${category}</td></tr>`;
        }
        const dataKey = `item_${rowNum}`;
        const checked1 = art1s3_data[`${dataKey}_1`] ? '☑' : '☐';
        const checked2 = art1s3_data[`${dataKey}_2`] ? '☑' : '☐';
        const checked3 = art1s3_data[`${dataKey}_3`] ? '☑' : '☐';
        const sign = art1s3_data[`${dataKey}_sign`] || '';
        tableRows += `<tr><td style="border: 1px solid #000; padding: 10px;">${rowNum}. ${itemText}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked1}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked2}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked3}</td>
                <td style="border: 1px solid #000; padding: 10px; font-size: 11px; white-space: pre-wrap;">${sign}</td></tr>`;
    });
    const dateCommence = document.getElementById('art1s3_dateCommence').value;
    const tutorName = document.getElementById('art1s3_tutorName').value;
    const tutorSignature = document.getElementById('art1s3_tutorSignature').value;
    const tutorDate = document.getElementById('art1s3_tutorDate').value;
    const traineeName = document.getElementById('art1s3_traineeName').value;
    const traineeSignature = document.getElementById('art1s3_traineeSignature').value;
    const traineeDate = document.getElementById('art1s3_traineeDate').value;
    const printWindow = window.open('', '_blank');
    if (!printWindow) return;
    printWindow.document.write(`<!DOCTYPE html><html><head><title>Assisted Reproductive Technology I Semester III</title><style>body{font-family:Arial,sans-serif;margin:20px;}h1{text-align:center;background:#4a7c59;color:white;padding:12px;margin:0 0 20px 0;}.date-field{margin-bottom:20px;border:1px solid #999;padding:10px;}.date-field span{font-weight:bold;display:inline-block;width:150px;}table{width:100%;border-collapse:collapse;margin-bottom:20px;}th,td{border:1px solid #000;padding:8px;text-align:left;font-size:11px;}th{background:#ffd700;font-weight:bold;}.signature-table{page-break-before:always;}@media print{.signature-table{page-break-before:always;}}.signature-table th{background:#f5f5f5;font-weight:bold;}.signature-table td{height:60px;vertical-align:top;font-size:10px;}</style></head><body><h1>ASSISTED REPRODUCTIVE TECHNOLOGY I - SEMESTER III</h1><div class="date-field"><span>Date of commence:</span> <strong>${dateCommence}</strong></div><table><thead><tr style="background:#ffd700;"><th colspan="5" style="text-align:center;background:#ffd700;">REPRODUCTIVE ENDOCRINOLOGY OUTPATIENT CLINIC</th></tr><tr style="background:#ffd700;"><th style="width:45%;">TARGET REQUIRING SIGNATURE</th><th colspan="3" style="text-align:center;">EXPECTED COMPETENCE LEVEL</th><th style="text-align:center;">CERTIFICATION</th></tr><tr style="background:#ffd700;"><th></th><th style="text-align:center;">1</th><th style="text-align:center;">2</th><th style="text-align:center;">3</th><th style="text-align:center;">Sign & Date</th></tr></thead><tbody>${tableRows}</tbody></table><table class="signature-table"><thead><tr><th colspan="3" style="text-align:center;">SIGNATURE TO CONFIRM COMPLETION</th></tr><tr><th>Name of Academic Tutor</th><th>Signature of Academic Tutor</th><th>Date</th></tr></thead><tbody><tr><td>${tutorName}</td><td style="white-space:pre-wrap;font-size:10px;">${tutorSignature}</td><td>${tutorDate}</td></tr><tr style="background:#f5f5f5;"><th>Name of Trainee</th><th>Signature of Trainee</th><th>Date</th></tr><tr><td>${traineeName}</td><td style="white-space:pre-wrap;font-size:10px;">${traineeSignature}</td><td>${traineeDate}</td></tr></tbody></table></body></html>`);
    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => { printWindow.print(); }, 250);
}

document.addEventListener('DOMContentLoaded', function() {
    loadART1s3_Data();
    const formInputs = ['art1s3_dateCommence', 'art1s3_tutorName', 'art1s3_tutorSignature', 'art1s3_tutorDate', 'art1s3_traineeName', 'art1s3_traineeSignature', 'art1s3_traineeDate'];
    formInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', saveART1s3_Data);
            element.addEventListener('change', saveART1s3_Data);
        }
    });
});

// ============ ASSISTED REPRODUCTIVE TECHNOLOGY II ============
const art2_items = [
    { text: 'Controlled ovarian hyperstimulation protocols', category: 'MANAGEMENT/TREATMENT CYCLES' },
    'GnRH agonist and antagonist usage',
    'Monitoring strategies during stimulation',
    'Trigger for final oocyte maturation',
    'Luteal phase support protocols',
    'Oocyte retrieval techniques',
    'Embryo culture systems',
    'Sperm preparation techniques',
    'Fertilization check and assessment',
    'Embryo grading and selection',
    { text: 'Oocyte retrieval procedures', category: 'PRACTICAL PROCEDURES' },
    'Embryo transfer technique',
    'Freezing and thawing procedures',
    'Cryopreservation methods',
    'Blastocyst culture management',
    'Intracytoplasmic sperm injection (ICSI)',
    'Assisted hatching techniques',
    'Pre-implantation genetic diagnosis (PGD)',
    'Pre-implantation genetic screening (PGS)',
    'Cycle statistics and outcomes',
    { text: 'Reporting of adverse incidents', category: 'ADVERSE INCIDENT REPORTING' },
    'Patient safety protocols',
    'Ovarian hyperstimulation syndrome management',
    { text: 'Genetic counselling in ART', category: 'GENETIC COUNSELLING' },
    'Inherited disorder screening',
    'Mitochondrial diseases assessment',
    { text: 'Gamete handling and processing', category: 'CELL CULTURE AND PROCESSING' },
    'Semen processing for ART',
    'Oocyte processing and assessment',
    'Embryo morphology evaluation',
    'Spent media testing',
    { text: 'PGD applications and techniques', category: 'PGD/PGS' },
    'PGS methodology',
    'Carrier screening protocols',
    'Sex selection for genetic conditions',
    'Viability and competency assessment',
    'Follow-up of genetic results',
    'Long-term outcomes in PGD/PGS cycles'
];
const art2_data = {};

function openART2() {
    showSection('art2');
    loadART2_Data();
}

function loadART2_Data() {
    for (let key in localStorage) {
        if (key.startsWith('art2_')) {
            const itemKey = key.replace('art2_', '');
            art2_data[itemKey] = localStorage.getItem(key);
        }
    }
    const dateCommence = localStorage.getItem('art2_dateCommence') || '';
    const tutorName = localStorage.getItem('art2_tutorName') || '';
    const tutorSignature = localStorage.getItem('art2_tutorSignature') || '';
    const tutorDate = localStorage.getItem('art2_tutorDate') || '';
    const traineeName = localStorage.getItem('art2_traineeName') || '';
    const traineeSignature = localStorage.getItem('art2_traineeSignature') || '';
    const traineeDate = localStorage.getItem('art2_traineeDate') || '';
    if (dateCommence) document.getElementById('art2_dateCommence').value = dateCommence;
    if (tutorName) document.getElementById('art2_tutorName').value = tutorName;
    if (tutorSignature) document.getElementById('art2_tutorSignature').value = tutorSignature;
    if (tutorDate) document.getElementById('art2_tutorDate').value = tutorDate;
    if (traineeName) document.getElementById('art2_traineeName').value = traineeName;
    if (traineeSignature) document.getElementById('art2_traineeSignature').value = traineeSignature;
    if (traineeDate) document.getElementById('art2_traineeDate').value = traineeDate;
    renderART2_Table();
}

function saveART2_Data() {
    for (let key in art2_data) {
        localStorage.setItem(`art2_${key}`, art2_data[key]);
    }
    const dateCommence = document.getElementById('art2_dateCommence').value;
    const tutorName = document.getElementById('art2_tutorName').value;
    const tutorSignature = document.getElementById('art2_tutorSignature').value;
    const tutorDate = document.getElementById('art2_tutorDate').value;
    const traineeName = document.getElementById('art2_traineeName').value;
    const traineeSignature = document.getElementById('art2_traineeSignature').value;
    const traineeDate = document.getElementById('art2_traineeDate').value;
    localStorage.setItem('art2_dateCommence', dateCommence);
    localStorage.setItem('art2_tutorName', tutorName);
    localStorage.setItem('art2_tutorSignature', tutorSignature);
    localStorage.setItem('art2_tutorDate', tutorDate);
    localStorage.setItem('art2_traineeName', traineeName);
    localStorage.setItem('art2_traineeSignature', traineeSignature);
    localStorage.setItem('art2_traineeDate', traineeDate);
}

function renderART2_Table() {
    const tbody = document.getElementById('art2_tableBody');
    if (!tbody) return;
    tbody.innerHTML = '';
    let currentCategory = '';
    art2_items.forEach((item, index) => {
        const rowNum = index + 1;
        const category = typeof item === 'object' ? item.category : null;
        const itemText = typeof item === 'object' ? item.text : item;
        if (category && category !== currentCategory) {
            currentCategory = category;
            const categoryRow = document.createElement('tr');
            categoryRow.innerHTML = `<td colspan="5" style="border: 1px solid #333; padding: 10px; background: #8B7355; color: white; font-weight: bold; text-align: left;">${category}</td>`;
            tbody.appendChild(categoryRow);
        }
        const dataKey = `item_${rowNum}`;
        const checked1 = art2_data[`${dataKey}_1`] || '';
        const checked2 = art2_data[`${dataKey}_2`] || '';
        const checked3 = art2_data[`${dataKey}_3`] || '';
        const sign = art2_data[`${dataKey}_sign`] || '';
        const row = document.createElement('tr');
        row.innerHTML = `<td style="border: 1px solid #333; padding: 10px; min-width: 300px;"><span>${rowNum}</span>. ${itemText}</td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="art2-checkbox" data-key="${dataKey}_1" ${checked1 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="art2-checkbox" data-key="${dataKey}_2" ${checked2 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="art2-checkbox" data-key="${dataKey}_3" ${checked3 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; min-width: 200px; height: 60px;"><textarea class="art2-input" data-key="${dataKey}_sign" rows="3" style="width: 100%; border: none; padding: 6px; resize: none; font-size: 12px;">${sign}</textarea></td>`;
        tbody.appendChild(row);
    });
    tbody.querySelectorAll('.art2-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', handleART2_Change);
    });
    tbody.querySelectorAll('.art2-input').forEach(input => {
        input.addEventListener('input', handleART2_Change);
    });
}

function handleART2_Change(event) {
    const key = event.target.dataset.key;
    if (event.target.type === 'checkbox') {
        art2_data[key] = event.target.checked ? '1' : '';
    } else {
        art2_data[key] = event.target.value;
    }
    saveART2_Data();
}

function printART2() {
    let tableRows = '';
    let currentCategory = '';
    art2_items.forEach((item, index) => {
        const rowNum = index + 1;
        const category = typeof item === 'object' ? item.category : null;
        const itemText = typeof item === 'object' ? item.text : item;
        if (category && category !== currentCategory) {
            currentCategory = category;
            tableRows += `<tr><td colspan="5" style="border: 1px solid #000; padding: 10px; background: #8B7355; color: white; font-weight: bold;">${category}</td></tr>`;
        }
        const dataKey = `item_${rowNum}`;
        const checked1 = art2_data[`${dataKey}_1`] ? '☑' : '☐';
        const checked2 = art2_data[`${dataKey}_2`] ? '☑' : '☐';
        const checked3 = art2_data[`${dataKey}_3`] ? '☑' : '☐';
        const sign = art2_data[`${dataKey}_sign`] || '';
        tableRows += `<tr><td style="border: 1px solid #000; padding: 10px;">${rowNum}. ${itemText}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked1}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked2}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked3}</td>
                <td style="border: 1px solid #000; padding: 10px; font-size: 11px; white-space: pre-wrap;">${sign}</td></tr>`;
    });
    const dateCommence = document.getElementById('art2_dateCommence').value;
    const tutorName = document.getElementById('art2_tutorName').value;
    const tutorSignature = document.getElementById('art2_tutorSignature').value;
    const tutorDate = document.getElementById('art2_tutorDate').value;
    const traineeName = document.getElementById('art2_traineeName').value;
    const traineeSignature = document.getElementById('art2_traineeSignature').value;
    const traineeDate = document.getElementById('art2_traineeDate').value;
    const printWindow = window.open('', '_blank');
    if (!printWindow) return;
    printWindow.document.write(`<!DOCTYPE html><html><head><title>Assisted Reproductive Technology II</title><style>body{font-family:Arial,sans-serif;margin:20px;}h1{text-align:center;background:#4a7c59;color:white;padding:12px;margin:0 0 20px 0;}.date-field{margin-bottom:20px;border:1px solid #999;padding:10px;}.date-field span{font-weight:bold;display:inline-block;width:150px;}table{width:100%;border-collapse:collapse;margin-bottom:20px;}th,td{border:1px solid #000;padding:8px;text-align:left;font-size:11px;}th{background:#ffd700;font-weight:bold;}.signature-table{page-break-before:always;}@media print{.signature-table{page-break-before:always;}}.signature-table th{background:#f5f5f5;font-weight:bold;}.signature-table td{height:60px;vertical-align:top;font-size:10px;}</style></head><body><h1>ASSISTED REPRODUCTIVE TECHNOLOGY II</h1><div class="date-field"><span>Date of commence:</span> <strong>${dateCommence}</strong></div><table><thead><tr style="background:#ffd700;"><th colspan="5" style="text-align:center;background:#ffd700;">REPRODUCTIVE ENDOCRINOLOGY OUTPATIENT CLINIC</th></tr><tr style="background:#ffd700;"><th style="width:45%;">TARGET REQUIRING SIGNATURE</th><th colspan="3" style="text-align:center;">EXPECTED COMPETENCE LEVEL</th><th style="text-align:center;">CERTIFICATION</th></tr><tr style="background:#ffd700;"><th></th><th style="text-align:center;">1</th><th style="text-align:center;">2</th><th style="text-align:center;">3</th><th style="text-align:center;">Sign & Date</th></tr></thead><tbody>${tableRows}</tbody></table><table class="signature-table"><thead><tr><th colspan="3" style="text-align:center;">SIGNATURE TO CONFIRM COMPLETION</th></tr><tr><th>Name of Academic Tutor</th><th>Signature of Academic Tutor</th><th>Date</th></tr></thead><tbody><tr><td>${tutorName}</td><td style="white-space:pre-wrap;font-size:10px;">${tutorSignature}</td><td>${tutorDate}</td></tr><tr style="background:#f5f5f5;"><th>Name of Trainee</th><th>Signature of Trainee</th><th>Date</th></tr><tr><td>${traineeName}</td><td style="white-space:pre-wrap;font-size:10px;">${traineeSignature}</td><td>${traineeDate}</td></tr></tbody></table></body></html>`);
    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => { printWindow.print(); }, 250);
}

document.addEventListener('DOMContentLoaded', function() {
    loadART2_Data();
    const formInputs = ['art2_dateCommence', 'art2_tutorName', 'art2_tutorSignature', 'art2_tutorDate', 'art2_traineeName', 'art2_traineeSignature', 'art2_traineeDate'];
    formInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', saveART2_Data);
            element.addEventListener('change', saveART2_Data);
        }
    });
});

// ============ MENOPAUSE AND PREMATURE OVARIAN FAILURE ============
const menopause_items = [
    { text: 'Management of post-menopausal women', category: 'MANAGEMENT OF MENOPAUSE' },
    'Hormone replacement therapy and alternatives',
    'Vasomotor symptom management',
    { text: 'Endocrine assessment in POF', category: 'MANAGEMENT OF POF' },
    'Fertility preservation strategies',
    'Psychological support and counselling',
    'Bone health management',
    'Cardiovascular risk assessment',
    'Long-term follow-up protocols'
];
const menopause_data = {};

function openMenopausePOF() {
    showSection('menopause-pof');
    loadMenopausePOF_Data();
}

function loadMenopausePOF_Data() {
    for (let key in localStorage) {
        if (key.startsWith('menopause_')) {
            const itemKey = key.replace('menopause_', '');
            menopause_data[itemKey] = localStorage.getItem(key);
        }
    }
    const dateCommence = localStorage.getItem('menopause_dateCommence') || '';
    const tutorName = localStorage.getItem('menopause_tutorName') || '';
    const tutorSignature = localStorage.getItem('menopause_tutorSignature') || '';
    const tutorDate = localStorage.getItem('menopause_tutorDate') || '';
    const traineeName = localStorage.getItem('menopause_traineeName') || '';
    const traineeSignature = localStorage.getItem('menopause_traineeSignature') || '';
    const traineeDate = localStorage.getItem('menopause_traineeDate') || '';
    if (dateCommence) document.getElementById('menopause_dateCommence').value = dateCommence;
    if (tutorName) document.getElementById('menopause_tutorName').value = tutorName;
    if (tutorSignature) document.getElementById('menopause_tutorSignature').value = tutorSignature;
    if (tutorDate) document.getElementById('menopause_tutorDate').value = tutorDate;
    if (traineeName) document.getElementById('menopause_traineeName').value = traineeName;
    if (traineeSignature) document.getElementById('menopause_traineeSignature').value = traineeSignature;
    if (traineeDate) document.getElementById('menopause_traineeDate').value = traineeDate;
    renderMenopausePOF_Table();
}

function saveMenopausePOF_Data() {
    for (let key in menopause_data) {
        localStorage.setItem(`menopause_${key}`, menopause_data[key]);
    }
    const dateCommence = document.getElementById('menopause_dateCommence').value;
    const tutorName = document.getElementById('menopause_tutorName').value;
    const tutorSignature = document.getElementById('menopause_tutorSignature').value;
    const tutorDate = document.getElementById('menopause_tutorDate').value;
    const traineeName = document.getElementById('menopause_traineeName').value;
    const traineeSignature = document.getElementById('menopause_traineeSignature').value;
    const traineeDate = document.getElementById('menopause_traineeDate').value;
    localStorage.setItem('menopause_dateCommence', dateCommence);
    localStorage.setItem('menopause_tutorName', tutorName);
    localStorage.setItem('menopause_tutorSignature', tutorSignature);
    localStorage.setItem('menopause_tutorDate', tutorDate);
    localStorage.setItem('menopause_traineeName', traineeName);
    localStorage.setItem('menopause_traineeSignature', traineeSignature);
    localStorage.setItem('menopause_traineeDate', traineeDate);
}

function renderMenopausePOF_Table() {
    const tbody = document.getElementById('menopause_tableBody');
    if (!tbody) return;
    tbody.innerHTML = '';
    let currentCategory = '';
    menopause_items.forEach((item, index) => {
        const rowNum = index + 1;
        const category = typeof item === 'object' ? item.category : null;
        const itemText = typeof item === 'object' ? item.text : item;
        if (category && category !== currentCategory) {
            currentCategory = category;
            const categoryRow = document.createElement('tr');
            categoryRow.innerHTML = `<td colspan="5" style="border: 1px solid #333; padding: 10px; background: #8B7355; color: white; font-weight: bold; text-align: left;">${category}</td>`;
            tbody.appendChild(categoryRow);
        }
        const dataKey = `item_${rowNum}`;
        const checked1 = menopause_data[`${dataKey}_1`] || '';
        const checked2 = menopause_data[`${dataKey}_2`] || '';
        const checked3 = menopause_data[`${dataKey}_3`] || '';
        const sign = menopause_data[`${dataKey}_sign`] || '';
        const row = document.createElement('tr');
        row.innerHTML = `<td style="border: 1px solid #333; padding: 10px; min-width: 300px;"><span>${rowNum}</span>. ${itemText}</td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="menopause-checkbox" data-key="${dataKey}_1" ${checked1 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="menopause-checkbox" data-key="${dataKey}_2" ${checked2 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="menopause-checkbox" data-key="${dataKey}_3" ${checked3 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; min-width: 200px; height: 60px;"><textarea class="menopause-input" data-key="${dataKey}_sign" rows="3" style="width: 100%; border: none; padding: 6px; resize: none; font-size: 12px;">${sign}</textarea></td>`;
        tbody.appendChild(row);
    });
    tbody.querySelectorAll('.menopause-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', handleMenopausePOF_Change);
    });
    tbody.querySelectorAll('.menopause-input').forEach(input => {
        input.addEventListener('input', handleMenopausePOF_Change);
    });
}

function handleMenopausePOF_Change(event) {
    const key = event.target.dataset.key;
    if (event.target.type === 'checkbox') {
        menopause_data[key] = event.target.checked ? '1' : '';
    } else {
        menopause_data[key] = event.target.value;
    }
    saveMenopausePOF_Data();
}

function printMenopausePOF() {
    let tableRows = '';
    let currentCategory = '';
    menopause_items.forEach((item, index) => {
        const rowNum = index + 1;
        const category = typeof item === 'object' ? item.category : null;
        const itemText = typeof item === 'object' ? item.text : item;
        if (category && category !== currentCategory) {
            currentCategory = category;
            tableRows += `<tr><td colspan="5" style="border: 1px solid #000; padding: 10px; background: #8B7355; color: white; font-weight: bold;">${category}</td></tr>`;
        }
        const dataKey = `item_${rowNum}`;
        const checked1 = menopause_data[`${dataKey}_1`] ? '☑' : '☐';
        const checked2 = menopause_data[`${dataKey}_2`] ? '☑' : '☐';
        const checked3 = menopause_data[`${dataKey}_3`] ? '☑' : '☐';
        const sign = menopause_data[`${dataKey}_sign`] || '';
        tableRows += `<tr><td style="border: 1px solid #000; padding: 10px;">${rowNum}. ${itemText}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked1}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked2}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked3}</td>
                <td style="border: 1px solid #000; padding: 10px; font-size: 11px; white-space: pre-wrap;">${sign}</td></tr>`;
    });
    const dateCommence = document.getElementById('menopause_dateCommence').value;
    const tutorName = document.getElementById('menopause_tutorName').value;
    const tutorSignature = document.getElementById('menopause_tutorSignature').value;
    const tutorDate = document.getElementById('menopause_tutorDate').value;
    const traineeName = document.getElementById('menopause_traineeName').value;
    const traineeSignature = document.getElementById('menopause_traineeSignature').value;
    const traineeDate = document.getElementById('menopause_traineeDate').value;
    const printWindow = window.open('', '_blank');
    if (!printWindow) return;
    printWindow.document.write(`<!DOCTYPE html><html><head><title>Menopause and Premature Ovarian Failure</title><style>body{font-family:Arial,sans-serif;margin:20px;}h1{text-align:center;background:#4a7c59;color:white;padding:12px;margin:0 0 20px 0;}.date-field{margin-bottom:20px;border:1px solid #999;padding:10px;}.date-field span{font-weight:bold;display:inline-block;width:150px;}table{width:100%;border-collapse:collapse;margin-bottom:20px;}th,td{border:1px solid #000;padding:8px;text-align:left;font-size:11px;}th{background:#ffd700;font-weight:bold;}.signature-table{page-break-before:always;}@media print{.signature-table{page-break-before:always;}}.signature-table th{background:#f5f5f5;font-weight:bold;}.signature-table td{height:60px;vertical-align:top;font-size:10px;}</style></head><body><h1>MENOPAUSE AND PREMATURE OVARIAN FAILURE</h1><div class="date-field"><span>Date of commence:</span> <strong>${dateCommence}</strong></div><table><thead><tr style="background:#ffd700;"><th colspan="5" style="text-align:center;background:#ffd700;">REPRODUCTIVE ENDOCRINOLOGY OUTPATIENT CLINIC</th></tr><tr style="background:#ffd700;"><th style="width:45%;">TARGET REQUIRING SIGNATURE</th><th colspan="3" style="text-align:center;">EXPECTED COMPETENCE LEVEL</th><th style="text-align:center;">CERTIFICATION</th></tr><tr style="background:#ffd700;"><th></th><th style="text-align:center;">1</th><th style="text-align:center;">2</th><th style="text-align:center;">3</th><th style="text-align:center;">Sign & Date</th></tr></thead><tbody>${tableRows}</tbody></table><table class="signature-table"><thead><tr><th colspan="3" style="text-align:center;">SIGNATURE TO CONFIRM COMPLETION</th></tr><tr><th>Name of Academic Tutor</th><th>Signature of Academic Tutor</th><th>Date</th></tr></thead><tbody><tr><td>${tutorName}</td><td style="white-space:pre-wrap;font-size:10px;">${tutorSignature}</td><td>${tutorDate}</td></tr><tr style="background:#f5f5f5;"><th>Name of Trainee</th><th>Signature of Trainee</th><th>Date</th></tr><tr><td>${traineeName}</td><td style="white-space:pre-wrap;font-size:10px;">${traineeSignature}</td><td>${traineeDate}</td></tr></tbody></table></body></html>`);
    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => { printWindow.print(); }, 250);
}

document.addEventListener('DOMContentLoaded', function() {
    loadMenopausePOF_Data();
    const formInputs = ['menopause_dateCommence', 'menopause_tutorName', 'menopause_tutorSignature', 'menopause_tutorDate', 'menopause_traineeName', 'menopause_traineeSignature', 'menopause_traineeDate'];
    formInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', saveMenopausePOF_Data);
            element.addEventListener('change', saveMenopausePOF_Data);
        }
    });
});

// ============ ENDOMETRIOSIS ============
const endo_items = [
    { text: 'Etiological theories of endometriosis', category: 'DIAGNOSIS' },
    'Signs and symptoms of endometriosis',
    'Focused physical examination',
    { text: 'Serum Ca125 measurement', category: 'INVESTIGATIONS' },
    'Pelvic MRI and imaging interpretation',
    { text: 'Counselling in endometriosis', category: 'MANAGEMENT' },
    'Progestogen therapy',
    'Combined oral contraceptive pill management',
    'GnRH analogues and add-back therapy',
    'Danazol and other medical treatments',
    { text: 'Pain management strategies', category: 'OTHER ASPECTS' },
    'Infertility management in endometriosis'
];
const endo_data = {};

function openEndometriosis() {
    showSection('endometriosis');
    loadEndometriosis_Data();
}

function loadEndometriosis_Data() {
    for (let key in localStorage) {
        if (key.startsWith('endo_')) {
            const itemKey = key.replace('endo_', '');
            endo_data[itemKey] = localStorage.getItem(key);
        }
    }
    const dateCommence = localStorage.getItem('endo_dateCommence') || '';
    const tutorName = localStorage.getItem('endo_tutorName') || '';
    const tutorSignature = localStorage.getItem('endo_tutorSignature') || '';
    const tutorDate = localStorage.getItem('endo_tutorDate') || '';
    const traineeName = localStorage.getItem('endo_traineeName') || '';
    const traineeSignature = localStorage.getItem('endo_traineeSignature') || '';
    const traineeDate = localStorage.getItem('endo_traineeDate') || '';
    if (dateCommence) document.getElementById('endo_dateCommence').value = dateCommence;
    if (tutorName) document.getElementById('endo_tutorName').value = tutorName;
    if (tutorSignature) document.getElementById('endo_tutorSignature').value = tutorSignature;
    if (tutorDate) document.getElementById('endo_tutorDate').value = tutorDate;
    if (traineeName) document.getElementById('endo_traineeName').value = traineeName;
    if (traineeSignature) document.getElementById('endo_traineeSignature').value = traineeSignature;
    if (traineeDate) document.getElementById('endo_traineeDate').value = traineeDate;
    renderEndometriosis_Table();
}

function saveEndometriosis_Data() {
    for (let key in endo_data) {
        localStorage.setItem(`endo_${key}`, endo_data[key]);
    }
    const dateCommence = document.getElementById('endo_dateCommence').value;
    const tutorName = document.getElementById('endo_tutorName').value;
    const tutorSignature = document.getElementById('endo_tutorSignature').value;
    const tutorDate = document.getElementById('endo_tutorDate').value;
    const traineeName = document.getElementById('endo_traineeName').value;
    const traineeSignature = document.getElementById('endo_traineeSignature').value;
    const traineeDate = document.getElementById('endo_traineeDate').value;
    localStorage.setItem('endo_dateCommence', dateCommence);
    localStorage.setItem('endo_tutorName', tutorName);
    localStorage.setItem('endo_tutorSignature', tutorSignature);
    localStorage.setItem('endo_tutorDate', tutorDate);
    localStorage.setItem('endo_traineeName', traineeName);
    localStorage.setItem('endo_traineeSignature', traineeSignature);
    localStorage.setItem('endo_traineeDate', traineeDate);
}

function renderEndometriosis_Table() {
    const tbody = document.getElementById('endo_tableBody');
    if (!tbody) return;
    tbody.innerHTML = '';
    let currentCategory = '';
    endo_items.forEach((item, index) => {
        const rowNum = index + 1;
        const category = typeof item === 'object' ? item.category : null;
        const itemText = typeof item === 'object' ? item.text : item;
        if (category && category !== currentCategory) {
            currentCategory = category;
            const categoryRow = document.createElement('tr');
            categoryRow.innerHTML = `<td colspan="5" style="border: 1px solid #333; padding: 10px; background: #8B7355; color: white; font-weight: bold; text-align: left;">${category}</td>`;
            tbody.appendChild(categoryRow);
        }
        const dataKey = `item_${rowNum}`;
        const checked1 = endo_data[`${dataKey}_1`] || '';
        const checked2 = endo_data[`${dataKey}_2`] || '';
        const checked3 = endo_data[`${dataKey}_3`] || '';
        const sign = endo_data[`${dataKey}_sign`] || '';
        const row = document.createElement('tr');
        row.innerHTML = `<td style="border: 1px solid #333; padding: 10px; min-width: 300px;"><span>${rowNum}</span>. ${itemText}</td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="endo-checkbox" data-key="${dataKey}_1" ${checked1 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="endo-checkbox" data-key="${dataKey}_2" ${checked2 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="endo-checkbox" data-key="${dataKey}_3" ${checked3 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; min-width: 200px; height: 60px;"><textarea class="endo-input" data-key="${dataKey}_sign" rows="3" style="width: 100%; border: none; padding: 6px; resize: none; font-size: 12px;">${sign}</textarea></td>`;
        tbody.appendChild(row);
    });
    tbody.querySelectorAll('.endo-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', handleEndometriosis_Change);
    });
    tbody.querySelectorAll('.endo-input').forEach(input => {
        input.addEventListener('input', handleEndometriosis_Change);
    });
}

function handleEndometriosis_Change(event) {
    const key = event.target.dataset.key;
    if (event.target.type === 'checkbox') {
        endo_data[key] = event.target.checked ? '1' : '';
    } else {
        endo_data[key] = event.target.value;
    }
    saveEndometriosis_Data();
}

function printEndometriosis() {
    let tableRows = '';
    let currentCategory = '';
    endo_items.forEach((item, index) => {
        const rowNum = index + 1;
        const category = typeof item === 'object' ? item.category : null;
        const itemText = typeof item === 'object' ? item.text : item;
        if (category && category !== currentCategory) {
            currentCategory = category;
            tableRows += `<tr><td colspan="5" style="border: 1px solid #000; padding: 10px; background: #8B7355; color: white; font-weight: bold;">${category}</td></tr>`;
        }
        const dataKey = `item_${rowNum}`;
        const checked1 = endo_data[`${dataKey}_1`] ? '☑' : '☐';
        const checked2 = endo_data[`${dataKey}_2`] ? '☑' : '☐';
        const checked3 = endo_data[`${dataKey}_3`] ? '☑' : '☐';
        const sign = endo_data[`${dataKey}_sign`] || '';
        tableRows += `<tr><td style="border: 1px solid #000; padding: 10px;">${rowNum}. ${itemText}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked1}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked2}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked3}</td>
                <td style="border: 1px solid #000; padding: 10px; font-size: 11px; white-space: pre-wrap;">${sign}</td></tr>`;
    });
    const dateCommence = document.getElementById('endo_dateCommence').value;
    const tutorName = document.getElementById('endo_tutorName').value;
    const tutorSignature = document.getElementById('endo_tutorSignature').value;
    const tutorDate = document.getElementById('endo_tutorDate').value;
    const traineeName = document.getElementById('endo_traineeName').value;
    const traineeSignature = document.getElementById('endo_traineeSignature').value;
    const traineeDate = document.getElementById('endo_traineeDate').value;
    const printWindow = window.open('', '_blank');
    if (!printWindow) return;
    printWindow.document.write(`<!DOCTYPE html><html><head><title>Endometriosis</title><style>body{font-family:Arial,sans-serif;margin:20px;}h1{text-align:center;background:#4a7c59;color:white;padding:12px;margin:0 0 20px 0;}.date-field{margin-bottom:20px;border:1px solid #999;padding:10px;}.date-field span{font-weight:bold;display:inline-block;width:150px;}table{width:100%;border-collapse:collapse;margin-bottom:20px;}th,td{border:1px solid #000;padding:8px;text-align:left;font-size:11px;}th{background:#ffd700;font-weight:bold;}.signature-table{page-break-before:always;}@media print{.signature-table{page-break-before:always;}}.signature-table th{background:#f5f5f5;font-weight:bold;}.signature-table td{height:60px;vertical-align:top;font-size:10px;}</style></head><body><h1>ENDOMETRIOSIS</h1><div class="date-field"><span>Date of commence:</span> <strong>${dateCommence}</strong></div><table><thead><tr style="background:#ffd700;"><th colspan="5" style="text-align:center;background:#ffd700;">REPRODUCTIVE ENDOCRINOLOGY OUTPATIENT CLINIC</th></tr><tr style="background:#ffd700;"><th style="width:45%;">TARGET REQUIRING SIGNATURE</th><th colspan="3" style="text-align:center;">EXPECTED COMPETENCE LEVEL</th><th style="text-align:center;">CERTIFICATION</th></tr><tr style="background:#ffd700;"><th></th><th style="text-align:center;">1</th><th style="text-align:center;">2</th><th style="text-align:center;">3</th><th style="text-align:center;">Sign & Date</th></tr></thead><tbody>${tableRows}</tbody></table><table class="signature-table"><thead><tr><th colspan="3" style="text-align:center;">SIGNATURE TO CONFIRM COMPLETION</th></tr><tr><th>Name of Academic Tutor</th><th>Signature of Academic Tutor</th><th>Date</th></tr></thead><tbody><tr><td>${tutorName}</td><td style="white-space:pre-wrap;font-size:10px;">${tutorSignature}</td><td>${tutorDate}</td></tr><tr style="background:#f5f5f5;"><th>Name of Trainee</th><th>Signature of Trainee</th><th>Date</th></tr><tr><td>${traineeName}</td><td style="white-space:pre-wrap;font-size:10px;">${traineeSignature}</td><td>${traineeDate}</td></tr></tbody></table></body></html>`);
    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => { printWindow.print(); }, 250);
}

document.addEventListener('DOMContentLoaded', function() {
    loadEndometriosis_Data();
    const formInputs = ['endo_dateCommence', 'endo_tutorName', 'endo_tutorSignature', 'endo_tutorDate', 'endo_traineeName', 'endo_traineeSignature', 'endo_traineeDate'];
    formInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', saveEndometriosis_Data);
            element.addEventListener('change', saveEndometriosis_Data);
        }
    });
});

// ============ REPRODUCTIVE SURGERY III ============
const surgeryIII_items = [
    { text: 'Hysteroscopic resection of fibroid', category: 'HYS TEROSCOPIC SURGERY' },
    'Hysteroscopic division of septum',
    'Hysteroscopic division of adhesions',
    { text: 'Deep infiltrating endometriosis excision', category: 'ENDOMETRIOSIS SURGERY' },
    { text: 'Excision of rudimentary horn', category: 'OTHERS' },
    'Hysterectomy for endometriosis management'
];
const surgeryIII_data = {};

function openReprodSurgeryIII() {
    showSection('reprod-surgery-iii');
    loadReprodSurgeryIII_Data();
}

function loadReprodSurgeryIII_Data() {
    for (let key in localStorage) {
        if (key.startsWith('surgeryIII_')) {
            const itemKey = key.replace('surgeryIII_', '');
            surgeryIII_data[itemKey] = localStorage.getItem(key);
        }
    }
    const dateCommence = localStorage.getItem('surgeryIII_dateCommence') || '';
    const tutorName = localStorage.getItem('surgeryIII_tutorName') || '';
    const tutorSignature = localStorage.getItem('surgeryIII_tutorSignature') || '';
    const tutorDate = localStorage.getItem('surgeryIII_tutorDate') || '';
    const traineeName = localStorage.getItem('surgeryIII_traineeName') || '';
    const traineeSignature = localStorage.getItem('surgeryIII_traineeSignature') || '';
    const traineeDate = localStorage.getItem('surgeryIII_traineeDate') || '';
    if (dateCommence) document.getElementById('surgeryIII_dateCommence').value = dateCommence;
    if (tutorName) document.getElementById('surgeryIII_tutorName').value = tutorName;
    if (tutorSignature) document.getElementById('surgeryIII_tutorSignature').value = tutorSignature;
    if (tutorDate) document.getElementById('surgeryIII_tutorDate').value = tutorDate;
    if (traineeName) document.getElementById('surgeryIII_traineeName').value = traineeName;
    if (traineeSignature) document.getElementById('surgeryIII_traineeSignature').value = traineeSignature;
    if (traineeDate) document.getElementById('surgeryIII_traineeDate').value = traineeDate;
    renderReprodSurgeryIII_Table();
}

function saveReprodSurgeryIII_Data() {
    for (let key in surgeryIII_data) {
        localStorage.setItem(`surgeryIII_${key}`, surgeryIII_data[key]);
    }
    const dateCommence = document.getElementById('surgeryIII_dateCommence').value;
    const tutorName = document.getElementById('surgeryIII_tutorName').value;
    const tutorSignature = document.getElementById('surgeryIII_tutorSignature').value;
    const tutorDate = document.getElementById('surgeryIII_tutorDate').value;
    const traineeName = document.getElementById('surgeryIII_traineeName').value;
    const traineeSignature = document.getElementById('surgeryIII_traineeSignature').value;
    const traineeDate = document.getElementById('surgeryIII_traineeDate').value;
    localStorage.setItem('surgeryIII_dateCommence', dateCommence);
    localStorage.setItem('surgeryIII_tutorName', tutorName);
    localStorage.setItem('surgeryIII_tutorSignature', tutorSignature);
    localStorage.setItem('surgeryIII_tutorDate', tutorDate);
    localStorage.setItem('surgeryIII_traineeName', traineeName);
    localStorage.setItem('surgeryIII_traineeSignature', traineeSignature);
    localStorage.setItem('surgeryIII_traineeDate', traineeDate);
}

function renderReprodSurgeryIII_Table() {
    const tbody = document.getElementById('surgeryIII_tableBody');
    if (!tbody) return;
    tbody.innerHTML = '';
    let currentCategory = '';
    surgeryIII_items.forEach((item, index) => {
        const rowNum = index + 1;
        const category = typeof item === 'object' ? item.category : null;
        const itemText = typeof item === 'object' ? item.text : item;
        if (category && category !== currentCategory) {
            currentCategory = category;
            const categoryRow = document.createElement('tr');
            categoryRow.innerHTML = `<td colspan="5" style="border: 1px solid #333; padding: 10px; background: #8B7355; color: white; font-weight: bold; text-align: left;">${category}</td>`;
            tbody.appendChild(categoryRow);
        }
        const dataKey = `item_${rowNum}`;
        const checked1 = surgeryIII_data[`${dataKey}_1`] || '';
        const checked2 = surgeryIII_data[`${dataKey}_2`] || '';
        const checked3 = surgeryIII_data[`${dataKey}_3`] || '';
        const sign = surgeryIII_data[`${dataKey}_sign`] || '';
        const row = document.createElement('tr');
        row.innerHTML = `<td style="border: 1px solid #333; padding: 10px; min-width: 300px;"><span>${rowNum}</span>. ${itemText}</td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="surgeryIII-checkbox" data-key="${dataKey}_1" ${checked1 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="surgeryIII-checkbox" data-key="${dataKey}_2" ${checked2 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; text-align: center; width: 60px;"><input type="checkbox" class="surgeryIII-checkbox" data-key="${dataKey}_3" ${checked3 ? 'checked' : ''}></td>
            <td style="border: 1px solid #333; padding: 10px; min-width: 200px; height: 60px;"><textarea class="surgeryIII-input" data-key="${dataKey}_sign" rows="3" style="width: 100%; border: none; padding: 6px; resize: none; font-size: 12px;">${sign}</textarea></td>`;
        tbody.appendChild(row);
    });
    tbody.querySelectorAll('.surgeryIII-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', handleReprodSurgeryIII_Change);
    });
    tbody.querySelectorAll('.surgeryIII-input').forEach(input => {
        input.addEventListener('input', handleReprodSurgeryIII_Change);
    });
}

function handleReprodSurgeryIII_Change(event) {
    const key = event.target.dataset.key;
    if (event.target.type === 'checkbox') {
        surgeryIII_data[key] = event.target.checked ? '1' : '';
    } else {
        surgeryIII_data[key] = event.target.value;
    }
    saveReprodSurgeryIII_Data();
}

function printReprodSurgeryIII() {
    let tableRows = '';
    let currentCategory = '';
    surgeryIII_items.forEach((item, index) => {
        const rowNum = index + 1;
        const category = typeof item === 'object' ? item.category : null;
        const itemText = typeof item === 'object' ? item.text : item;
        if (category && category !== currentCategory) {
            currentCategory = category;
            tableRows += `<tr><td colspan="5" style="border: 1px solid #000; padding: 10px; background: #8B7355; color: white; font-weight: bold;">${category}</td></tr>`;
        }
        const dataKey = `item_${rowNum}`;
        const checked1 = surgeryIII_data[`${dataKey}_1`] ? '☑' : '☐';
        const checked2 = surgeryIII_data[`${dataKey}_2`] ? '☑' : '☐';
        const checked3 = surgeryIII_data[`${dataKey}_3`] ? '☑' : '☐';
        const sign = surgeryIII_data[`${dataKey}_sign`] || '';
        tableRows += `<tr><td style="border: 1px solid #000; padding: 10px;">${rowNum}. ${itemText}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked1}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked2}</td>
                <td style="border: 1px solid #000; padding: 10px; text-align: center;">${checked3}</td>
                <td style="border: 1px solid #000; padding: 10px; font-size: 11px; white-space: pre-wrap;">${sign}</td></tr>`;
    });
    const dateCommence = document.getElementById('surgeryIII_dateCommence').value;
    const tutorName = document.getElementById('surgeryIII_tutorName').value;
    const tutorSignature = document.getElementById('surgeryIII_tutorSignature').value;
    const tutorDate = document.getElementById('surgeryIII_tutorDate').value;
    const traineeName = document.getElementById('surgeryIII_traineeName').value;
    const traineeSignature = document.getElementById('surgeryIII_traineeSignature').value;
    const traineeDate = document.getElementById('surgeryIII_traineeDate').value;
    const printWindow = window.open('', '_blank');
    if (!printWindow) return;
    printWindow.document.write(`<!DOCTYPE html><html><head><title>Reproductive Surgery III</title><style>body{font-family:Arial,sans-serif;margin:20px;}h1{text-align:center;background:#4a7c59;color:white;padding:12px;margin:0 0 20px 0;}.date-field{margin-bottom:20px;border:1px solid #999;padding:10px;}.date-field span{font-weight:bold;display:inline-block;width:150px;}table{width:100%;border-collapse:collapse;margin-bottom:20px;}th,td{border:1px solid #000;padding:8px;text-align:left;font-size:11px;}th{background:#ffd700;font-weight:bold;}.signature-table{page-break-before:always;}@media print{.signature-table{page-break-before:always;}}.signature-table th{background:#f5f5f5;font-weight:bold;}.signature-table td{height:60px;vertical-align:top;font-size:10px;}</style></head><body><h1>REPRODUCTIVE SURGERY III</h1><div class="date-field"><span>Date of commence:</span> <strong>${dateCommence}</strong></div><table><thead><tr style="background:#ffd700;"><th colspan="5" style="text-align:center;background:#ffd700;">REPRODUCTIVE ENDOCRINOLOGY OUTPATIENT CLINIC</th></tr><tr style="background:#ffd700;"><th style="width:45%;">TARGET REQUIRING SIGNATURE</th><th colspan="3" style="text-align:center;">EXPECTED COMPETENCE LEVEL</th><th style="text-align:center;">CERTIFICATION</th></tr><tr style="background:#ffd700;"><th></th><th style="text-align:center;">1</th><th style="text-align:center;">2</th><th style="text-align:center;">3</th><th style="text-align:center;">Sign & Date</th></tr></thead><tbody>${tableRows}</tbody></table><table class="signature-table"><thead><tr><th colspan="3" style="text-align:center;">SIGNATURE TO CONFIRM COMPLETION</th></tr><tr><th>Name of Academic Tutor</th><th>Signature of Academic Tutor</th><th>Date</th></tr></thead><tbody><tr><td>${tutorName}</td><td style="white-space:pre-wrap;font-size:10px;">${tutorSignature}</td><td>${tutorDate}</td></tr><tr style="background:#f5f5f5;"><th>Name of Trainee</th><th>Signature of Trainee</th><th>Date</th></tr><tr><td>${traineeName}</td><td style="white-space:pre-wrap;font-size:10px;">${traineeSignature}</td><td>${traineeDate}</td></tr></tbody></table></body></html>`);
    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => { printWindow.print(); }, 250);
}

document.addEventListener('DOMContentLoaded', function() {
    loadReprodSurgeryIII_Data();
    const formInputs = ['surgeryIII_dateCommence', 'surgeryIII_tutorName', 'surgeryIII_tutorSignature', 'surgeryIII_tutorDate', 'surgeryIII_traineeName', 'surgeryIII_traineeSignature', 'surgeryIII_traineeDate'];
    formInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('input', saveReprodSurgeryIII_Data);
            element.addEventListener('change', saveReprodSurgeryIII_Data);
        }
    });
});


