// Global variables
let currentDate = new Date();
let currentMonth = currentDate.getMonth();
let currentYear = currentDate.getFullYear();
let selectedDate = null;
let allActivityTypes = [];
let currentUserRole = 'trainee';
let currentUserId = null;
let currentLogEditId = null;
let currentLogEditOwnerId = null;
const traineeLogCache = new Map();
const traineePortfolioCache = new Map();
let logSignatureCanvas = null;
let logSignatureCtx = null;
let isDrawingLogSignature = false;

// Initialize app
document.addEventListener('DOMContentLoaded', function() {
    checkSession();
    loadActivityTypes();
    initializeCalendar();
    initializeLogForm();
    initializeProfileSections();
    initializeAutoDismiss();
});

// Check if user is logged in
function checkSession() {
    fetch('php/session.php')
        .then(response => response.json())
        .then(data => {
            if (!data.authenticated) {
                window.location.href = 'login.html';
                return;
            }
            
            // Store user role and id for later use
            currentUserRole = data.role || 'trainee';
            currentUserId = data.user_data?.id || null;
            window.currentUserRole = currentUserRole;
            window.currentUserId = currentUserId;
            window.currentUserSupervisorInitial = data.user_data?.supervisor_initial || null;
            
            // Debug logging for session
            console.log('Session loaded:', {
                role: currentUserRole,
                userId: currentUserId,
                supervisorInitial: window.currentUserSupervisorInitial,
                fullName: data.user_data?.full_name
            });
            try {
                if (currentUserId) {
                    sessionStorage.setItem('elogbook_current_user_id', String(currentUserId));
                } else {
                    sessionStorage.removeItem('elogbook_current_user_id');
                }
            } catch (error) {
                // ignore sessionStorage errors
            }
            window.dispatchEvent(new CustomEvent('elogbook:user-ready', {
                detail: { userId: currentUserId, role: currentUserRole }
            }));
            
            // Check if user is admin - redirect to admin panel
            if (data.role === 'admin') {
                window.location.href = 'admin.html';
                return;
            }
            
            // Update display with user data
            if (data.user_data) {
                updateUserDisplay(data.user_data);
            }
        })
        .catch(error => {
            console.error('Session check failed:', error);
            // Fallback to demo data for testing
            const userData = {
                full_name: 'dr. Zulfadli, Sp.OG',
                specialization: 'Obstetri dan Ginekologi',
                semester: 2,
                username: 'zulfadli'
            };
            updateUserDisplay(userData);
        });
}

// Update user display
function updateUserDisplay(userData) {
    // Update header
    const userName = document.getElementById('userName');
    if (userName) userName.textContent = userData.full_name || 'User';
    
    // Update sidebar
    const userNameFull = document.getElementById('userNameFull');
    if (userNameFull) userNameFull.textContent = userData.full_name || 'User';
    
    const userSpec = document.getElementById('userSpec');
    if (userSpec) userSpec.textContent = userData.specialization || 'Subspesialisasi';
    
    // Update role display
    const userRole = document.getElementById('userRole');
    if (userRole) {
        const roleLabels = {
            'trainee': 'Trainee (Peserta PPDS-2)',
            'dosen': 'Dosen (Pendidik PPDS-2)',
            'admin': 'Admin'
        };
        userRole.textContent = roleLabels[currentUserRole] || 'Trainee (Peserta PPDS-2)';
    }
    
    // Show trainee logbooks menu for dosen users
    const traineeLogsMenu = document.getElementById('trainee-logbooks-menu');
    if (traineeLogsMenu) {
        traineeLogsMenu.style.display = (currentUserRole === 'dosen') ? 'block' : 'none';
    }
    
    // Hide DIVISI & SUBSPESIALISASI menu section for dosen users (show only NAVIGASI UTAMA)
    if (currentUserRole === 'dosen') {
        const divisiMenuSection = document.querySelector('.sidebar-menu .menu-section:nth-of-type(2)');
        if (divisiMenuSection) {
            divisiMenuSection.style.display = 'none';
        }
    } else {
        // For trainee users, filter subspecialty menu items based on specialization
        filterSubspecialtyMenu(userData.specialization);
    }
    
    // Get initial for avatar
    const initial = (userData.full_name || 'U').charAt(0).toUpperCase();
    const userInitial = document.getElementById('userInitial');
    const userInitialLarge = document.getElementById('userInitialLarge');
    
    if (userInitial) userInitial.textContent = initial;
    if (userInitialLarge) userInitialLarge.textContent = initial;
    
    // Update welcome section
    const welcomeName = document.getElementById('welcomeName');
    if (welcomeName) welcomeName.textContent = userData.full_name || 'User';
    
    // Update statistics
    const statSemester = document.getElementById('statSemester');
    if (statSemester) statSemester.textContent = userData.semester || '-';
    
    // Initialize dashboard with correct role
    initializeDashboard();
}

// Filter subspecialty menu items to show only the user's specialization
function filterSubspecialtyMenu(userSpecialization) {
    // Map specialization to menu item ID prefix
    const specializationMap = {
        'Fertilitas Endokrinologi dan Reproduksi': 'fertilitas',
        'Fetomaternal': 'fetomaternal',
        'Onkologi Ginekologi': 'onkologi',
        'Obstetri Ginekologi Sosial': 'sosial',
        'Uroginekologi': 'uroginekologi'
    };
    
    // Get the matching menu item ID
    const matchingMenuId = specializationMap[userSpecialization];
    
    // Get all subspecialty menu items (li with class menu-item-with-submenu under divisi-menu)
    const divisiMenu = document.getElementById('divisi-menu');
    if (!divisiMenu) return;
    
    const allMenuItems = divisiMenu.querySelectorAll(':scope > li.menu-item-with-submenu');
    
    // Hide/Show menu items based on match
    allMenuItems.forEach(item => {
        const submenu = item.querySelector('.submenu');
        if (submenu) {
            const submenuId = submenu.id;
            // Show only if this item's submenu ID matches the user's specialization
            if (submenuId === matchingMenuId + '-submenu') {
                item.style.display = 'block';
            } else {
                item.style.display = 'none';
            }
        }
    });
}

// Load activity types
function loadActivityTypes() {
    fetch('php/api.php?action=get_activity_types')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                allActivityTypes = data.data;
                populateActivityTypeSelect(data.data);
            }
        })
        .catch(error => console.error('Error:', error));
}

// Populate activity type select
function populateActivityTypeSelect(activities) {
    const select = document.getElementById('activityType');
    if (!select) return;
    
    // Group by category
    const grouped = {};
    activities.forEach(activity => {
        if (!grouped[activity.category_name]) {
            grouped[activity.category_name] = [];
        }
        grouped[activity.category_name].push(activity);
    });
    
    // Create optgroups
    Object.keys(grouped).forEach(category => {
        const optgroup = document.createElement('optgroup');
        optgroup.label = category;
        
        grouped[category].forEach(activity => {
            const option = document.createElement('option');
            option.value = activity.id;
            option.textContent = activity.type_name;
            optgroup.appendChild(option);
        });
        
        select.appendChild(optgroup);
    });
}

// Initialize dashboard
function initializeDashboard() {
    // Show/hide stats based on role
    const traineeStatsDiv = document.getElementById('trainee-stats');
    const dosenStatsDiv = document.getElementById('dosen-stats');
    
    if (!traineeStatsDiv || !dosenStatsDiv) {
        // Elements not found, skip dashboard initialization
        return;
    }
    
    if (currentUserRole === 'dosen' || currentUserRole === 'admin') {
        traineeStatsDiv.style.display = 'none';
        dosenStatsDiv.style.display = 'grid';
        loadDosenStatistics();
    } else {
        traineeStatsDiv.style.display = 'grid';
        dosenStatsDiv.style.display = 'none';
        loadStatistics();
    }
    
    loadRecentActivities();
}

