// Portfolio Management System
// Handles form display, signature capturing, and API communications

let portfolioState = {
    currentEditId: null,
    currentDivisi: null,
    currentSemester: null,
    currentSettingType: null,
    viewUserId: null,
    traineeList: [],
    traineeSignatureCanvas: null,
    traineeCtx: null,
    dpjpSignatureCanvas: null,
    dpjpCtx: null,
    isDrawingTrainee: false,
    isDrawingDPJP: false,
    lastX: null,
    lastY: null,
    currentPortfolioItems: []  // Store current items for filtering
};

// Initialize portfolio subsection data display on hash change
document.addEventListener('DOMContentLoaded', function() {
    window.addEventListener('hashchange', handlePortfolioSectionChange);
    // Also check initial hash
    handlePortfolioSectionChange();
    injectPortfolioAddButtons();
    injectPortfolioSearch();
    if (getCurrentUserRole() === 'dosen' || getCurrentUserRole() === 'admin') {
        loadPortfolioTrainees();
    }
});

function getCurrentUserRole() {
    return window.currentUserRole || 'trainee';
}

function getCurrentUserId() {
    return window.currentUserId || null;
}

function loadPortfolioTrainees() {
    fetch('php/logbook.php?action=get_trainees')
        .then(response => response.json())
        .then(data => {
            if (data.success && Array.isArray(data.data)) {
                portfolioState.traineeList = data.data;
                if (!portfolioState.viewUserId && data.data.length > 0) {
                    portfolioState.viewUserId = data.data[0].id;
                }
                updatePortfolioTraineeSelects();
            }
        })
        .catch(error => console.error('Error loading trainees:', error));
}

function updatePortfolioTraineeSelects() {
    const selects = document.querySelectorAll('.portfolio-trainee-select');
    selects.forEach(select => {
        const currentValue = portfolioState.viewUserId ? String(portfolioState.viewUserId) : '';
        select.innerHTML = '';

        portfolioState.traineeList.forEach(trainee => {
            const option = document.createElement('option');
            option.value = trainee.id;
            option.textContent = `${trainee.full_name} (Sem ${trainee.semester || '-'})`;
            if (String(trainee.id) === currentValue) {
                option.selected = true;
            }
            select.appendChild(option);
        });
    });
}

function handlePortfolioSectionChange() {
    const hash = window.location.hash.substring(1);
    
    console.log('=== Portfolio Section Change ===');
    console.log('Full URL:', window.location.href);
    console.log('Hash with #:', window.location.hash);
    console.log('Hash without #:', hash);
    
    // Check if this is a portfolio subsection (kamar operasi, poliklinik, rawat inap)
    const portfolioMatch = hash.match(/^(\w+)-sem(\d+)-portofolio-(kamaroperasi|poliklinik|rawatinap)$/);
    
    console.log('Regex match result:', portfolioMatch);
    
    if (portfolioMatch) {
        const divisi = portfolioMatch[1];
        const semester = parseInt(portfolioMatch[2]);
        const settingType = portfolioMatch[3];
        
        console.log('Portfolio section detected:', { divisi, semester, settingType });
        
        setPortfolioContext(divisi, semester, settingType);
        
        // Load portfolio data for table display
        setTimeout(() => {
            loadPortfolioDataForTable(divisi, semester, settingType);
        }, 100);
    } else {
        console.log('Not a portfolio section hash');
    }
}

function setPortfolioContext(divisi, semester, settingType) {
    const settingTypeMap = {
        kamaroperasi: 'OK',
        poliklinik: 'Poliklinik',
        rawatinap: 'Rawat_Inap'
    };

    portfolioState.currentDivisi = divisi;
    portfolioState.currentSemester = semester;
    portfolioState.currentSettingType = settingTypeMap[settingType] || settingType;
}

function setPortfolioContextFromHash() {
    const hash = window.location.hash.substring(1);
    const portfolioMatch = hash.match(/^([\w-]+)-sem(\d+)-portofolio-(kamaroperasi|poliklinik|rawatinap)$/);

    if (!portfolioMatch) {
        return false;
    }

    setPortfolioContext(portfolioMatch[1], parseInt(portfolioMatch[2]), portfolioMatch[3]);
    return true;
}

function setPortfolioContextFromSection(section) {
    const sectionId = section ? section.id : '';
    const portfolioMatch = sectionId.match(/^([\w-]+)-sem(\d+)-portofolio-(kamaroperasi|poliklinik|rawatinap)$/);

    if (!portfolioMatch) {
        return false;
    }

    setPortfolioContext(portfolioMatch[1], parseInt(portfolioMatch[2]), portfolioMatch[3]);
    return true;
}

function openPortfolioFormFromCurrentSection(button) {
    if (getCurrentUserRole() === 'dosen' || getCurrentUserRole() === 'admin') {
        alert('Dosen tidak dapat menambah portofolio baru. Gunakan Edit untuk verifikasi.');
        return;
    }

    const section = button ? button.closest('section') : null;
    const hasSectionContext = setPortfolioContextFromSection(section);
    const hasHashContext = hasSectionContext ? true : setPortfolioContextFromHash();

    if (!hasHashContext) {
        alert('Buka submenu portofolio terlebih dahulu.');
        return;
    }

    openPortfolioForm(null);
}

function injectPortfolioAddButtons() {
    const headings = document.querySelectorAll('section[id*="-portofolio-"] h3');

    headings.forEach((heading) => {
        if (!heading.textContent.includes('Ringkasan Data Pasien')) {
            return;
        }

        const existingButton = heading.parentElement.querySelector('.portfolio-add-button');
        if (existingButton) {
            return;
        }

        // Create button container
        const buttonContainer = document.createElement('div');
        buttonContainer.style.display = 'flex';
        buttonContainer.style.gap = '10px';
        buttonContainer.style.marginTop = '10px';
        buttonContainer.style.marginBottom = '10px';
        buttonContainer.style.flexWrap = 'wrap';

        const userRole = getCurrentUserRole();
        if (userRole === 'dosen' || userRole === 'admin') {
            const traineeSelect = document.createElement('select');
            traineeSelect.className = 'portfolio-trainee-select';
            traineeSelect.style.minWidth = '260px';
            traineeSelect.addEventListener('change', (event) => {
                portfolioState.viewUserId = parseInt(event.target.value, 10);
                const hash = window.location.hash.substring(1);
                const match = hash.match(/^(\w+)-sem(\d+)-portofolio-(kamaroperasi|poliklinik|rawatinap)$/);
                if (match) {
                    loadPortfolioDataForTable(match[1], parseInt(match[2], 10), match[3]);
                }
            });
            buttonContainer.appendChild(traineeSelect);
        }

        // Tambah Data button
        const addButton = document.createElement('button');
        addButton.type = 'button';
        addButton.className = 'btn btn-primary portfolio-add-button';
        addButton.textContent = '+ Tambah Data';
        addButton.addEventListener('click', (event) => {
            openPortfolioFormFromCurrentSection(event.currentTarget);
        });

        // Import Excel button
        const importButton = document.createElement('button');
        importButton.type = 'button';
        importButton.className = 'btn btn-success';
        importButton.innerHTML = '📥 Import Excel';
        importButton.addEventListener('click', () => {
            importExcelData();
        });

        // Template Excel button
        const templateButton = document.createElement('button');
        templateButton.type = 'button';
        templateButton.className = 'btn btn-info';
        templateButton.innerHTML = '📄 Template Excel';
        templateButton.addEventListener('click', () => {
            downloadExcelTemplate();
        });

        // Print button
        const printButton = document.createElement('button');
        printButton.type = 'button';
        printButton.className = 'btn btn-secondary';
        printButton.innerHTML = '🖨️ Print';
        printButton.addEventListener('click', () => {
            printPortfolioTable();
        });

        if (getCurrentUserRole() === 'trainee') {
            buttonContainer.appendChild(addButton);
        }
        buttonContainer.appendChild(importButton);
        buttonContainer.appendChild(templateButton);
        buttonContainer.appendChild(printButton);

        heading.parentElement.insertBefore(buttonContainer, heading.nextSibling);
    });

    updatePortfolioTraineeSelects();
}

// Inject portfolio search input
function injectPortfolioSearch() {
    const headings = document.querySelectorAll('section[id*="-portofolio-"] h3');
    
    headings.forEach((heading) => {
        if (!heading.textContent.includes('Ringkasan Data Pasien')) {
            return;
        }
        
        // Check if search input already exists
        const contentCol = heading.closest('.content-col');
        if (!contentCol) return;
        
        const existingSearch = contentCol.querySelector('.portfolio-search-input');
        if (existingSearch) return;
        
        // Create search input
        const searchInput = document.createElement('input');
        searchInput.type = 'text';
        searchInput.className = 'portfolio-search-input';
        searchInput.placeholder = '🔍 Cari berdasarkan Nama, No.RM, Diagnosis, Tatalaksana...';
        searchInput.style.cssText = `
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 100%;
            font-size: 14px;
            margin-bottom: 15px;
        `;
        
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase().trim();
            const table = contentCol.querySelector('.portfolio-patients-table');
            if (!table) return;
            
            const rows = table.querySelectorAll('tbody tr:not(:has(td[colspan]))');
            let visibleCount = 0;
            
            rows.forEach(row => {
                const text = row.textContent.toLowerCase();
                if (text.includes(searchTerm)) {
                    row.style.display = '';
                    visibleCount++;
                } else {
                    row.style.display = 'none';
                }
            });
        });
        
        // Insert search input after heading
        heading.parentElement.insertBefore(searchInput, heading.nextSibling);
    });
}

function downloadExcelTemplate() {
    // Check if XLSX library is loaded
    if (typeof XLSX === 'undefined') {
        alert('Library Excel belum dimuat. Silakan reload halaman.');
        return;
    }
    
    // Create template data
    const templateData = [
        ['No', 'Tanggal (YYYY-MM-DD)', 'Nama Pasien', 'No. RM', 'Umur', 'Paritas', 'Alamat', 'Diagnosis', 'Tatalaksana', 'Kompetensi', 'Supervisor/DPJP'],
        ['1', '2026-01-01', 'Contoh Pasien', '123456', '30', 'P0A0', 'Jl. Contoh No. 123', 'Endometriosis', 'Laparoskopi diagnostik', 'Level I', 'dr. Nama Dokter, Sp.OG'],
        ['2', '2026-01-02', 'Contoh Pasien 2', '123457', '28', 'P1A0', 'Jl. Contoh No. 456', 'Kista Ovarium', 'Kistektomi', 'Level II', 'dr. Nama Dokter, Sp.OG']
    ];
    
    // Create workbook and worksheet
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet(templateData);
    
    // Set column widths
    ws['!cols'] = [
        { wch: 5 },  // No
        { wch: 15 }, // Tanggal
        { wch: 20 }, // Nama Pasien
        { wch: 12 }, // No. RM
        { wch: 8 },  // Umur
        { wch: 10 }, // Paritas
        { wch: 30 }, // Alamat
        { wch: 25 }, // Diagnosis
        { wch: 30 }, // Tatalaksana
        { wch: 12 }, // Kompetensi
        { wch: 25 }  // Supervisor
    ];
    
    // Add worksheet to workbook
    XLSX.utils.book_append_sheet(wb, ws, 'Template Portfolio');
    
    // Generate Excel file and download
    XLSX.writeFile(wb, 'Template_Portfolio_PPDS.xlsx');
}

function importExcelData() {
    // Check if XLSX library is loaded
    if (typeof XLSX === 'undefined') {
        alert('Library Excel belum dimuat. Silakan reload halaman.');
        return;
    }
    
    // Create file input
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = '.xlsx, .xls';
    
    fileInput.onchange = function(e) {
        const file = e.target.files[0];
        if (!file) return;
        
        const reader = new FileReader();
        reader.onload = function(e) {
            try {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });
                
                // Get first worksheet
                const firstSheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[firstSheetName];
                
                // Convert to JSON
                const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
                
                // Process data (skip header row)
                if (jsonData.length < 2) {
                    alert('File Excel kosong atau tidak ada data');
                    return;
                }
                
                // Confirm import
                const dataCount = jsonData.length - 1; // Exclude header
                if (!confirm(`Ditemukan ${dataCount} baris data. Lanjutkan import?`)) {
                    return;
                }
                
                // Process each row
                processExcelImport(jsonData.slice(1)); // Skip header
                
            } catch (error) {
                console.error('Error parsing Excel:', error);
                alert('Gagal membaca file Excel: ' + error.message);
            }
        };
        
        reader.readAsArrayBuffer(file);
    };
    
    fileInput.click();
}

function processExcelImport(rows) {
    let successCount = 0;
    let failCount = 0;
    const errors = [];
    
    // Get current context
    if (!portfolioState.currentDivisi || !portfolioState.currentSemester || !portfolioState.currentSettingType) {
        alert('Konteks portfolio tidak ditemukan. Pastikan Anda berada di halaman portfolio yang benar.');
        return;
    }
    
    // Process rows sequentially
    const processRow = async (index) => {
        if (index >= rows.length) {
            // All done
            showImportResult(successCount, failCount, errors);
            return;
        }
        
        const row = rows[index];
        
        // Expected columns: No, Tanggal, Nama Pasien, No. RM, Umur, Paritas, Alamat, Diagnosis, Tatalaksana, Kompetensi, Supervisor
        const [no, tanggal, namaPasien, nomorRM, umur, paritas, alamat, diagnosis, tatalaksana, kompetensi, supervisor] = row;
        
        // Validate required fields
        if (!tanggal || !namaPasien || !diagnosis) {
            errors.push(`Baris ${index + 2}: Data tidak lengkap (tanggal, nama pasien, atau diagnosis kosong)`);
            failCount++;
            processRow(index + 1);
            return;
        }
        
        // Format tanggal to YYYY-MM-DD
        let formattedDate = tanggal;
        if (tanggal instanceof Date) {
            formattedDate = tanggal.toISOString().split('T')[0];
        } else if (typeof tanggal === 'string') {
            // Try to parse date string
            const dateObj = new Date(tanggal);
            if (!isNaN(dateObj.getTime())) {
                formattedDate = dateObj.toISOString().split('T')[0];
            }
        }
        
        // Build identifikasi_pasien
        const identifikasiPasien = `Nama: ${namaPasien}${nomorRM ? ', No. RM: ' + nomorRM : ''}${umur ? ', Umur: ' + umur : ''}${paritas ? ', Paritas: ' + paritas : ''}${alamat ? ', Alamat: ' + alamat : ''}`;
        
        // Prepare data for API
        const portfolioData = {
            action: 'create',
            divisi: portfolioState.currentDivisi,
            semester: portfolioState.currentSemester,
            setting_type: portfolioState.currentSettingType,
            tanggal: formattedDate,
            identifikasi_pasien: identifikasiPasien,
            nama_pasien: namaPasien || '',
            nomor_rm: nomorRM || '',
            umur: umur ? parseInt(umur) : 0,
            paritas: paritas || '',
            alamat: alamat || '',
            diagnosis: diagnosis || '',
            tatalaksana: tatalaksana || '',
            kompetenszi: kompetensi || 'Level I',
            supervisor_name: supervisor || '',
            trainee_signature: '' // Empty signature for import
        };
        
        // Send to API
        try {
            const response = await fetch('php/portfolio.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                },
                body: JSON.stringify(portfolioData)
            });
            
            const result = await response.json();
            
            if (result.success) {
                successCount++;
            } else {
                errors.push(`Baris ${index + 2}: ${result.error || 'Gagal menyimpan'}`);
                failCount++;
            }
        } catch (error) {
            errors.push(`Baris ${index + 2}: ${error.message}`);
            failCount++;
        }
        
        // Process next row
        processRow(index + 1);
    };
    
    // Start processing
    processRow(0);
}