// Load statistics
function loadStatistics() {
    const year = new Date().getFullYear();
    fetch(`php/logbook.php?action=get_stats&year=${year}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const stats = data.data;
                document.getElementById('statLogs').textContent = stats.total_logs || 0;
                document.getElementById('statCases').textContent = stats.total_cases || 0;
            }
        })
        .catch(error => console.error('Error:', error));
}

// Load statistics for dosen
function loadDosenStatistics() {
    const year = new Date().getFullYear();
    fetch(`php/logbook.php?action=get_dosen_stats&year=${year}`)
        .then(response => response.json())
        .then(data => {
            console.log('Dosen stats response:', data);
            if (data.success) {
                const stats = data.data;
                document.getElementById('statTotalTrainee').textContent = stats.total_trainees || 0;
                document.getElementById('statUnverified').textContent = stats.unverified_logs || 0;
                document.getElementById('statVerified').textContent = stats.verified_logs || 0;
                document.getElementById('statActivityToday').textContent = stats.today_activities || 0;
            } else {
                console.error('Error loading dosen stats:', data.message);
            }
        })
        .catch(error => console.error('Error:', error));
}

// Load recent activities
function loadRecentActivities() {
    // For trainee: load their own logs and portfolio
    // For dosen/admin: load from trainee endpoint that shows accessible units
    let logsUrl, portfolioUrl;
    
    if (currentUserRole === 'trainee') {
        logsUrl = 'php/api.php?action=get_logs&all=1';
        portfolioUrl = 'php/portfolio.php?action=list';
    } else {
        // For dosen/admin: use endpoints that return trainee data they can access
        logsUrl = 'php/logbook.php?action=get_logbooks&all=1';
        portfolioUrl = 'php/portfolio.php?action=list_all';
    }
    
    Promise.all([
        fetch(logsUrl).then(r => r.json()),
        fetch(portfolioUrl).then(r => r.json())
    ])
    .then(([logsData, portfolioData]) => {
        console.log('Logs data:', logsData);
        console.log('Portfolio data:', portfolioData);
        
        const activities = [];
        
        // Add logs
        if (logsData.success && logsData.data && Array.isArray(logsData.data)) {
            logsData.data.forEach(log => {
                const createdAt = log.created_at || log.log_date;
                const updatedAt = log.updated_at || createdAt;
                const isUpdated = new Date(updatedAt) > new Date(createdAt);
                activities.push({
                    type: 'logbook',
                    date: log.log_date || log.tanggal,
                    title: log.title,
                    category: log.category_name || log.type_name || 'Logbook',
                    menu: 'Buku Log',
                    action: isUpdated ? 'Diubah' : 'Ditambah',
                    timestamp: updatedAt
                });
                
                // If logbook is verified, add separate verification activity
                if (log.dpjp_verified && log.dpjp_verified_at) {
                    activities.push({
                        type: 'logbook',
                        date: log.log_date || log.tanggal,
                        title: log.title,
                        category: log.category_name || log.type_name || 'Logbook',
                        menu: 'Buku Log',
                        action: 'Diverifikasi',
                        timestamp: log.dpjp_verified_at
                    });
                }
            });
        }
        
        // Add portfolio entries
        if (portfolioData.success && portfolioData.data && Array.isArray(portfolioData.data)) {
            portfolioData.data.forEach(item => {
                const settingLabelMap = {
                    'OK': 'Kamar Operasi',
                    'Poliklinik': 'Poliklinik',
                    'Rawat_Inap': 'Rawat Inap/Bangsal'
                };
                const submenuLabel = settingLabelMap[item.setting_type] || item.setting_type || 'Portfolio';
                const createdAt = item.created_at || item.tanggal;
                const updatedAt = item.updated_at || createdAt;
                const isUpdated = new Date(updatedAt) > new Date(createdAt);
                
                // Add main portfolio activity (created/updated)
                activities.push({
                    type: 'portfolio',
                    date: item.tanggal,
                    title: item.diagnosis || `Portfolio ${item.setting_type}`,
                    category: submenuLabel,
                    menu: 'Portfolio',
                    action: isUpdated ? 'Diubah' : 'Ditambah',
                    timestamp: updatedAt
                });
                
                // If portfolio is verified, add separate verification activity
                if (item.dpjp_verified && item.dpjp_verified_at) {
                    activities.push({
                        type: 'portfolio',
                        date: item.tanggal,
                        title: item.diagnosis || `Portfolio ${item.setting_type}`,
                        category: submenuLabel,
                        menu: 'Portfolio',
                        action: 'Diverifikasi',
                        timestamp: item.dpjp_verified_at
                    });
                }
            });
        }
        
        // Sort by activity timestamp descending (newest first)
        activities.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
        
        console.log('Final activities:', activities);
        displayRecentActivities(activities);
    })
    .catch(error => {
        console.error('Error loading recent activities:', error);
        const container = document.getElementById('recentActivities');
        if (container) {
            container.innerHTML = '<p class="text-danger">Error memuat aktivitas</p>';
        }
    });
}

// Display recent activities
function displayRecentActivities(activities) {
    const container = document.getElementById('recentActivities');
    if (!container) return;
    
    if (activities.length === 0) {
        container.innerHTML = '<p class="text-muted">Belum ada aktivitas</p>';
        return;
    }
    
    // Get last 5 recent activities
    const recentActivities = activities.slice(0, 5);
    
    container.innerHTML = recentActivities.map(activity => {
        const typeIcon = activity.type === 'logbook' ? '📖' : '📁';
        const submenuSuffix = activity.type === 'portfolio' && activity.category
            ? ` (${activity.category})`
            : '';
        
        return `
            <div class="activity-item">
                <div class="activity-date">${formatDateTime(activity.timestamp)}</div>
                <div class="activity-title">${typeIcon} ${activity.action}: ${activity.title}${submenuSuffix}</div>
                <span class="log-category">${activity.category}</span>
                <span class="log-type">${activity.menu}</span>
            </div>
        `;
    }).join('');
}

// Load trainee logbooks (for dosen only)
function loadTraineeLogbooks() {
    if (currentUserRole !== 'dosen') return;
    
    const container = document.getElementById('traineeLogsContainer');
    if (!container) return;
    
    container.innerHTML = '<p class="text-muted">Memuat daftar trainee...</p>';
    
    // Load list of trainees
    fetch('php/logbook.php?action=get_trainees')
        .then(r => r.json())
        .then(data => {
            if (!data.success || !Array.isArray(data.data) || data.data.length === 0) {
                container.innerHTML = '<p class="text-muted">Belum ada trainee dengan subspesialisasi yang sama</p>';
                return;
            }
            
            displayTraineeCards(data.data);
        })
        .catch(error => {
            console.error('Error loading trainees:', error);
            container.innerHTML = '<p class="text-muted">Error memuat data trainee</p>';
        });
}

// Display trainee cards
function displayTraineeCards(trainees) {
    const container = document.getElementById('traineeLogsContainer');
    if (!container || !trainees || trainees.length === 0) {
        container.innerHTML = '<p class="text-muted">Belum ada trainee dengan subspesialisasi yang sama</p>';
        return;
    }
    
    container.innerHTML = `
        <div class="trainee-cards-container">
            ${trainees.map(trainee => {
                const safeName = (trainee.full_name || 'Trainee').replace(/'/g, '&#39;');
                return `
                    <div class="trainee-card" onclick="loadSpecificTraineeLogbooks(${trainee.id}, '${safeName}')">
                        <div class="trainee-card-header">
                            <div class="trainee-initial">${(trainee.full_name || 'T').charAt(0).toUpperCase()}</div>
                            <div class="trainee-card-info">
                                <div class="trainee-card-name">${trainee.full_name || 'Trainee'}</div>
                                <div class="trainee-card-specialization">${trainee.specialization || '-'}</div>
                                <div class="trainee-card-semester">Semester ${trainee.semester || '-'}</div>
                            </div>
                        </div>
                        <div class="trainee-card-footer">
                            <span class="trainee-card-link">Klik untuk melihat logbook →</span>
                        </div>
                    </div>
                `;
            }).join('')}
        </div>
    `;
}

// Load specific trainee's logbooks
function loadSpecificTraineeLogbooks(traineeId, traineeName) {
    const container = document.getElementById('traineeLogsContainer');
    if (!container) return;
    
    container.innerHTML = `
        <div class="trainee-logbooks-header">
            <button class="btn btn-secondary" onclick="loadTraineeLogbooks()">← Kembali ke Daftar Trainee</button>
            <h3>Logbook & Portfolio: ${traineeName}</h3>
        </div>
        <p class="text-muted">Memuat data...</p>
    `;
    
    Promise.all([
        fetch(`php/logbook.php?action=get_logbooks&all=1&sort=unverified_first`).then(r => r.json()),
        fetch('php/portfolio.php?action=list_all').then(r => r.json())
    ])
        .then(([logData, portfolioData]) => {
            const items = [];
            
            if (logData.success && Array.isArray(logData.data)) {
                logData.data
                    .filter(log => log.user_id === traineeId)
                    .forEach(log => {
                        items.push({
                            type: 'logbook',
                            id: log.id,
                            user_id: log.user_id,
                            full_name: log.full_name,
                            specialization: log.specialization,
                            date: log.log_date,
                            timestamp: log.updated_at || log.created_at || log.log_date,
                            title: log.title,
                            description: log.description,
                            location: log.location,
                            supervisor_name: log.supervisor_name,
                            supervisor_initial: log.supervisor_initial,
                            case_count: log.case_count,
                            status: log.status,
                            category_name: log.category_name,
                            type_name: log.type_name,
                            is_verified: log.dpjp_verified === true || log.dpjp_verified === 1,
                            dpjp_verified_by: log.dpjp_verified_by,
                            verified_by_me: parseInt(log.dpjp_verified_by) === parseInt(window.currentUserId)
                        });
                    });
            }
            
            if (portfolioData.success && Array.isArray(portfolioData.data)) {
                portfolioData.data
                    .filter(item => item.user_id === traineeId)
                    .forEach(item => {
                        items.push({
                            type: 'portfolio',
                            id: item.id,
                            user_id: item.user_id,
                            full_name: item.user_name,
                            specialization: item.specialization,
                            date: item.tanggal,
                            timestamp: item.updated_at || item.created_at || item.tanggal,
                            title: item.diagnosis || 'Portofolio',
                            tatalaksana: item.tatalaksana,
                            kompetenszi: item.kompetenszi,
                            supervisor_name: item.supervisor_name,
                            supervisor_initial: item.supervisor_initial,
                            status: item.status,
                            setting_type: item.setting_type,
                            is_verified: item.dpjp_verified === true || item.dpjp_verified === 1,
                            dpjp_verified_by: item.dpjp_verified_by,
                            verified_by_me: parseInt(item.dpjp_verified_by) === parseInt(window.currentUserId)
                        });
                    });
            }
            
            if (items.length === 0) {
                container.innerHTML = `
                    <div class="trainee-logbooks-header">
                        <button class="btn btn-secondary" onclick="loadTraineeLogbooks()">← Kembali ke Daftar Trainee</button>
                        <h3>Logbook & Portfolio: ${traineeName}</h3>
                    </div>
                    <p class="text-muted">Belum ada logbook atau portofolio yang memerlukan verifikasi</p>
                `;
                return;
            }
            
            items.sort((a, b) => {
                if (a.is_verified !== b.is_verified) {
                    return a.is_verified ? 1 : -1;
                }
                return new Date(b.timestamp || b.date) - new Date(a.timestamp || a.date);
            });
            
            displaySpecificTraineeLogbooks(items, traineeName);
        })
        .catch(error => {
            console.error('Error loading trainee logbooks:', error);
            container.innerHTML = `
                <div class="trainee-logbooks-header">
                    <button class="btn btn-secondary" onclick="loadTraineeLogbooks()">← Kembali ke Daftar Trainee</button>
                    <h3>Logbook & Portfolio: ${traineeName}</h3>
                </div>
                <p class="text-muted">Error memuat data</p>
            `;
        });
}

// Display specific trainee's logbooks
function displaySpecificTraineeLogbooks(items, traineeName) {
    const container = document.getElementById('traineeLogsContainer');
    if (!container || !items || items.length === 0) {
        return;
    }

    traineeLogCache.clear();
    traineePortfolioCache.clear();
    items.filter(item => item.type === 'logbook').forEach(log => traineeLogCache.set(log.id, log));
    items.filter(item => item.type === 'portfolio').forEach(portfolio => traineePortfolioCache.set(portfolio.id, portfolio));

    // Count verified items - for dosen, only count cases where they are the DPJP
    const isDosen = currentUserRole === 'dosen';
    let verifiedByMeCount = 0;
    let unverifiedCount = 0;
    
    if (isDosen) {
        // Filter only cases where current dosen is the DPJP
        const myCases = items.filter(item => item.supervisor_initial === window.currentUserSupervisorInitial);
        verifiedByMeCount = myCases.filter(item => item.verified_by_me).length;
        unverifiedCount = myCases.filter(item => !item.is_verified).length;
    } else {
        // For non-dosen users, count all verified/unverified
        verifiedByMeCount = items.filter(item => item.is_verified).length;
        unverifiedCount = items.filter(item => !item.is_verified).length;
    }

    const settingLabelMap = {
        'OK': 'Kamar Operasi',
        'Poliklinik': 'Poliklinik',
        'Rawat_Inap': 'Rawat Inap/Bangsal'
    };

    const itemsHtml = items.map(item => {
        const name = item.full_name || 'Trainee';
        const safeName = name.replace(/'/g, '&#39;');
        const dateLabel = formatDateTime(item.timestamp || item.date);
        const isPortfolio = item.type === 'portfolio';
        const category = isPortfolio ? 'Portofolio' : (item.category_name || 'Logbook');
        const typeLabel = isPortfolio
            ? (settingLabelMap[item.setting_type] || item.setting_type || 'Portofolio')
            : (item.type_name || 'Logbook');
        
        // Create verification badge based on who verified it
        let verifyBadge;
        const supervisorBadge = item.supervisor_name ? `<span class="supervisor-badge" style="background-color: #f0f0f0; color: #555; padding: 4px 8px; border-radius: 3px; font-size: 12px; margin-left: 8px;">DPJP: ${item.supervisor_name}</span>` : '';
        
        if (item.verified_by_me) {
            verifyBadge = `<span class="log-verified-badge">✓ Sudah Diverifikasi oleh Saya</span>${supervisorBadge}`;
        } else if (item.is_verified) {
            verifyBadge = `<span class="log-verified-badge" style="background-color: #d3d3d3; color: #666;">✓ Diverifikasi oleh Supervisor Lain</span>${supervisorBadge}`;
        } else {
            verifyBadge = `<span class="log-unverified-badge blink">✗ BELUM DIVERIFIKASI</span>${supervisorBadge}`;
        }

        // Check if current user is the supervisor for this case
        const isSupervisor = item.supervisor_initial === window.currentUserSupervisorInitial;
        
        // Debug logging
        if (window.currentUserRole === 'dosen') {
            console.log('Debug Button Access:', {
                case_title: item.title,
                item_supervisor_initial: item.supervisor_initial,
                current_user_supervisor_initial: window.currentUserSupervisorInitial,
                isSupervisor: isSupervisor
            });
        }
        
        const disabledAttr = !isSupervisor ? 'disabled' : '';
        const disabledStyle = !isSupervisor ? 'opacity: 0.5; cursor: not-allowed;' : '';
        const disabledTitle = !isSupervisor ? 'title="Hanya DPJP yang ditunjuk yang dapat melakukan ini"' : '';

        const actions = isPortfolio
            ? `
                <button class="btn btn-sm btn-primary" onclick="openPortfolioForm(${item.id})" ${disabledAttr} style="${disabledStyle}" ${disabledTitle}>Edit</button>
                <button class="btn btn-sm btn-secondary" onclick="openTraineeItemTable('portfolio', ${item.id})">View</button>
                <button class="btn btn-sm btn-success" onclick="openPortfolioForm(${item.id})" ${disabledAttr} style="${disabledStyle}" ${disabledTitle}>Verifikasi & TTD</button>
                <button class="btn btn-sm btn-info" onclick="openMessageModal('portfolio', ${item.id}, ${item.user_id}, '${safeName}')" ${disabledAttr} style="${disabledStyle}" ${disabledTitle}>Pesan</button>
            `
            : `
                <button class="btn btn-sm btn-primary" onclick="openEditLogModal(${item.id})" ${disabledAttr} style="${disabledStyle}" ${disabledTitle}>Edit</button>
                <button class="btn btn-sm btn-secondary" onclick="openTraineeItemTable('logbook', ${item.id})">View</button>
                <button class="btn btn-sm btn-success" onclick="openVerifyLogModal(${item.id})" ${disabledAttr} style="${disabledStyle}" ${disabledTitle}>Verifikasi & TTD</button>
                <button class="btn btn-sm btn-info" onclick="openMessageModal('logbook', ${item.id}, ${item.user_id}, '${safeName}')" ${disabledAttr} style="${disabledStyle}" ${disabledTitle}>Pesan</button>
            `;

        return `
            <div class="activity-item trainee-log">
                <div class="trainee-info">
                    <strong>${name}</strong> <small>(${item.specialization || '-'})</small>
                    <div class="log-date">${dateLabel}</div>
                </div>
                <div class="activity-title">${item.title}</div>
                <div style="display: flex; gap: 8px; flex-wrap: wrap; margin: 8px 0;">
                    <span class="log-category">${category}</span>
                    <span class="log-type">${typeLabel}</span>
                </div>
                <div style="display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin: 6px 0;">
                    ${verifyBadge}
                </div>
                <div class="trainee-log-actions" style="margin-top: 8px; display: flex; gap: 8px; flex-wrap: wrap;">
                    ${actions}
                </div>
            </div>
        `;
    }).join('');
    
    // Calculate total for display (for dosen, only count their supervised cases)
    const totalForDisplay = isDosen 
        ? items.filter(item => item.supervisor_initial === window.currentUserSupervisorInitial).length
        : items.length;
    
    container.innerHTML = `
        <div class="trainee-logbooks-header">
            <button class="btn btn-secondary" onclick="loadTraineeLogbooks()">← Kembali ke Daftar Trainee</button>
            <div style="flex: 1;">
                <h3>Logbook & Portfolio: ${traineeName}</h3>
                <div class="verification-summary">
                    <span class="summary-verified">✓ Diverifikasi oleh saya: <strong>${verifiedByMeCount}</strong></span>
                    <span class="summary-unverified ${unverifiedCount > 0 ? 'blink' : ''}">✗ Belum Diverifikasi: <strong>${unverifiedCount}</strong></span>
                    <span class="summary-total">Total: <strong>${totalForDisplay}</strong></span>
                </div>
            </div>
        </div>
        ${itemsHtml}
    `;
}

function openTraineeItemTable(type, itemId) {
    const modal = document.getElementById('traineeItemTableModal');
    const titleEl = document.getElementById('traineeItemTableTitle');
    const tbody = document.getElementById('traineeItemTableBody');

    if (!modal || !titleEl || !tbody) return;

    const item = type === 'portfolio'
        ? traineePortfolioCache.get(itemId)
        : traineeLogCache.get(itemId);

    if (!item) {
        showNotification('Data item tidak ditemukan', 'error');
        return;
    }

    const verifyLabel = item.is_verified ? 'Sudah Diverifikasi' : 'Belum Diverifikasi';
    const settingLabelMap = {
        'OK': 'Kamar Operasi',
        'Poliklinik': 'Poliklinik',
        'Rawat_Inap': 'Rawat Inap/Bangsal'
    };

    const rows = [];
    rows.push(['Nama', item.full_name || '-']);
    rows.push(['Subspesialisasi', item.specialization || '-']);
    rows.push(['Tanggal', formatDate(item.date)]);
    rows.push(['Timestamp', formatDateTime(item.timestamp || item.date)]);

    if (type === 'portfolio') {
        rows.push(['Jenis Portofolio', settingLabelMap[item.setting_type] || item.setting_type || '-']);
        rows.push(['Diagnosis', item.title || '-']);
        rows.push(['Tatalaksana', item.tatalaksana || '-']);
        rows.push(['Kompetensi', item.kompetenszi || '-']);
        rows.push(['Pembimbing', item.supervisor_name || '-']);
        rows.push(['Status Verifikasi', verifyLabel]);
        rows.push(['Status', item.status || '-']);
        titleEl.textContent = 'Detail Portofolio Trainee';
    } else {
        rows.push(['Jenis Aktivitas', item.type_name || '-']);
        rows.push(['Kategori', item.category_name || '-']);
        rows.push(['Judul', item.title || '-']);
        rows.push(['Deskripsi', item.description || '-']);
        rows.push(['Lokasi', item.location || '-']);
        rows.push(['Pembimbing', item.supervisor_name || '-']);
        rows.push(['Jumlah Kasus', item.case_count || '-']);
        rows.push(['Status Verifikasi', verifyLabel]);
        rows.push(['Status', item.status || '-']);
        titleEl.textContent = 'Detail Logbook Trainee';
    }

    tbody.innerHTML = rows.map(([label, value]) => `
        <tr>
            <th style="width: 35%;">${label}</th>
            <td>${value}</td>
        </tr>
    `).join('');

    modal.style.display = 'flex';
}

function closeTraineeItemTableModal() {
    const modal = document.getElementById('traineeItemTableModal');
    if (!modal) return;
    modal.style.display = 'none';
}

function openEditLogModal(logId) {
    const log = traineeLogCache.get(logId);
    if (!log) {
        showNotification('Data log tidak ditemukan', 'error');
        return;
    }

    currentLogEditId = logId;
    currentLogEditOwnerId = log.user_id;

    const logIdInput = document.getElementById('logId');
    const logOwnerInput = document.getElementById('logOwnerId');
    if (logIdInput) logIdInput.value = logId;
    if (logOwnerInput) logOwnerInput.value = log.user_id;

    const modalTitle = document.querySelector('#logModal .modal-header h2');
    if (modalTitle) {
        modalTitle.textContent = `Edit Log - ${log.full_name}`;
    }

    document.getElementById('logDate').value = log.log_date || '';
    document.getElementById('activityType').value = log.activity_type_id || '';
    document.getElementById('logTitle').value = log.title || '';
    document.getElementById('logDescription').value = log.description || '';
    document.getElementById('logLocation').value = log.location || '';
    document.getElementById('logSupervisor').value = log.supervisor_name || '';
    document.getElementById('caseCount').value = log.case_count || 1;

    openLogModal();
}

function openVerifyLogModal(logId) {
    const log = traineeLogCache.get(logId);
    if (!log) {
        showNotification('Data log tidak ditemukan', 'error');
        return;
    }

    const modal = document.getElementById('verifyLogModal');
    if (!modal) {
        showNotification('Form verifikasi tidak tersedia', 'error');
        return;
    }

    const title = modal.querySelector('.modal-header h2');
    if (title) title.textContent = `Verifikasi Log - ${log.full_name}`;

    const logInfo = document.getElementById('verifyLogInfo');
    if (logInfo) {
        logInfo.textContent = `${formatDate(log.log_date)} - ${log.title}`;
    }

    const logIdInput = document.getElementById('verifyLogId');
    if (logIdInput) logIdInput.value = logId;

    const noteInput = document.getElementById('verifySupervisorNote');
    if (noteInput) noteInput.value = '';

    const signatureInput = document.getElementById('verifyLogSignature');
    if (signatureInput) signatureInput.value = '';

    initializeLogSignatureCanvas();
    clearLogSignature();

    modal.style.display = 'flex';
}

function closeVerifyLogModal() {
    const modal = document.getElementById('verifyLogModal');
    if (modal) {
        modal.style.display = 'none';
    }
}

function initializeLogSignatureCanvas() {
    const canvas = document.getElementById('logSignatureCanvas');
    if (!canvas) return;
    if (logSignatureCanvas) return;

    logSignatureCanvas = canvas;
    logSignatureCtx = canvas.getContext('2d');

    canvas.addEventListener('mousedown', startDrawingLogSignature);
    canvas.addEventListener('mousemove', drawLogSignature);
    canvas.addEventListener('mouseup', stopDrawingLogSignature);
    canvas.addEventListener('mouseout', stopDrawingLogSignature);

    canvas.addEventListener('touchstart', startDrawingLogSignatureTouch, { passive: false });
    canvas.addEventListener('touchmove', drawLogSignatureTouch, { passive: false });
    canvas.addEventListener('touchend', stopDrawingLogSignature);
}

function startDrawingLogSignature(e) {
    if (!logSignatureCanvas || !logSignatureCtx) return;
    const rect = logSignatureCanvas.getBoundingClientRect();
    logSignatureCtx.beginPath();
    logSignatureCtx.moveTo(e.clientX - rect.left, e.clientY - rect.top);
    isDrawingLogSignature = true;
}

function drawLogSignature(e) {
    if (!isDrawingLogSignature || !logSignatureCtx || !logSignatureCanvas) return;
    const rect = logSignatureCanvas.getBoundingClientRect();
    logSignatureCtx.lineTo(e.clientX - rect.left, e.clientY - rect.top);
    logSignatureCtx.strokeStyle = '#333';
    logSignatureCtx.lineWidth = 2;
    logSignatureCtx.lineCap = 'round';
    logSignatureCtx.lineJoin = 'round';
    logSignatureCtx.stroke();
}

function stopDrawingLogSignature() {
    if (!isDrawingLogSignature) return;
    isDrawingLogSignature = false;
    saveLogSignature();
}

function startDrawingLogSignatureTouch(e) {
    if (!logSignatureCanvas || !logSignatureCtx) return;
    e.preventDefault();
    const touch = e.touches[0];
    const rect = logSignatureCanvas.getBoundingClientRect();
    logSignatureCtx.beginPath();
    logSignatureCtx.moveTo(touch.clientX - rect.left, touch.clientY - rect.top);
    isDrawingLogSignature = true;
}

function drawLogSignatureTouch(e) {
    if (!isDrawingLogSignature || !logSignatureCtx || !logSignatureCanvas) return;
    e.preventDefault();
    const touch = e.touches[0];
    const rect = logSignatureCanvas.getBoundingClientRect();
    logSignatureCtx.lineTo(touch.clientX - rect.left, touch.clientY - rect.top);
    logSignatureCtx.strokeStyle = '#333';
    logSignatureCtx.lineWidth = 2;
    logSignatureCtx.lineCap = 'round';
    logSignatureCtx.lineJoin = 'round';
    logSignatureCtx.stroke();
}

function clearLogSignature() {
    if (logSignatureCanvas && logSignatureCtx) {
        logSignatureCtx.clearRect(0, 0, logSignatureCanvas.width, logSignatureCanvas.height);
    }
    const signatureInput = document.getElementById('verifyLogSignature');
    if (signatureInput) signatureInput.value = '';
}

function saveLogSignature() {
    if (!logSignatureCanvas) return;
    const signatureData = logSignatureCanvas.toDataURL('image/png');
    const signatureInput = document.getElementById('verifyLogSignature');
    if (signatureInput) signatureInput.value = signatureData;
}

function submitVerifyLog() {
    const logId = document.getElementById('verifyLogId')?.value;
    const signature = document.getElementById('verifyLogSignature')?.value || '';
    const note = document.getElementById('verifySupervisorNote')?.value || '';

    if (!logId) {
        showNotification('Log ID tidak ditemukan', 'error');
        return;
    }

    const formData = new FormData();
    formData.append('action', 'verify_log');
    formData.append('log_id', logId);
    formData.append('dpjp_signature', signature);
    formData.append('supervisor_note', note);

    fetch('php/api.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('Log berhasil diverifikasi', 'success');
            closeVerifyLogModal();
            loadTraineeLogbooks();
            loadRecentActivities();
        } else {
            showNotification(data.message || 'Gagal verifikasi log', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('Gagal verifikasi log', 'error');
    });
}

function openMessageModal(targetType, targetId, recipientId, recipientName) {
    const modal = document.getElementById('messageModal');
    if (!modal) {
        showNotification('Form pesan tidak tersedia', 'error');
        return;
    }

    document.getElementById('messageTargetType').value = targetType;
    document.getElementById('messageTargetId').value = targetId;
    document.getElementById('messageRecipientId').value = recipientId;
    document.getElementById('messageText').value = '';

    const title = modal.querySelector('.modal-header h2');
    if (title) title.textContent = `Kirim Pesan ke ${recipientName}`;

    modal.style.display = 'flex';
}

function closeMessageModal() {
    const modal = document.getElementById('messageModal');
    if (modal) {
        modal.style.display = 'none';
    }
}

function submitMessage() {
    const targetType = document.getElementById('messageTargetType')?.value;
    const targetId = document.getElementById('messageTargetId')?.value;
    const recipientId = document.getElementById('messageRecipientId')?.value;
    const message = document.getElementById('messageText')?.value || '';

    if (!recipientId || !message.trim()) {
        showNotification('Pesan tidak boleh kosong', 'error');
        return;
    }

    const formData = new FormData();
    formData.append('action', 'create');
    formData.append('target_type', targetType || 'user');
    formData.append('target_id', targetId || '');
    formData.append('recipient_id', recipientId);
    formData.append('message', message);

    fetch('php/messages.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('Pesan berhasil dikirim', 'success');
            closeMessageModal();
        } else {
            showNotification(data.message || 'Gagal mengirim pesan', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('Gagal mengirim pesan', 'error');
    });
}

// Initialize calendar
function initializeCalendar() {
    const prevBtn = document.getElementById('prevMonth');
    const nextBtn = document.getElementById('nextMonth');
    
    if (prevBtn) prevBtn.addEventListener('click', previousMonth);
    if (nextBtn) nextBtn.addEventListener('click', nextMonth);
    
    renderCalendar();
}

// Previous month
function previousMonth() {
    currentMonth--;
    if (currentMonth < 0) {
        currentMonth = 11;
        currentYear--;
    }
    renderCalendar();
}

// Next month
function nextMonth() {
    currentMonth++;
    if (currentMonth > 11) {
        currentMonth = 0;
        currentYear++;
    }
    renderCalendar();
}

// Render calendar
function renderCalendar() {
    const monthNames = ['January', 'February', 'March', 'April', 'May', 'June',
                       'July', 'August', 'September', 'October', 'November', 'December'];
    const monthTitle = document.getElementById('currentMonth');
    const calendar = document.getElementById('calendar');
    
    if (!calendar) return;
    
    monthTitle.textContent = `${monthNames[currentMonth]} ${currentYear}`;
    
    // Load logs and portfolio for this month
    const month = (currentMonth + 1).toString().padStart(2, '0');
    
    // Fetch both logs and portfolio data in parallel
    Promise.all([
        fetch(`php/logbook.php?action=get_logbooks&year=${currentYear}&month=${month}`)
            .then(response => response.json()),
        fetch(`php/portfolio.php?action=get_by_month&year=${currentYear}&month=${month}`)
            .then(response => response.json())
    ])
    .then(([logsData, portfolioData]) => {
        const logs = logsData.success ? logsData.data : [];
        const portfolios = portfolioData.success ? portfolioData.data : [];
        displayCalendar(logs, portfolios);
    })
    .catch(error => {
        console.error('Error:', error);
        displayCalendar([], []);
    });
}

// Get portfolio colors based on setting type
function getPortfolioColors(settingType) {
    const colorMap = {
        'OK': { bg: '#e3f2fd', text: '#1565c0', border: '#1565c0', badge: '#1976d2' },
        'Poliklinik': { bg: '#e8f5e9', text: '#2e7d32', border: '#2e7d32', badge: '#43a047' },
        'Rawat_Inap': { bg: '#fff3e0', text: '#e65100', border: '#e65100', badge: '#fb8c00' },
        'default': { bg: '#f3e5f5', text: '#6a1b9a', border: '#6a1b9a', badge: '#8e24aa' }
    };
    return colorMap[settingType] || colorMap['default'];
}

// Display calendar
function displayCalendar(logs, portfolios = []) {
    const calendar = document.getElementById('calendar');
    if (!calendar) return;
    
    const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    
    // Create log map by date
    const logMap = {};
    logs.forEach(log => {
        const date = log.log_date;
        if (!logMap[date]) {
            logMap[date] = [];
        }
        logMap[date].push(log);
    });
    
    // Create portfolio map by date
    const portfolioMap = {};
    portfolios.forEach(portfolio => {
        const date = portfolio.tanggal;
        if (!portfolioMap[date]) {
            portfolioMap[date] = [];
        }
        portfolioMap[date].push(portfolio);
    });
    
    // Create table
    let html = '<table style="width: 100%; border-collapse: collapse;">';
    
    // Header
    html += '<thead><tr>';
    dayNames.forEach(day => {
        html += `<th style="background: #1e88e5; color: white; padding: 12px; font-weight: 600;">${day}</th>`;
    });
    html += '</tr></thead>';
    
    // Body
    html += '<tbody>';
    
    const firstDay = new Date(currentYear, currentMonth, 1);
    const lastDay = new Date(currentYear, currentMonth + 1, 0);
    const startDate = new Date(firstDay);
    startDate.setDate(startDate.getDate() - firstDay.getDay());
    
    let currentCell = new Date(startDate);
    
    while (currentCell <= lastDay) {
        html += '<tr>';
        
        for (let i = 0; i < 7; i++) {
            const dateStr = currentCell.toISOString().split('T')[0];
            const isCurrentMonth = currentCell.getMonth() === currentMonth;
            const isToday = dateStr === new Date().toISOString().split('T')[0];
            const hasLogs = logMap[dateStr] && logMap[dateStr].length > 0;
            const hasPortfolios = portfolioMap[dateStr] && portfolioMap[dateStr].length > 0;
            
            let cellClass = 'calendar-cell';
            if (!isCurrentMonth) cellClass += ' other-month';
            if (isToday) cellClass += ' today';
            if (hasLogs) cellClass += ' has-logs';
            if (selectedDate === dateStr) cellClass += ' selected';
            
            html += `<td class="${cellClass}" data-date="${dateStr}" onclick="selectDate('${dateStr}')" style="border: 1px solid #e0e0e0; padding: 8px; text-align: center; min-height: 100px; vertical-align: top; cursor: pointer; background: ${!isCurrentMonth ? '#f5f5f5' : hasLogs ? '#e8f5e9' : 'white'}; color: ${!isCurrentMonth ? '#9e9e9e' : 'inherit'}; ${isToday ? 'background: #fff9e6; font-weight: bold;' : ''}">`;
            html += `<span style="display: block; font-weight: 600; margin-bottom: 5px;">${currentCell.getDate()}</span>`;
            
            // Display log count
            if (hasLogs) {
                html += `<span style="display: block; font-size: 11px; color: #9e9e9e; margin-bottom: 4px;">${logMap[dateStr].length} logs</span>`;
            }
            
            // Display portfolio badges
            if (hasPortfolios) {
                const uniqueTypes = {};
                portfolioMap[dateStr].forEach(p => {
                    const key = `${p.divisi}-${p.setting_type}`;
                    if (!uniqueTypes[key]) {
                        uniqueTypes[key] = {
                            divisi: p.divisi,
                            setting_type: p.setting_type,
                            count: 0
                        };
                    }
                    uniqueTypes[key].count++;
                });
                
                Object.values(uniqueTypes).forEach(type => {
                    const settingTypeName = type.setting_type.replace(/_/g, ' ').toUpperCase();
                    const colors = getPortfolioColors(type.setting_type);
                    html += `<span style="display: block; font-size: 9px; background: ${colors.bg}; color: ${colors.text}; padding: 3px 5px; margin: 2px 0; border-radius: 3px; line-height: 1.2; text-align: center; font-weight: 500;" title="Portfolio - ${settingTypeName}">📋 ${settingTypeName}</span>`;
                });
            }
            
            html += '</td>';
            
            currentCell.setDate(currentCell.getDate() + 1);
        }
        
        html += '</tr>';
    }
    
    html += '</tbody></table>';
    
    calendar.innerHTML = html;
}

// Select date
function selectDate(dateStr) {
    selectedDate = dateStr;
    renderCalendar();
    
    const month = (currentMonth + 1).toString().padStart(2, '0');
    
    // Load logs and portfolios for selected date
    Promise.all([
        fetch(`php/logbook.php?action=get_logbooks&year=${currentYear}&month=${month}`)
            .then(response => response.json()),
        fetch(`php/portfolio.php?action=get_by_month&year=${currentYear}&month=${month}`)
            .then(response => response.json())
    ])
    .then(([logsData, portfolioData]) => {
        const selectedLogs = logsData.success ? logsData.data.filter(log => log.log_date === dateStr) : [];
        const selectedPortfolios = portfolioData.success ? portfolioData.data.filter(p => p.tanggal === dateStr) : [];
        displaySelectedDateLogs(selectedLogs, selectedPortfolios, dateStr);
    })
    .catch(error => console.error('Error:', error));
}

// Display logs for selected date
function displaySelectedDateLogs(logs, portfolios, dateStr) {
    const container = document.getElementById('selectedDateLogs');
    if (!container) return;
    
    const dateObj = new Date(dateStr + 'T00:00:00');
    const dateDisplay = dateObj.toLocaleDateString('id-ID', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
    
    let html = `<h4 style="margin-bottom: 15px; color: #333;">Aktivitas untuk ${dateDisplay}</h4>`;
    
    // Display logs
    if (logs.length > 0) {
        html += `<h5 style="margin-top: 20px; margin-bottom: 10px; color: #1e88e5;">📚 Logbook Kegiatan (${logs.length})</h5>`;
        html += logs.map(log => `
            <div class="log-item" style="background: #f5f5f5; padding: 12px; margin-bottom: 10px; border-radius: 8px; border-left: 4px solid #4caf50;">
                <span class="log-category" style="background: #4caf50; color: white; padding: 4px 8px; border-radius: 4px; font-size: 11px; margin-right: 6px;">${log.category_name}</span>
                <span class="log-type" style="background: #2196f3; color: white; padding: 4px 8px; border-radius: 4px; font-size: 11px;">${log.type_name}</span>
                <div class="log-title" style="font-weight: bold; margin-top: 8px;">${log.title}</div>
                <div class="log-description" style="color: #666; margin-top: 4px;">${log.description || '-'}</div>
                ${log.location ? `<div style="font-size: 12px; color: #666; margin-top: 6px;">📍 ${log.location}</div>` : ''}
                ${log.supervisor_name ? `<div style="font-size: 12px; color: #666;">👨‍⚕️ ${log.supervisor_name}</div>` : ''}
                ${log.case_count ? `<div style="font-size: 12px; color: #666;">👥 ${log.case_count} kasus</div>` : ''}
            </div>
        `).join('');
    }
    
    // Display portfolios
    if (portfolios.length > 0) {
        html += `<h5 style="margin-top: 20px; margin-bottom: 10px; color: #333;">📋 Portfolio (${portfolios.length})</h5>`;
        html += portfolios.map(portfolio => {
            const settingTypeName = portfolio.setting_type.replace(/_/g, ' ').toUpperCase();
            const colors = getPortfolioColors(portfolio.setting_type);
            const statusBadge = portfolio.dpjp_verified ? 
                '<span style="background: #4caf50; color: white; padding: 3px 8px; border-radius: 4px; font-size: 11px; margin-left: 8px;">✓ Terverifikasi</span>' : 
                '<span style="background: #ff9800; color: white; padding: 3px 8px; border-radius: 4px; font-size: 11px; margin-left: 8px;">⏳ Menunggu Verifikasi</span>';
            
            return `
            <div class="portfolio-item" style="background: ${colors.bg}; padding: 12px; margin-bottom: 10px; border-radius: 8px; border-left: 4px solid ${colors.border};">
                <div style="display: flex; align-items: center; flex-wrap: wrap;">
                    <span style="background: ${colors.badge}; color: white; padding: 4px 8px; border-radius: 4px; font-size: 11px; font-weight: bold;">
                        ${portfolio.divisi} - ${settingTypeName}
                    </span>
                    ${statusBadge}
                </div>
                <div style="font-weight: bold; margin-top: 8px; color: ${colors.text};">Pasien: ${portfolio.nama_pasien}</div>
                <div style="color: #666; margin-top: 4px;">Diagnosis: ${portfolio.diagnosis}</div>
                <div style="font-size: 12px; color: #666; margin-top: 6px;">
                    No. ${portfolio.nomor} | Semester ${portfolio.semester}
                </div>
            </div>
            `;
        }).join('');
    }
    
    // If no activities
    if (logs.length === 0 && portfolios.length === 0) {
        html = `<p class="text-muted">Tidak ada aktivitas untuk ${dateDisplay}</p>`;
    }
    
    container.innerHTML = html;
}

// Initialize log form
function initializeLogForm() {
    const logForm = document.getElementById('logForm');
    if (!logForm) return;
    
    logForm.addEventListener('submit', function(e) {
        e.preventDefault();
        saveLog();
    });
    
    // Add event listener for Add Log button
    const addLogBtn = document.getElementById('addLogBtn');
    if (addLogBtn) {
        addLogBtn.addEventListener('click', function() {
            openLogModal();
        });
    }
    
    // Setup modal event listeners
    const logModal = document.getElementById('logModal');
    if (logModal) {
        // Close modal when clicking outside
        logModal.addEventListener('click', function(e) {
            if (e.target === this) {
                closeLogModal();
            }
        });
    }
    
    // Close modal on Escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const logModal = document.getElementById('logModal');
            if (logModal && logModal.style.display !== 'none') {
                closeLogModal();
            }
        }
    });
}

// Load supervisors for log form
function loadLogSupervisors() {
    const supervisorSelect = document.getElementById('logSupervisorInitial');
    const supervisorNameInput = document.getElementById('logSupervisor');
    
    if (!supervisorSelect) return;
    
    fetch('php/portfolio.php?action=get_supervisors')
        .then(response => response.json())
        .then(data => {
            if (data.success && Array.isArray(data.data)) {
                supervisorSelect.innerHTML = '<option value="">-- Pilih Supervisor --</option>';
                
                data.data.forEach(supervisor => {
                    const option = document.createElement('option');
                    option.value = supervisor.supervisor_initial;
                    option.textContent = `${supervisor.supervisor_initial} - ${supervisor.full_name}`;
                    option.dataset.fullName = supervisor.full_name;
                    supervisorSelect.appendChild(option);
                });
                
                // Add change event listener to auto-fill supervisor name
                supervisorSelect.addEventListener('change', function() {
                    const selectedOption = this.options[this.selectedIndex];
                    if (selectedOption && selectedOption.value && supervisorNameInput) {
                        supervisorNameInput.value = selectedOption.dataset.fullName || '';
                    } else if (supervisorNameInput) {
                        supervisorNameInput.value = '';
                    }
                });
            }
        })
        .catch(error => {
            console.error('Error loading supervisors:', error);
        });
}

// Open log modal
function openLogModal() {
    const logModal = document.getElementById('logModal');
    if (logModal) {
        logModal.style.display = 'flex';
        loadLogSupervisors();
    }
}

// Close log modal
function closeLogModal() {
    const logModal = document.getElementById('logModal');
    if (logModal) {
        logModal.style.display = 'none';
    }
    // Reset form
    const logForm = document.getElementById('logForm');
    if (logForm) {
        logForm.reset();
    }
    resetLogFormState();
}

function resetLogFormState() {
    currentLogEditId = null;
    currentLogEditOwnerId = null;
    const logIdInput = document.getElementById('logId');
    const logOwnerInput = document.getElementById('logOwnerId');
    if (logIdInput) logIdInput.value = '';
    if (logOwnerInput) logOwnerInput.value = '';

    const modalTitle = document.querySelector('#logModal .modal-header h2');
    if (modalTitle) modalTitle.textContent = 'Tambah Log Baru';
}

// Save log
function saveLog() {
    const logForm = document.getElementById('logForm');
    const formData = new FormData(logForm);
    const logId = document.getElementById('logId')?.value;
    if (logId) {
        formData.append('action', 'update_log');
        formData.append('log_id', logId);
    } else {
        formData.append('action', 'save_log');
    }
    
    // Show loading state
    const saveBtn = logForm ? logForm.querySelector('button[type="submit"]') : null;
    const originalText = saveBtn ? saveBtn.textContent : 'Simpan';
    if (saveBtn) saveBtn.textContent = 'Menyimpan...';
    if (saveBtn) saveBtn.disabled = true;
    
    fetch('php/api.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.text(); // Get raw text first
    })
    .then(text => {
        console.log('Raw response:', text);
        try {
            const data = JSON.parse(text);
            if (data.success) {
                // Show success notification
                const message = logId ? 'Log berhasil diperbarui!' : 'Log berhasil disimpan!';
                showNotification(message, 'success');
                closeLogModal();
                renderCalendar();
                loadStatistics();
                loadRecentActivities();
                loadTraineeLogbooks();
            } else {
                showNotification('Error: ' + (data.message || 'Gagal menyimpan log'), 'error');
            }
        } catch (e) {
            console.error('JSON Parse error:', e);
            showNotification('Terjadi kesalahan pada server response', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('Terjadi kesalahan saat menyimpan log', 'error');
    })
    .finally(() => {
        // Restore button state
        if (saveBtn) {
            saveBtn.textContent = originalText;
            saveBtn.disabled = false;
        }
    });
}

// Notification helper
function showNotification(message, type = 'info') {
    // Remove existing notification if any
    const existing = document.querySelector('.notification');
    if (existing) existing.remove();

    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 16px 24px;
        background: ${type === 'success' ? '#4caf50' : type === 'error' ? '#f44336' : '#2196f3'};
        color: white;
        border-radius: 4px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.2);
        z-index: 9999;
        animation: slideIn 0.3s ease-out;
    `;

    document.body.appendChild(notification);

    // Auto-dismiss after 3 seconds
    setTimeout(() => {
        notification.style.animation = 'slideOut 0.3s ease-out';
        setTimeout(() => notification.remove(), 300);
    }, 3000);
}

// Format date
function formatDate(dateStr) {
    const date = new Date(dateStr + 'T00:00:00');
    return date.toLocaleDateString('id-ID', { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' });
}

// Format date time (for activity timestamps)
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '-';
    const date = new Date(dateTimeStr);
    return date.toLocaleDateString('id-ID', {
        weekday: 'short',
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// Initialize profile and settings sections
function initializeProfileSections() {
    const profileForm = document.getElementById('profileForm');
    const passwordForm = document.getElementById('passwordForm');

    if (!profileForm && !passwordForm) return;

    loadProfileData();

    if (profileForm) {
        profileForm.addEventListener('submit', function(e) {
            e.preventDefault();
            updateProfile();
        });
    }

    if (passwordForm) {
        passwordForm.addEventListener('submit', function(e) {
            e.preventDefault();
            changePassword();
        });
    }
}

function loadProfileData() {
    fetch('php/user_profile.php?action=profile')
        .then(response => response.json())
        .then(data => {
            if (!data.success || !data.data) return;

            const user = data.data;
            const fullName = document.getElementById('profileFullName');
            const username = document.getElementById('profileUsername');
            const specialization = document.getElementById('profileSpecialization');
            const semester = document.getElementById('profileSemester');
            const institution = document.getElementById('profileInstitution');
            const email = document.getElementById('profileEmail');
            const phone = document.getElementById('profilePhone');

            if (fullName) fullName.value = user.full_name || '';
            if (username) username.value = user.username || '';
            if (specialization) specialization.value = user.specialization || '';
            if (semester) semester.value = user.semester || '';
            if (institution) institution.value = user.institution || '';
            if (email) email.value = user.email || '';
            if (phone) phone.value = user.phone || '';
        })
        .catch(error => console.error('Error:', error));
}

function updateProfile() {
    const form = document.getElementById('profileForm');
    const message = document.getElementById('profileMessage');
    if (!form || !message) return;

    const formData = new FormData(form);
    formData.append('action', 'update_profile');

    fetch('php/user_profile.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        showFormMessage(message, data.success ? 'success' : 'danger', data.message || 'Gagal memperbarui profil');
        if (data.success && data.data) {
            updateUserDisplay(data.data);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showFormMessage(message, 'danger', 'Terjadi kesalahan saat menyimpan profil');
    });
}

function changePassword() {
    const form = document.getElementById('passwordForm');
    const message = document.getElementById('passwordMessage');
    if (!form || !message) return;

    const formData = new FormData(form);
    formData.append('action', 'change_password');

    fetch('php/user_profile.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        showFormMessage(message, data.success ? 'success' : 'danger', data.message || 'Gagal mengubah password');
        if (data.success) {
            form.reset();
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showFormMessage(message, 'danger', 'Terjadi kesalahan saat mengubah password');
    });
}

function showFormMessage(container, type, text) {
    container.className = `alert alert-${type}`;
    container.textContent = text;
    container.style.display = 'block';
    scheduleAutoDismiss(container);
}

// Load settings page user information
function loadSettingsData() {
    fetch('php/user_profile.php?action=profile')
        .then(response => response.json())
        .then(data => {
            if (!data.success || !data.data) return;

            const user = data.data;
            document.getElementById('settingsUsername').textContent = user.username || '-';
            document.getElementById('settingsFullName').textContent = user.full_name || '-';
            document.getElementById('settingsSpecialization').textContent = user.specialization || '-';
            document.getElementById('settingsSemester').textContent = user.semester || '-';
            document.getElementById('settingsInstitution').textContent = user.institution || '-';
            document.getElementById('settingsEmail').textContent = user.email || '-';
            document.getElementById('settingsPhone').textContent = user.phone || '-';
        })
        .catch(error => console.error('Error:', error));
}

function initializeAutoDismiss() {
    const elements = document.querySelectorAll('.success-message, .alert');
    elements.forEach(element => {
        if (window.getComputedStyle(element).display !== 'none') {
            scheduleAutoDismiss(element);
        }
    });
}

function scheduleAutoDismiss(element, delay = 4000) {
    if (!element) return;
    if (element.dataset.hideTimerId) {
        clearTimeout(Number(element.dataset.hideTimerId));
    }
    const timerId = setTimeout(() => {
        element.style.display = 'none';
    }, delay);
    element.dataset.hideTimerId = String(timerId);
}
// Portfolio Navigation Handler
// DISABLED: Now handled by portfolio.js handlePortfolioSectionChange
/*
document.addEventListener('DOMContentLoaded', function() {
    // Listen for hash changes to handle portfolio navigation
    window.addEventListener('hashchange', handlePortfolioNavigation);
    
    // Initial check when page loads
    handlePortfolioNavigation();
});

function handlePortfolioNavigation() {
    const hash = window.location.hash.substring(1);
    
    // Check if this is a portfolio link
    const portfolioMatch = hash.match(/^([a-z]+)-sem(\d+)-portofolio-(ok|kamaroperasi|poliklinik|rawatinap)$/i);
    
    if (portfolioMatch) {
        const divisiName = portfolioMatch[1];
        const semester = parseInt(portfolioMatch[2]);
        const settingType = portfolioMatch[3];
        
        // Map setting types to database values
        const settingTypeMap = {
            'ok': 'OK',
            'kamaroperasi': 'OK',
            'poliklinik': 'Poliklinik',
            'rawatinap': 'Rawat_Inap'
        };
        
        const dbSettingType = settingTypeMap[settingType.toLowerCase()];
        
        // Show portfolio list and initialize with context
        showPortfolioListView();
        initializePortfolio(divisiName, semester, dbSettingType);
    }
}
*/

// ============================================
// INBOX / MESSAGES
// ============================================

let currentMessageFilter = 'all';

function updateUnreadCount() {
    fetch('php/messages.php?action=list')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.messages) {
                const unreadCount = data.messages.filter(msg => msg.is_read === '0' || msg.is_read === 0).length;
                const badge = document.getElementById('unreadBadge');
                if (badge) {
                    if (unreadCount > 0) {
                        badge.textContent = unreadCount;
                        badge.style.display = 'inline-block';
                    } else {
                        badge.style.display = 'none';
                    }
                }
            }
        })
        .catch(error => console.error('Error updating unread count:', error));
}

function loadInbox() {
    const container = document.getElementById('messagesContainer');
    if (!container) return;
    
    container.innerHTML = '<p class="text-muted">Memuat pesan...</p>';
    
    fetch('php/messages.php?action=list')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.messages) {
                displayMessages(data.messages);
            } else {
                container.innerHTML = '<p class="text-muted">Tidak ada pesan</p>';
            }
        })
        .catch(error => {
            console.error('Error loading messages:', error);
            container.innerHTML = '<p class="text-danger">Gagal memuat pesan</p>';
        });
}