function showImportResult(successCount, failCount, errors) {
    let message = `Import selesai!\n\nBerhasil: ${successCount}\nGagal: ${failCount}`;
    
    if (errors.length > 0) {
        message += '\n\nError:\n' + errors.slice(0, 5).join('\n');
        if (errors.length > 5) {
            message += `\n... dan ${errors.length - 5} error lainnya`;
        }
    }
    
    alert(message);
    
    // Reload table
    const hash = window.location.hash.substring(1);
    const portfolioMatch = hash.match(/^(\w+)-sem(\d+)-portofolio-(kamaroperasi|poliklinik|rawatinap)$/);
    if (portfolioMatch) {
        loadPortfolioDataForTable(portfolioMatch[1], parseInt(portfolioMatch[2]), portfolioMatch[3]);
    }
}

function printPortfolioTable() {
    const hash = window.location.hash.substring(1);
    const portfolioMatch = hash.match(/^(\w+)-sem(\d+)-portofolio-(kamaroperasi|poliklinik|rawatinap)$/);
    
    if (!portfolioMatch) {
        alert('Tidak dapat mengidentifikasi tabel yang akan di-print');
        return;
    }
    
    const divisi = portfolioMatch[1];
    const semester = parseInt(portfolioMatch[2]);
    const settingType = portfolioMatch[3];
    
    // Map settingType dari URL ke database values
    const settingTypeMap = {
        'kamaroperasi': 'OK',
        'poliklinik': 'Poliklinik',
        'rawatinap': 'Rawat_Inap'
    };
    
    const dbSettingType = settingTypeMap[settingType] || settingType;
    
    // Fetch data from API - now with verified_only filter
    const params = new URLSearchParams({
        action: 'list',
        divisi: divisi,
        semester: semester,
        setting_type: dbSettingType,
        verified_only: '1'  // Only fetch verified/signed items
    });

    if ((getCurrentUserRole() === 'dosen' || getCurrentUserRole() === 'admin') && portfolioState.viewUserId) {
        params.append('user_id', String(portfolioState.viewUserId));
    }
    
    fetch(`php/portfolio.php?${params}`)
        .then(response => response.json())
        .then(data => {
            if (!data.success || !data.data || data.data.length === 0) {
                alert('Tidak ada data yang sudah ditandatangani/diverifikasi untuk dicetak');
                return;
            }
            
            generatePrintWindow(data.data, divisi, semester, settingType);
        })
        .catch(error => {
            console.error('Error fetching print data:', error);
            alert('Gagal memuat data untuk print');
        });
}

function generatePrintWindow(items, divisi, semester, settingType) {
    const settingTypeNames = {
        'kamaroperasi': 'Kamar Operasi',
        'poliklinik': 'Poliklinik',
        'rawatinap': 'Rawat Inap / Bangsal'
    };
    
    // Build table rows
    const rows = items.map((item, index) => {
        // Truncate tatalaksana if too long
        let tatalaksanaDisplay = item.tatalaksana || '-';
        if (tatalaksanaDisplay.length > 30) {
            tatalaksanaDisplay = tatalaksanaDisplay.substring(0, 30) + '...';
        }
        
        // Format umur with "tahun"
        const umurDisplay = item.umur ? `${item.umur} tahun` : '-';
        
        // Check signature status and prepare signature image
        const hasTraineeSignature = item.trainee_signature ? true : false;
        const hasDPJPSignature = item.dpjp_signature ? true : false;
        const isVerified = item.dpjp_verified ? true : false;
        
        // Determine which signature to display (prefer DPJP signature if available)
        let signatureDisplay = '&nbsp;';
        let signatureStyle = 'height: 50px; vertical-align: middle;';
        
        if (hasDPJPSignature || hasTraineeSignature) {
            // Use DPJP signature if available (already verified), otherwise use trainee signature
            const signatureData = hasDPJPSignature ? item.dpjp_signature : item.trainee_signature;
            
            // Check if signature data is base64 already or needs conversion
            let imgSrc = '';
            if (signatureData) {
                // If it starts with data:, use as is; otherwise treat as base64 and add prefix
                if (signatureData.startsWith('data:')) {
                    imgSrc = signatureData;
                } else {
                    imgSrc = `data:image/png;base64,${signatureData}`;
                }
            }
            
            if (imgSrc) {
                signatureDisplay = `<img src="${imgSrc}" style="max-height: 50px; max-width: 100%; object-fit: contain;" />`;
                signatureStyle = 'height: 50px; vertical-align: middle; padding: 5px;';
            }
        }
        
        return `
            <tr>
                <td>${index + 1}</td>
                <td>${formatDate(item.tanggal)}</td>
                <td>${item.nama_pasien || '-'}</td>
                <td>${item.nomor_rm || '-'}</td>
                <td>${umurDisplay}</td>
                <td>${item.paritas || '-'}</td>
                <td>${item.diagnosis || '-'}</td>
                <td>${tatalaksanaDisplay}</td>
                <td>${item.kompetenszi || '-'}</td>
                <td style="${signatureStyle}">${signatureDisplay}</td>
            </tr>
        `;
    }).join('');
    
    const printWindow = window.open('', '_blank');
    
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Print Portfolio - ${settingTypeNames[settingType]} (Semester ${semester})</title>
            <style>
                @page {
                    size: landscape;
                    margin: 10mm;
                }
                
                body {
                    font-family: Arial, sans-serif;
                    margin: 10mm;
                }
                h1 {
                    text-align: center;
                    margin-bottom: 20px;
                    font-size: 12pt;
                    font-weight: normal;
                    page-break-after: avoid;
                }
                table {
                    width: 100%;
                    border-collapse: collapse;
                    margin-top: 20px;
                    page-break-inside: auto;
                    font-size: 10pt;
                }
                tr {
                    page-break-inside: avoid;
                    page-break-after: auto;
                }
                th, td {
                    border: 1px solid #333;
                    padding: 8px;
                    text-align: center;
                    vertical-align: middle;
                    font-size: 12pt;
                    color: #000;
                    word-wrap: break-word;
                    word-break: break-word;
                    overflow-wrap: break-word;
                    white-space: normal;
                }
                th {
                    background-color: #e0e0e0;
                    color: #000;
                    font-weight: normal;
                }
                tr:nth-child(even) {
                    background-color: #f9f9f9;
                }
                td img {
                    max-height: 50px;
                    max-width: 100%;
                    object-fit: contain;
                }
                @media print {
                    body { margin: 10px; }
                    h1 { page-break-after: avoid; }
                    table { page-break-inside: auto; }
                    tr { page-break-inside: avoid; }
                    td, th { 
                        word-wrap: break-word !important;
                        word-break: break-word !important;
                        overflow-wrap: break-word !important;
                        white-space: normal !important;
                    }
                    td:nth-child(8), th:nth-child(8) { 
                        min-width: 100px !important;
                        max-height: auto !important;
                    }
                }
            </style>
        </head>
        <body>
            <h1>Portfolio - ${settingTypeNames[settingType]} (Semester ${semester})</h1>
            <table>
                <thead>
                    <tr>
                        <th style="width: 40px;">No</th>
                        <th style="width: 80px;">Tanggal</th>
                        <th style="width: 120px;">Nama Pasien</th>
                        <th style="width: 100px;">No. RM</th>
                        <th style="width: 80px;">Umur</th>
                        <th style="width: 80px;">Paritas</th>
                        <th style="width: 150px;">Diagnosis</th>
                        <th style="width: 200px;">Tatalaksana</th>
                        <th style="width: 90px;">Kompetensi</th>
                        <th style="width: 150px;">Tanda Tangan Supervisor/DPJP</th>
                    </tr>
                </thead>
                <tbody>
                    ${rows}
                </tbody>
            </table>
            <div style="margin-top: 20px; padding-top: 10px; border-top: 1px solid #999; font-size: 11pt;">
                <p style="margin: 5px 0;">
                    <strong>Keterangan:</strong>
                </p>
                <p style="margin: 5px 0; color: #155724; background-color: #d4edda; padding: 5px; display: inline-block;">
                    Gambar tanda tangan ditampilkan untuk logbook/portofolio yang telah diverifikasi
                </p>
            </div>
            <script>
                window.onload = function() {
                    window.print();
                    window.onafterprint = function() {
                        window.close();
                    };
                };
            </script>
        </body>
        </html>
    `);
    printWindow.document.close();
}

// Mapping untuk convert settingType dari URL ke ID tabel
function getPortfolioTableTbodyId(divisi, semester, settingType) {
    // Map URL settingType to tbody ID suffix
    const tbodyIdMap = {
        'kamaroperasi': 'ok',
        'poliklinik': 'poliklinik',
        'rawatinap': 'rawatinap'
    };
    const tbodyIdSuffix = tbodyIdMap[settingType] || settingType;
    return `portfolio-data-${divisi}-sem${semester}-${tbodyIdSuffix}`;
}

function loadPortfolioDataForTable(divisi, semester, settingType) {
    const tbodyId = getPortfolioTableTbodyId(divisi, semester, settingType);
    const tbody = document.getElementById(tbodyId);
    
    console.log('Loading portfolio data for table:', tbodyId);
    console.log('tbody element found:', !!tbody);
    
    if (!tbody) {
        console.warn(`Table body not found: ${tbodyId}`);
        return;
    }

    if ((getCurrentUserRole() === 'dosen' || getCurrentUserRole() === 'admin') && !portfolioState.viewUserId) {
        tbody.innerHTML = `
            <tr>
                <td colspan="10" style="text-align: center; padding: 20px; color: #999;">
                    Pilih trainee terlebih dahulu
                </td>
            </tr>
        `;
        return;
    }
    
    // Map settingType dari URL ke database values
    const settingTypeMap = {
        'kamaroperasi': 'OK',
        'poliklinik': 'Poliklinik',
        'rawatinap': 'Rawat_Inap'
    };
    
    const dbSettingType = settingTypeMap[settingType] || settingType;
    
    console.log('Fetching with params:', { divisi, semester, dbSettingType });
    
    const params = new URLSearchParams({
        action: 'list',
        divisi: divisi,
        semester: semester,
        setting_type: dbSettingType
    });
    
    fetch(`php/portfolio.php?${params}`)
        .then(response => response.json())
        .then(data => {
            console.log('Portfolio data fetched:', data);
            if (data.success) {
                renderPortfolioDataInTable(data.data, tbody);
            } else {
                showTableError(tbody, 'Gagal memuat data');
            }
        })
        .catch(error => {
            console.error('Error loading portfolio data:', error);
            showTableError(tbody, 'Terjadi kesalahan saat memuat data');
        });
}

function renderPortfolioDataInTable(items, tbody) {
    console.log('Rendering portfolio data in table. Items count:', items ? items.length : 0);
    console.log('First item:', items && items.length > 0 ? items[0] : 'none');
    
    if (!items || items.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="10" style="text-align: center; padding: 20px; color: #999;">
                    Belum ada data pasien
                </td>
            </tr>
        `;
        return;
    }
    
    tbody.innerHTML = items.map((item, index) => {
        const hasTraineeSignature = item.trainee_signature ? '✓' : '✗';
        const hasDPJPSignature = item.dpjp_signature ? '✓' : '✗';
        const isVerified = item.dpjp_verified ? 'Sudah' : 'Belum';
        const canMessage = getCurrentUserRole() === 'dosen' || getCurrentUserRole() === 'admin';
        const recipientName = (item.user_name || '').replace(/'/g, '&#39;');
        
        // Truncate tatalaksana if too long
        let tatalaksanaDisplay = '-';
        if (item.tatalaksana) {
            if (item.tatalaksana.length > 30) {
                tatalaksanaDisplay = `<span title="${item.tatalaksana}">${item.tatalaksana.substring(0, 30)}...</span>`;
            } else {
                tatalaksanaDisplay = item.tatalaksana;
            }
        }
        
        return `
        <tr>
            <td>${index + 1}</td>
            <td>${formatDate(item.tanggal)}</td>
            <td>${item.nama_pasien || '-'}</td>
            <td>${item.nomor_rm || '-'}</td>
            <td><span title="${item.diagnosis}">${item.diagnosis.substring(0, 30)}${item.diagnosis.length > 30 ? '...' : ''}</span></td>
            <td>${tatalaksanaDisplay}</td>
            <td>${item.kompetenszi || '-'}</td>
            <td style="text-align: center; font-weight: bold;">${hasTraineeSignature}</td>
            <td>${isVerified}</td>
            <td>
                <div class="action-buttons" style="display: flex; gap: 5px; flex-wrap: wrap;">
                    <button class="btn-edit" onclick="viewPortfolioFromTable(${item.id})" title="Lihat">Lihat</button>
                    <button class="btn-edit" onclick="editPortfolioFromTable(${item.id})" title="Edit">Edit</button>
                    <button class="btn-delete" onclick="deletePortfolioFromTable(${item.id})" title="Hapus">Hapus</button>
                    ${canMessage ? `<button class="btn btn-info" onclick="openMessageModal('portfolio', ${item.id}, ${item.user_id}, '${recipientName}')" title="Pesan">Pesan</button>` : ''}
                </div>
            </td>
        </tr>
    `;
    }).join('');
    
    // Setup search functionality
    injectPortfolioSearch();
}

function editPortfolioFromTable(portfolioId) {
    // Set state dan buka form
    portfolioState.currentEditId = portfolioId;
    openPortfolioForm(portfolioId);
}

function deletePortfolioFromTable(portfolioId) {
    if (!confirm('Apakah Anda yakin ingin menghapus portofolio ini?')) {
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'delete');
    formData.append('id', portfolioId);
    
    fetch('php/portfolio.php', {
        method: 'POST',
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Portofolio berhasil dihapus');
                // Reload data tabel
                const hash = window.location.hash.substring(1);
                const portfolioMatch = hash.match(/^(\w+)-sem(\d+)-portofolio-(kamaroperasi|poliklinik|rawatinap)$/);
                if (portfolioMatch) {
                    loadPortfolioDataForTable(portfolioMatch[1], parseInt(portfolioMatch[2]), portfolioMatch[3]);
                }
            } else {
                alert('Gagal menghapus portofolio: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error deleting portfolio:', error);
            alert('Terjadi kesalahan saat menghapus portofolio');
        });
}

function viewPortfolioFromTable(portfolioId) {
    // Fetch portfolio data and display in view modal
    const formData = new FormData();
    formData.append('action', 'fetch');
    formData.append('id', portfolioId);
    
    fetch('php/portfolio.php', {
        method: 'POST',
        body: formData
    })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.text();
        })
        .then(text => {
            try {
                const data = JSON.parse(text);
                if (data.success && data.data) {
                    displayPortfolioInViewModal(data.data);
                    document.getElementById('portfolioViewModal').style.display = 'flex';
                    portfolioState.currentEditId = portfolioId;
                } else {
                    alert('Gagal memuat data portofolio: ' + (data.error || 'Unknown error'));
                }
            } catch (e) {
                console.error('JSON Parse Error:', e);
                console.log('Response text:', text);
                alert('Error parsing response: ' + e.message);
            }
        })
        .catch(error => {
            console.error('Error fetching portfolio:', error);
            alert('Terjadi kesalahan saat memuat data portofolio: ' + error.message);
        });
}