function displayMessages(messages) {
    const container = document.getElementById('messagesContainer');
    if (!container) return;
    
    // Filter messages based on current filter
    let filteredMessages = messages;
    if (currentMessageFilter !== 'all') {
        filteredMessages = messages.filter(msg => msg.target_type === currentMessageFilter);
    }
    
    if (filteredMessages.length === 0) {
        container.innerHTML = '<p class="text-muted">Tidak ada pesan</p>';
        return;
    }
    
    // Sort by date (newest first)
    filteredMessages.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
    
    let html = '';
    filteredMessages.forEach(msg => {
        const isUnread = msg.is_read === '0' || msg.is_read === 0;
        const date = new Date(msg.created_at);
        const formattedDate = date.toLocaleDateString('id-ID', { 
            day: 'numeric', 
            month: 'short', 
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
        
        let targetInfo = '';
        if (msg.target_type === 'logbook' && msg.target_id) {
            const logTitle = msg.log_title ? msg.log_title : `Logbook ID #${msg.target_id}`;
            targetInfo = `<div class="message-subject">Re: ${logTitle}</div>`;
        } else if (msg.target_type === 'portfolio' && msg.target_id) {
            const portfolioTitle = msg.portfolio_diagnosis ? msg.portfolio_diagnosis : `Portfolio ID #${msg.target_id}`;
            targetInfo = `<div class="message-subject">Re: ${portfolioTitle}</div>`;
        }
        
        html += `
            <div class="message-item ${isUnread ? 'unread' : ''}" data-message-id="${msg.id}">
                <div class="message-content">
                    <div class="message-header">
                        <div>
                            <span class="message-from">${msg.sender_name || 'Unknown'}</span>
                            <span class="message-type-badge ${msg.target_type}">${msg.target_type === 'logbook' ? 'Logbook' : msg.target_type === 'portfolio' ? 'Portfolio' : 'Umum'}</span>
                        </div>
                        <span class="message-date">${formattedDate}</span>
                    </div>
                    ${targetInfo}
                    <div class="message-body">${msg.message || ''}</div>
                </div>
                <button class="btn-delete-message" onclick="deleteMessage(${msg.id}, event)" title="Hapus pesan">
                    🗑️
                </button>
            </div>
        `;
    });
    
    container.innerHTML = html;
    
    // Mark messages as read when clicked
    container.querySelectorAll('.message-item .message-content').forEach(item => {
        item.addEventListener('click', function() {
            const messageId = this.closest('.message-item').getAttribute('data-message-id');
            markMessageAsRead(messageId);
            this.closest('.message-item').classList.remove('unread');
        });
    });
}

function deleteMessage(messageId, event) {
    if (event) {
        event.stopPropagation(); // Prevent marking as read when deleting
    }
    
    if (!confirm('Yakin ingin menghapus pesan ini?')) {
        return;
    }
    
    fetch('php/messages.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            action: 'delete',
            message_id: messageId
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            loadInbox(); // Reload messages after deletion
            updateUnreadCount(); // Update badge
            showMessage('Pesan berhasil dihapus', 'success');
        } else {
            showMessage('Gagal menghapus pesan: ' + (data.message || 'Unknown error'), 'error');
        }
    })
    .catch(error => {
        console.error('Error deleting message:', error);
        showMessage('Gagal menghapus pesan', 'error');
    });
}