function displayPortfolioInViewModal(item) {
    // Fill in the view modal with portfolio data
    document.getElementById('view-portfolio-nomor').textContent = item.nomor || '-';
    document.getElementById('view-portfolio-tanggal').textContent = formatDate(item.tanggal) || '-';
    document.getElementById('view-portfolio-identifikasi').textContent = item.identifikasi_pasien || '-';
    document.getElementById('view-portfolio-diagnosis').textContent = item.diagnosis || '-';
    document.getElementById('view-portfolio-tatalaksana').textContent = item.tatalaksana || '-';
    document.getElementById('view-portfolio-kompetenszi').textContent = item.kompetenszi || '-';
    document.getElementById('view-portfolio-supervisor').textContent = item.supervisor_name || '-';
    document.getElementById('view-portfolio-supervisor-initial').textContent = item.supervisor_initial || '-';
    
    const verificationStatus = item.dpjp_verified ? 'Sudah Diverifikasi' : 'Belum Diverifikasi';
    document.getElementById('view-portfolio-verification-status').textContent = verificationStatus;
    
    // Handle trainee signature
    const traineeSignatureImg = document.getElementById('view-trainee-signature-img');
    const traineeSignatureEmpty = document.getElementById('view-trainee-signature-empty');
    if (item.trainee_signature) {
        traineeSignatureImg.src = item.trainee_signature;
        traineeSignatureImg.style.display = 'block';
        traineeSignatureEmpty.style.display = 'none';
    } else {
        traineeSignatureImg.style.display = 'none';
        traineeSignatureEmpty.style.display = 'block';
    }
    
    // Handle DPJP signature
    const dpjpSignatureSection = document.getElementById('view-dpjp-signature-section');
    const dpjpSignatureImg = document.getElementById('view-dpjp-signature-img');
    const dpjpSignatureEmpty = document.getElementById('view-dpjp-signature-empty');
    
    if (item.dpjp_signature) {
        dpjpSignatureSection.style.display = 'block';
        dpjpSignatureImg.src = item.dpjp_signature;
        dpjpSignatureImg.style.display = 'block';
        dpjpSignatureEmpty.style.display = 'none';
    } else {
        dpjpSignatureSection.style.display = 'none';
        dpjpSignatureImg.style.display = 'none';
        dpjpSignatureEmpty.style.display = 'block';
    }
}

function closePortfolioView() {
    document.getElementById('portfolioViewModal').style.display = 'none';
}

function editPortfolioFromView() {
    closePortfolioView();
    if (portfolioState.currentEditId) {
        editPortfolioFromTable(portfolioState.currentEditId);
    }
}

function showTableError(tbody, message) {
    tbody.innerHTML = `
        <tr>
            <td colspan="9" style="text-align: center; padding: 20px; color: #dc3545;">
                ${message}
            </td>
        </tr>
    `;
}

// Initialize portfolio with specific context
function initializePortfolio(divisi, semester, settingType) {
    portfolioState.currentDivisi = divisi;
    portfolioState.currentSemester = semester;
    portfolioState.currentSettingType = settingType;
    
    // Load portfolio list and show list view
    loadPortfolioList();
    showPortfolioListView();
}

// Open portfolio form (new or edit)
// Load supervisors list for dropdown
function loadSupervisors() {
    fetch('php/portfolio.php?action=get_supervisors')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const select = document.getElementById('portfolio-supervisor-initial');
                if (select) {
                    // Clear existing options except the first one
                    select.innerHTML = '<option value="">-- Pilih Inisial Supervisor --</option>';
                    
                    // Add supervisor options
                    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;
                        select.appendChild(option);
                    });
                    
                    // Add onchange event to auto-fill supervisor name
                    select.onchange = function() {
                        const selectedOption = this.options[this.selectedIndex];
                        const supervisorNameField = document.getElementById('portfolio-supervisor');
                        if (selectedOption && selectedOption.dataset.fullName) {
                            supervisorNameField.value = selectedOption.dataset.fullName;
                        } else {
                            supervisorNameField.value = '';
                        }
                    };
                }
            }
        })
        .catch(error => console.error('Error loading supervisors:', error));
}

function openPortfolioForm(portfolioId) {
    const modal = document.getElementById('portfolioFormModal');
    const title = document.getElementById('portfolioFormTitle');
    const form = document.getElementById('portfolioForm');
    const dpjpSection = document.getElementById('dpjpSignatureSection');
    const submitBtn = document.getElementById('submitVerificationBtn');
    const verifyBtn = document.getElementById('verifyDpjpBtn');
    
    portfolioState.currentEditId = portfolioId;
    
    // Reset form
    form.reset();
    document.getElementById('portfolio-trainee-signature').value = '';
    document.getElementById('portfolio-dpjp-signature').value = '';
    clearTraineeSignature();
    clearDPJPSignature();
    
    // Load supervisors list
    loadSupervisors();
    
    if (portfolioId) {
        title.textContent = 'Edit Portofolio';
        loadPortfolioData(portfolioId);
    } else {
        title.textContent = 'Tambah Portofolio Baru';
        getNextNomor();
        document.getElementById('portfolio-tanggal').valueAsDate = new Date();
        if (submitBtn) submitBtn.style.display = 'none';
        if (verifyBtn) verifyBtn.style.display = 'none';
    }

    if (dpjpSection) {
        dpjpSection.style.display = (getCurrentUserRole() === 'dosen' || getCurrentUserRole() === 'admin') ? 'block' : 'none';
    }
    
    modal.style.display = 'flex';
    
    // Initialize signature canvases if not already done
    initializeSignatureCanvases();
}

// Close portfolio form
function closePortfolioForm() {
    const modal = document.getElementById('portfolioFormModal');
    modal.style.display = 'none';
    portfolioState.currentEditId = null;
}

// Get next portfolio number
function getNextNomor() {
    const params = new URLSearchParams({
        action: 'get_next_nomor',
        divisi: portfolioState.currentDivisi,
        semester: portfolioState.currentSemester,
        setting_type: portfolioState.currentSettingType
    });
    
    fetch(`php/portfolio.php?${params}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('portfolio-nomor').value = data.nomor;
            }
        })
        .catch(error => console.error('Error getting nomor:', error));
}

// Load portfolio data for editing
function loadPortfolioData(portfolioId) {
    const params = new URLSearchParams({
        action: 'get',
        id: portfolioId
    });
    
    fetch(`php/portfolio.php?${params}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const portfolio = data.data;
                
                document.getElementById('portfolio-nomor').value = portfolio.nomor;
                document.getElementById('portfolio-tanggal').value = portfolio.tanggal;
                
                // Parse identifikasi_pasien or populate individual fields if they exist
                if (portfolio.nama_pasien) {
                    document.getElementById('portfolio-nama').value = portfolio.nama_pasien || '';
                    document.getElementById('portfolio-nomor-rm').value = portfolio.nomor_rm || '';
                    document.getElementById('portfolio-umur').value = portfolio.umur || '';
                    document.getElementById('portfolio-paritas').value = portfolio.paritas || '';
                    document.getElementById('portfolio-alamat').value = portfolio.alamat || '';
                } else if (portfolio.identifikasi_pasien) {
                    // Fallback: try to populate from identifikasi_pasien if fields don't exist separately
                    document.getElementById('portfolio-nama').value = portfolio.identifikasi_pasien;
                }
                
                document.getElementById('portfolio-diagnosis').value = portfolio.diagnosis;
                document.getElementById('portfolio-tatalaksana').value = portfolio.tatalaksana;
                document.getElementById('portfolio-kompetenszi').value = portfolio.kompetenszi;
                document.getElementById('portfolio-supervisor').value = portfolio.supervisor_name;
                
                // Set supervisor initial if exists
                if (portfolio.supervisor_initial) {
                    const supervisorInitialSelect = document.getElementById('portfolio-supervisor-initial');
                    if (supervisorInitialSelect) {
                        supervisorInitialSelect.value = portfolio.supervisor_initial;
                    }
                }
                
                // Load signatures if exist
                if (portfolio.trainee_signature) {
                    document.getElementById('portfolio-trainee-signature').value = portfolio.trainee_signature;
                    drawSignatureFromImage('traineeSignatureCanvas', portfolio.trainee_signature);
                }
                
                if (portfolio.dpjp_signature) {
                    document.getElementById('portfolio-dpjp-signature').value = portfolio.dpjp_signature;
                    drawSignatureFromImage('dpjpSignatureCanvas', portfolio.dpjp_signature);
                }
                
                // Toggle submit/verify buttons based on role
                const submitBtn = document.getElementById('submitVerificationBtn');
                const verifyBtn = document.getElementById('verifyDpjpBtn');
                const isDosen = getCurrentUserRole() === 'dosen' || getCurrentUserRole() === 'admin';

                if (isDosen) {
                    if (verifyBtn) verifyBtn.style.display = portfolio.status !== 'verified' ? 'block' : 'none';
                    if (submitBtn) submitBtn.style.display = 'none';
                } else {
                    if (submitBtn) submitBtn.style.display = portfolio.status === 'draft' ? 'block' : 'none';
                    if (verifyBtn) verifyBtn.style.display = 'none';
                }
            }
        })
        .catch(error => console.error('Error loading portfolio:', error));
}

function verifyPortfolioDpjp() {
    if (getCurrentUserRole() !== 'dosen' && getCurrentUserRole() !== 'admin') {
        alert('Hanya dosen yang dapat melakukan verifikasi DPJP');
        return;
    }

    const portfolioId = portfolioState.currentEditId;
    if (!portfolioId) {
        alert('Portfolio ID tidak ditemukan');
        return;
    }

    const dpjpSignature = document.getElementById('portfolio-dpjp-signature').value;
    if (!dpjpSignature) {
        alert('Mohon tandatangani kolom DPJP terlebih dahulu');
        return;
    }

    const payload = {
        action: 'verify_dpjp',
        id: portfolioId,
        dpjp_signature: dpjpSignature
    };

    fetch('php/portfolio.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json; charset=utf-8'
        },
        body: JSON.stringify(payload)
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Portofolio berhasil diverifikasi');
                closePortfolioForm();
                const hash = window.location.hash.substring(1);
                const match = hash.match(/^(\w+)-sem(\d+)-portofolio-(kamaroperasi|poliklinik|rawatinap)$/);
                if (match) {
                    loadPortfolioDataForTable(match[1], parseInt(match[2], 10), match[3]);
                }
                // Update recent activities on dashboard if function exists
                if (typeof loadRecentActivities === 'function') {
                    loadRecentActivities();
                }
            } else {
                alert('Gagal verifikasi portofolio: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error verifying portfolio:', error);
            alert('Terjadi kesalahan saat verifikasi');
        });
}

// Initialize signature canvases
function initializeSignatureCanvases() {
    // Trainee signature
    const traineeCanvas = document.getElementById('traineeSignatureCanvas');
    if (traineeCanvas) {
        portfolioState.traineeSignatureCanvas = traineeCanvas;
        portfolioState.traineeCtx = traineeCanvas.getContext('2d');
        
        traineeCanvas.addEventListener('mousedown', startDrawingTrainee);
        traineeCanvas.addEventListener('mousemove', drawTrainee);
        traineeCanvas.addEventListener('mouseup', stopDrawingTrainee);
        traineeCanvas.addEventListener('mouseout', stopDrawingTrainee);
        
        // Touch support
        traineeCanvas.addEventListener('touchstart', startDrawingTraineeTouch);
        traineeCanvas.addEventListener('touchmove', drawTraineeTouch);
        traineeCanvas.addEventListener('touchend', stopDrawingTrainee);
    }
    
    // DPJP signature
    const dpjpCanvas = document.getElementById('dpjpSignatureCanvas');
    if (dpjpCanvas) {
        portfolioState.dpjpSignatureCanvas = dpjpCanvas;
        portfolioState.dpjpCtx = dpjpCanvas.getContext('2d');
        
        dpjpCanvas.addEventListener('mousedown', startDrawingDPJP);
        dpjpCanvas.addEventListener('mousemove', drawDPJP);
        dpjpCanvas.addEventListener('mouseup', stopDrawingDPJP);
        dpjpCanvas.addEventListener('mouseout', stopDrawingDPJP);
        
        // Touch support
        dpjpCanvas.addEventListener('touchstart', startDrawingDPJPTouch);
        dpjpCanvas.addEventListener('touchmove', drawDPJPTouch);
        dpjpCanvas.addEventListener('touchend', stopDrawingDPJP);
    }
}

// Trainee signature drawing functions
function startDrawingTrainee(e) {
    if (!portfolioState.traineeSignatureCanvas) {
        console.error('Trainee canvas not initialized');
        return;
    }
    const rect = portfolioState.traineeSignatureCanvas.getBoundingClientRect();
    portfolioState.lastX = e.clientX - rect.left;
    portfolioState.lastY = e.clientY - rect.top;
    portfolioState.isDrawingTrainee = true;
    console.log('Started drawing trainee signature at', portfolioState.lastX, portfolioState.lastY);
}

function drawTrainee(e) {
    if (!portfolioState.isDrawingTrainee || !portfolioState.traineeSignatureCanvas) return;
    
    const rect = portfolioState.traineeSignatureCanvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    portfolioState.traineeCtx.beginPath();
    portfolioState.traineeCtx.moveTo(portfolioState.lastX, portfolioState.lastY);
    portfolioState.traineeCtx.lineTo(x, y);
    portfolioState.traineeCtx.strokeStyle = '#333';
    portfolioState.traineeCtx.lineWidth = 2;
    portfolioState.traineeCtx.lineCap = 'round';
    portfolioState.traineeCtx.lineJoin = 'round';
    portfolioState.traineeCtx.stroke();
    
    portfolioState.lastX = x;
    portfolioState.lastY = y;
}

function stopDrawingTrainee() {
    portfolioState.isDrawingTrainee = false;
    saveTraineeSignature();
}

function startDrawingTraineeTouch(e) {
    const touch = e.touches[0];
    const rect = portfolioState.traineeSignatureCanvas.getBoundingClientRect();
    portfolioState.lastX = touch.clientX - rect.left;
    portfolioState.lastY = touch.clientY - rect.top;
    portfolioState.isDrawingTrainee = true;
}

function drawTraineeTouch(e) {
    if (!portfolioState.isDrawingTrainee) return;
    e.preventDefault();
    
    const touch = e.touches[0];
    const rect = portfolioState.traineeSignatureCanvas.getBoundingClientRect();
    const x = touch.clientX - rect.left;
    const y = touch.clientY - rect.top;
    
    portfolioState.traineeCtx.beginPath();
    portfolioState.traineeCtx.moveTo(portfolioState.lastX, portfolioState.lastY);
    portfolioState.traineeCtx.lineTo(x, y);
    portfolioState.traineeCtx.strokeStyle = '#333';
    portfolioState.traineeCtx.lineWidth = 2;
    portfolioState.traineeCtx.lineCap = 'round';
    portfolioState.traineeCtx.lineJoin = 'round';
    portfolioState.traineeCtx.stroke();
    
    portfolioState.lastX = x;
    portfolioState.lastY = y;
}

function clearTraineeSignature() {
    if (portfolioState.traineeSignatureCanvas && portfolioState.traineeCtx) {
        portfolioState.traineeCtx.clearRect(0, 0, portfolioState.traineeSignatureCanvas.width, portfolioState.traineeSignatureCanvas.height);
        document.getElementById('portfolio-trainee-signature').value = '';
    }
}

function saveTraineeSignature() {
    if (portfolioState.traineeSignatureCanvas) {
        const signatureData = portfolioState.traineeSignatureCanvas.toDataURL('image/png');
        document.getElementById('portfolio-trainee-signature').value = signatureData;
    }
}

// DPJP signature drawing functions
function startDrawingDPJP(e) {
    const rect = portfolioState.dpjpSignatureCanvas.getBoundingClientRect();
    portfolioState.lastX = e.clientX - rect.left;
    portfolioState.lastY = e.clientY - rect.top;
    portfolioState.isDrawingDPJP = true;
}