function deleteAllMessages() {
    if (!confirm('Yakin ingin menghapus SEMUA pesan?')) {
        return;
    }
    
    fetch('php/messages.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            action: 'delete_all'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            loadInbox(); // Reload messages after deletion
            updateUnreadCount(); // Update badge
            showMessage(data.message || 'Semua pesan berhasil dihapus', 'success');
        } else {
            showMessage('Gagal menghapus pesan: ' + (data.message || 'Unknown error'), 'error');
        }
    })
    .catch(error => {
        console.error('Error deleting all messages:', error);
        showMessage('Gagal menghapus pesan', 'error');
    });
}

function markMessageAsRead(messageId) {
    fetch('php/messages.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            action: 'mark_read',
            message_id: messageId
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            updateUnreadCount(); // Update badge after marking as read
        } else {
            console.error('Failed to mark message as read');
        }
    })
    .catch(error => console.error('Error marking message as read:', error));
}

function setupInboxFilters() {
    const filterTabs = document.querySelectorAll('.filter-tab');
    filterTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // Remove active class from all tabs
            filterTabs.forEach(t => t.classList.remove('active'));
            // Add active class to clicked tab
            this.classList.add('active');
            
            // Update filter and reload messages
            currentMessageFilter = this.getAttribute('data-filter');
            loadInbox();
        });
    });
}

// Simple notification toast function
function showMessage(message, type = 'info') {
    // Create toast element
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.textContent = message;
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        background: ${type === 'success' ? '#4caf50' : type === 'error' ? '#f44336' : '#2196f3'};
        color: white;
        border-radius: 4px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        z-index: 10000;
        font-size: 14px;
        max-width: 300px;
        animation: slideInRight 0.3s ease-out;
    `;
    
    document.body.appendChild(toast);
    
    // Auto remove after 3 seconds
    setTimeout(() => {
        toast.style.animation = 'slideOutRight 0.3s ease-out';
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 300);
    }, 3000);
}

// Initialize inbox when section is shown
document.addEventListener('DOMContentLoaded', function() {
    // Setup inbox filters
    setupInboxFilters();
    
    // Load inbox when the inbox section is shown
    const inboxLink = document.querySelector('a[href="#inbox"]');
    if (inboxLink) {
        inboxLink.addEventListener('click', function() {
            setTimeout(() => {
                loadInbox();
            }, 100);
        });
    }
    
    // Update unread count on page load
    updateUnreadCount();
    
    // Update unread count every 30 seconds
    setInterval(updateUnreadCount, 30000);
});