function drawDPJP(e) {
    if (!portfolioState.isDrawingDPJP || !portfolioState.dpjpSignatureCanvas) return;
    
    const rect = portfolioState.dpjpSignatureCanvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    portfolioState.dpjpCtx.beginPath();
    portfolioState.dpjpCtx.moveTo(portfolioState.lastX, portfolioState.lastY);
    portfolioState.dpjpCtx.lineTo(x, y);
    portfolioState.dpjpCtx.strokeStyle = '#333';
    portfolioState.dpjpCtx.lineWidth = 2;
    portfolioState.dpjpCtx.lineCap = 'round';
    portfolioState.dpjpCtx.lineJoin = 'round';
    portfolioState.dpjpCtx.stroke();
    
    portfolioState.lastX = x;
    portfolioState.lastY = y;
}

function stopDrawingDPJP() {
    portfolioState.isDrawingDPJP = false;
    saveDPJPSignature();
}

function startDrawingDPJPTouch(e) {
    const touch = e.touches[0];
    const rect = portfolioState.dpjpSignatureCanvas.getBoundingClientRect();
    portfolioState.lastX = touch.clientX - rect.left;
    portfolioState.lastY = touch.clientY - rect.top;
    portfolioState.isDrawingDPJP = true;
}

function drawDPJPTouch(e) {
    if (!portfolioState.isDrawingDPJP) return;
    e.preventDefault();
    
    const touch = e.touches[0];
    const rect = portfolioState.dpjpSignatureCanvas.getBoundingClientRect();
    const x = touch.clientX - rect.left;
    const y = touch.clientY - rect.top;
    
    portfolioState.dpjpCtx.beginPath();
    portfolioState.dpjpCtx.moveTo(portfolioState.lastX, portfolioState.lastY);
    portfolioState.dpjpCtx.lineTo(x, y);
    portfolioState.dpjpCtx.strokeStyle = '#333';
    portfolioState.dpjpCtx.lineWidth = 2;
    portfolioState.dpjpCtx.lineCap = 'round';
    portfolioState.dpjpCtx.lineJoin = 'round';
    portfolioState.dpjpCtx.stroke();
    
    portfolioState.lastX = x;
    portfolioState.lastY = y;
}

function clearDPJPSignature() {
    if (portfolioState.dpjpSignatureCanvas && portfolioState.dpjpCtx) {
        portfolioState.dpjpCtx.clearRect(0, 0, portfolioState.dpjpSignatureCanvas.width, portfolioState.dpjpSignatureCanvas.height);
        document.getElementById('portfolio-dpjp-signature').value = '';
    }
}

function saveDPJPSignature() {
    if (portfolioState.dpjpSignatureCanvas) {
        const signatureData = portfolioState.dpjpSignatureCanvas.toDataURL('image/png');
        document.getElementById('portfolio-dpjp-signature').value = signatureData;
    }
}

// Draw signature from image data
function drawSignatureFromImage(canvasId, imageData) {
    const canvas = document.getElementById(canvasId);
    const ctx = canvas.getContext('2d');
    const img = new Image();
    
    img.onload = function() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        // Scale and center the image
        const scale = Math.min(canvas.width / img.width, canvas.height / img.height);
        const x = (canvas.width / 2) - (img.width / 2) * scale;
        const y = (canvas.height / 2) - (img.height / 2) * scale;
        ctx.drawImage(img, x, y, img.width * scale, img.height * scale);
    };
    
    img.src = imageData;
}

// Show portfolio list view
function showPortfolioListView() {
    const formModal = document.getElementById('portfolioFormModal');
    const listView = document.getElementById('portfolioListView');
    
    formModal.style.display = 'none';
    listView.style.display = 'block';
    
    // Update title
    const titles = {
        'OK': 'Kamar Operasi',
        'Poliklinik': 'Poliklinik',
        'Rawat_Inap': 'Rawat Inap / Bangsal'
    };
    
    document.getElementById('portfolioListTitle').textContent = 
        `Portofolio - ${titles[portfolioState.currentSettingType] || ''} (Semester ${portfolioState.currentSemester})`;
}

// Load portfolio list
function loadPortfolioList() {
    const params = new URLSearchParams({
        action: 'list',
        divisi: portfolioState.currentDivisi,
        semester: portfolioState.currentSemester,
        setting_type: portfolioState.currentSettingType
    });

    if ((getCurrentUserRole() === 'dosen' || getCurrentUserRole() === 'admin') && portfolioState.viewUserId) {
        params.append('user_id', String(portfolioState.viewUserId));
    }
    
    fetch(`php/portfolio.php?${params}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderPortfolioList(data.data);
            }
        })
        .catch(error => console.error('Error loading portfolio list:', error));
}

// Render portfolio list in table
function renderPortfolioList(items) {
    const tbody = document.getElementById('portfolioTableBody');
    
    // Store items for filtering
    portfolioState.currentPortfolioItems = items;
    
    if (!items || items.length === 0) {
        const isDosen = getCurrentUserRole() === 'dosen' || getCurrentUserRole() === 'admin';
        const emptyText = isDosen
            ? 'Tidak ada data portofolio untuk trainee ini.'
            : 'Tidak ada data portofolio. <a href="#" onclick="openPortfolioForm(null); return false;">Tambah yang pertama</a>';
        tbody.innerHTML = `
            <tr>
                <td colspan="7" style="text-align: center; padding: 20px; color: #999;">
                    ${emptyText}
                </td>
            </tr>
        `;
        return;
    }
    
    const statusLabels = {
        'draft': 'Draft',
        'submitted': 'Menunggu Verifikasi',
        'verified': 'Terverifikasi'
    };
    
    tbody.innerHTML = items.map(item => {
        // Try to extract patient info from identifikasi_pasien or use raw value
        let patientInfo = item.identifikasi_pasien.substring(0, 50) + '...';
        if (item.identifikasi_pasien && item.identifikasi_pasien.includes('Nama:')) {
            // Extract nama and nomor RM if available
            const namaMatch = item.identifikasi_pasien.match(/Nama:\s*([^,]+)/);
            const rmMatch = item.identifikasi_pasien.match(/No\.\s*RM:\s*([^,]+)/);
            if (namaMatch && rmMatch) {
                patientInfo = namaMatch[1].trim() + ' (' + rmMatch[1].trim() + ')';
            }
        }
        
        return `
        <tr class="portfolio-row" data-search="${(item.identifikasi_pasien + ' ' + item.diagnosis + ' ' + (item.tatalaksana || '') + ' ' + (item.kompetenszi || '')).toLowerCase()}">
            <td>${item.nomor}</td>
            <td>${formatDate(item.tanggal)}</td>
            <td>${patientInfo}</td>
            <td>${item.diagnosis.substring(0, 50)}...</td>
            <td>${item.kompetenszi || '-'}</td>
            <td>
                <span class="status-badge status-${item.status}">
                    ${statusLabels[item.status] || item.status}
                </span>
            </td>
            <td>
                <div class="action-buttons">
                    <button class="btn-edit" onclick="openPortfolioForm(${item.id})" title="Edit">Edit</button>
                    <button class="btn-delete" onclick="deletePortfolio(${item.id})" title="Hapus">Hapus</button>
                </div>
            </td>
        </tr>
    `;
    }).join('');
    
    // Setup search functionality
    setupPortfolioSearch();
}

// Delete portfolio
function deletePortfolio(portfolioId) {
    if (!confirm('Apakah Anda yakin ingin menghapus portofolio ini?')) {
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'delete');
    formData.append('id', portfolioId);
    
    fetch('php/portfolio.php', {
        method: 'POST',
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Portofolio berhasil dihapus');
                loadPortfolioList();
            } else {
                alert('Gagal menghapus portofolio: ' + data.error);
            }
        })
        .catch(error => {
            console.error('Error deleting portfolio:', error);
            alert('Terjadi kesalahan saat menghapus portofolio');
        });
}

// Submit portfolio for verification
function submitPortfolioForVerification() {
    const portfolioId = portfolioState.currentEditId;
    
    if (!portfolioId) {
        alert('Portfolio ID tidak ditemukan');
        return;
    }
    
    if (!confirm('Apakah Anda yakin ingin mengajukan portofolio ini untuk verifikasi DPJP?')) {
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'submit_for_verification');
    formData.append('id', portfolioId);
    
    fetch('php/portfolio.php', {
        method: 'POST',
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Portofolio berhasil diajukan untuk verifikasi DPJP');
                closePortfolioForm();
                loadPortfolioList();
            } else {
                alert('Gagal mengajukan portofolio: ' + data.error);
            }
        })
        .catch(error => {
            console.error('Error submitting portfolio:', error);
            alert('Terjadi kesalahan saat mengajukan portofolio');
        });
}

// Save portfolio form
document.addEventListener('DOMContentLoaded', function() {
    const portfolioForm = document.getElementById('portfolioForm');
    if (portfolioForm) {
        portfolioForm.addEventListener('submit', function(e) {
            e.preventDefault();
            savePortfolio();
        });
    }
});

function savePortfolio() {
    const traineeSignatureRaw = document.getElementById('portfolio-trainee-signature').value;
    
    console.log('Starting portfolio save...');
    
    // Trainee signature is required
    if (!traineeSignatureRaw) {
        alert('Mohon tandatangani kolom tanda tangan trainee terlebih dahulu');
        return;
    }
    
    // Get patient identification fields
    const namaPasien = document.getElementById('portfolio-nama').value.trim();
    const nomorRM = document.getElementById('portfolio-nomor-rm').value.trim();
    const diagnosis = document.getElementById('portfolio-diagnosis').value.trim();
    const tatalaksana = document.getElementById('portfolio-tatalaksana').value.trim();
    
    // Validate required fields
    if (!namaPasien || !nomorRM || !diagnosis || !tatalaksana) {
        alert('Mohon lengkapi semua kolom yang wajib diisi');
        return;
    }
    
    const portfolioId = portfolioState.currentEditId;
    
    // Concatenate patient identification fields
    const umur = document.getElementById('portfolio-umur').value.trim();
    const paritas = document.getElementById('portfolio-paritas').value.trim();
    const alamat = document.getElementById('portfolio-alamat').value.trim();
    
    const identifikasiPasienCombined = `Nama: ${namaPasien}, No. RM: ${nomorRM}${umur ? ', Umur: ' + umur : ''}${paritas ? ', Paritas: ' + paritas : ''}${alamat ? ', Alamat: ' + alamat : ''}`;
    
    // Strip data URI prefix from signature if present
    let traineeSignature = traineeSignatureRaw;
    if (traineeSignature.includes('data:image')) {
        traineeSignature = traineeSignature.replace(/^data:image\/[^;]+;base64,/, '');
    }
    
    // Prepare data
    const data = {
        action: portfolioId ? 'update' : 'create',
        divisi: portfolioState.currentDivisi,
        semester: portfolioState.currentSemester,
        setting_type: portfolioState.currentSettingType,
        id: portfolioId,
        tanggal: document.getElementById('portfolio-tanggal').value,
        identifikasi_pasien: identifikasiPasienCombined,
        nama_pasien: namaPasien,
        nomor_rm: nomorRM,
        umur: umur ? parseInt(umur) : '',
        paritas: paritas,
        alamat: alamat,
        diagnosis: diagnosis,
        tatalaksana: tatalaksana,
        kompetenszi: document.getElementById('portfolio-kompetenszi').value,
        supervisor_name: document.getElementById('portfolio-supervisor').value,
        supervisor_initial: document.getElementById('portfolio-supervisor-initial').value,
        trainee_signature: traineeSignature,  // Send base64 without prefix
        dpjp_signature: document.getElementById('portfolio-dpjp-signature').value
    };
    
    console.log('Sending portfolio data, signature length:', data.trainee_signature.length);
    
    fetch('php/portfolio.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json; charset=utf-8'
        },
        body: JSON.stringify(data)
    })
        .then(response => {
            console.log('Got response, status:', response.status);
            return response.text().then(text => {
                console.log('Raw response text:', text.substring(0, 200));
                if (!text) {
                    throw new Error('Empty response from server');
                }
                try {
                    return JSON.parse(text);
                } catch (e) {
                    console.error('Failed to parse JSON. Response:', text);
                    throw new Error('Invalid JSON response: ' + e.message);
                }
            });
        })
        .then(result => {
            console.log('Parsed response:', result);
            if (result.success) {
                console.log('Portfolio saved successfully!');
                closePortfolioForm();
                
                alert('Portofolio berhasil disimpan');
                
                // Reload table data based on current hash
                const hash = window.location.hash.substring(1);
                const portfolioMatch = hash.match(/^(\w+)-sem(\d+)-portofolio-(kamaroperasi|poliklinik|rawatinap)$/);
                if (portfolioMatch) {
                    loadPortfolioDataForTable(portfolioMatch[1], parseInt(portfolioMatch[2]), portfolioMatch[3]);
                }
            } else {
                console.error('Save failed:', result.error);
                alert('Gagal menyimpan portofolio:\n' + (result.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Complete error:', error);
            alert('Kesalahan jaringan:\n' + error.message);
        });
}

// Utility function to format date
function formatDate(dateString) {
    const options = { year: 'numeric', month: 'long', day: 'numeric' };
    return new Date(dateString).toLocaleDateString('id-ID', options);
}

// Close modal when pressing Escape
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        const modal = document.getElementById('portfolioFormModal');
        if (modal && modal.style.display !== 'none') {
            closePortfolioForm();
        }
    }
});

// Portfolio success notification functions
function showPortfolioSuccessNotification(message) {
    document.getElementById('successMessage').textContent = message;
    document.getElementById('portfolioSuccessNotification').style.display = 'flex';
}

function hidePortfolioSuccessNotification() {
    document.getElementById('portfolioSuccessNotification').style.display = 'none';
}

function showPortfolioList() {
    hidePortfolioSuccessNotification();
    closePortfolioForm();
    showPortfolioListView();
}

function addPortfolioAgain() {
    hidePortfolioSuccessNotification();
    closePortfolioForm();
    openPortfolioForm(null);
}

// Setup search functionality for portfolio list
function setupPortfolioSearch() {
    const searchInput = document.getElementById('portfolioSearchInput');
    if (searchInput) {
        searchInput.value = '';  // Clear previous search
        searchInput.addEventListener('input', filterPortfolioTable);
    }
}

// Filter portfolio table
function filterPortfolioTable(event) {
    const searchTerm = event.target.value.toLowerCase().trim();
    const tbody = document.getElementById('portfolioTableBody');
    const rows = tbody.querySelectorAll('.portfolio-row');
    
    let visibleCount = 0;
    rows.forEach(row => {
        const searchData = row.getAttribute('data-search');
        if (searchData.includes(searchTerm)) {
            row.style.display = '';
            visibleCount++;
        } else {
            row.style.display = 'none';
        }
    });
    
    // Show "no results" message if no visible rows
    if (visibleCount === 0 && searchTerm !== '') {
        const emptyRow = tbody.querySelector('tr[style="display: none;"]');
        if (!emptyRow) {
            tbody.innerHTML += `
                <tr>
                    <td colspan="7" style="text-align: center; padding: 20px; color: #999;">
                        Tidak ada hasil pencarian untuk "${searchTerm}"
                    </td>
                </tr>
            `;
        }
    }
}

// Escape key support for success notification
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        const notif = document.getElementById('portfolioSuccessNotification');
        if (notif && notif.style.display !== 'none') {
            hidePortfolioSuccessNotification();
        }
    }
});
