/**
 * Portfolio Form Management System
 * 
 * This system provides comprehensive portfolio submission functionality for PPDS-2 trainees,
 * including digital signature capture and DPJP verification workflow.
 * 
 * @author E-Logbook PPDS Development Team
 * @version 1.0.0
 * @since 2026-02-25
 */

// ============================================================================
// PORTFOLIO STATE MANAGEMENT
// ============================================================================

/**
 * Global portfolio state object
 * Manages current form context and UI state
 */
let portfolioState = {
    // Current portfolio context
    currentEditId: null,              // ID of portfolio being edited (null for new)
    currentDivisi: null,              // Current division (e.g., "fertilitas")
    currentSemester: null,            // Current semester (1-5)
    currentSettingType: null,         // Current setting: "OK", "Poliklinik", "Rawat_Inap"
    
    // Canvas and drawing state
    traineeSignatureCanvas: null,     // Reference to trainee signature canvas
    traineeCtx: null,                 // 2D context for trainee canvas
    dpjpSignatureCanvas: null,        // Reference to DPJP signature canvas
    dpjpCtx: null,                    // 2D context for DPJP canvas
    isDrawingTrainee: false,          // Whether currently drawing trainee signature
    isDrawingDPJP: false,             // Whether currently drawing DPJP signature
    lastX: null,                      // Last X coordinate for smooth drawing
    lastY: null                       // Last Y coordinate for smooth drawing
};

// ============================================================================
// PORTFOLIO INITIALIZATION
// ============================================================================

/**
 * Initialize portfolio with specific context
 * Sets the current division, semester, and setting type
 * Loads the portfolio list for the selected context
 * 
 * @param {string} divisi - Division name (e.g., "fertilitas")
 * @param {number} semester - Semester number (1-5)
 * @param {string} settingType - Setting type: "OK", "Poliklinik", or "Rawat_Inap"
 * 
 * @example
 * initializePortfolio('fertilitas', 1, 'OK');
 */
function initializePortfolio(divisi, semester, settingType) {
    portfolioState.currentDivisi = divisi;
    portfolioState.currentSemester = semester;
    portfolioState.currentSettingType = settingType;
    
    loadPortfolioList();
    showPortfolioListView();
}

// ============================================================================
// FORM MODAL MANAGEMENT
// ============================================================================

/**
 * Open portfolio form in modal
 * Shows new form or loads existing portfolio for editing
 * 
 * @param {number|null} portfolioId - ID of portfolio to edit, null for new entry
 * 
 * @example
 * openPortfolioForm(null);    // New entry
 * openPortfolioForm(5);       // Edit entry with ID 5
 */
function openPortfolioForm(portfolioId) {
    const modal = document.getElementById('portfolioFormModal');
    const title = document.getElementById('portfolioFormTitle');
    const form = document.getElementById('portfolioForm');
    
    portfolioState.currentEditId = portfolioId;
    
    // Clear form and signatures
    form.reset();
    document.getElementById('portfolio-trainee-signature').value = '';
    document.getElementById('portfolio-dpjp-signature').value = '';
    clearTraineeSignature();
    clearDPJPSignature();
    
    if (portfolioId) {
        // Edit mode
        title.textContent = 'Edit Portofolio';
        loadPortfolioData(portfolioId);
    } else {
        // Create mode
        title.textContent = 'Tambah Portofolio Baru';
        getNextNomor();
        document.getElementById('portfolio-tanggal').valueAsDate = new Date();
        document.getElementById('submitVerificationBtn').style.display = 'none';
    }
    
    modal.style.display = 'flex';
    initializeSignatureCanvases();
}

/**
 * Close portfolio form modal
 * Hides the form and resets edit state
 */
function closePortfolioForm() {
    const modal = document.getElementById('portfolioFormModal');
    modal.style.display = 'none';
    portfolioState.currentEditId = null;
}

// ============================================================================
// PORTFOLIO DATA OPERATIONS
// ============================================================================

/**
 * Fetch next portfolio number for current context
 * Makes API call to get_next_nomor action
 * Updates the nomor field in the form
 */
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
 * Fetches portfolio record and populates form fields
 * Restores signatures if they exist
 * 
 * @param {number} portfolioId - ID of portfolio to load
 */
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;
                
                // Populate form fields
                document.getElementById('portfolio-nomor').value = portfolio.nomor;
                document.getElementById('portfolio-tanggal').value = portfolio.tanggal;
                document.getElementById('portfolio-identifikasi').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;
                
                // Restore signatures
                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);
                }
                
                // Show submit button only if status is draft
                const submitBtn = document.getElementById('submitVerificationBtn');
                submitBtn.style.display = portfolio.status === 'draft' ? 'block' : 'none';
            }
        })
        .catch(error => console.error('Error loading portfolio:', error));
}

/**
 * Load portfolio list for current context
 * Fetches portfolios filtered by divisi, semester, and setting_type
 */
function loadPortfolioList() {
    const params = new URLSearchParams({
        action: 'list',
        divisi: portfolioState.currentDivisi,
        semester: portfolioState.currentSemester,
        setting_type: portfolioState.currentSettingType
    });
    
    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));
}

/**
 * Save portfolio form (create or update)
 * Validates required fields including signature
 * Submits form data to PHP API
 */
function savePortfolio() {
    const traineeSignature = document.getElementById('portfolio-trainee-signature').value;
    
    // Validate traineee signature
    if (!traineeSignature) {
        alert('Mohon tandatangani kolom tanda tangan trainee');
        return;
    }
    
    const portfolioId = portfolioState.currentEditId;
    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: document.getElementById('portfolio-identifikasi').value,
        diagnosis: document.getElementById('portfolio-diagnosis').value,
        tatalaksana: document.getElementById('portfolio-tatalaksana').value,
        kompetenszi: document.getElementById('portfolio-kompetenszi').value,
        supervisor_name: document.getElementById('portfolio-supervisor').value,
        trainee_signature: traineeSignature,
        dpjp_signature: document.getElementById('portfolio-dpjp-signature').value
    };
    
    fetch('php/portfolio.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(portfolioId ? 'Portofolio berhasil diperbarui' : 'Portofolio berhasil disimpan');
                closePortfolioForm();
                loadPortfolioList();
            } else {
                alert('Gagal menyimpan portofolio: ' + data.error);
            }
        })
        .catch(error => {
            console.error('Error saving portfolio:', error);
            alert('Terjadi kesalahan saat menyimpan portofolio');
        });
}

/**
 * Delete portfolio entry
 * Requires user confirmation before deletion
 * 
 * @param {number} portfolioId - ID of portfolio to delete
 */
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 DPJP verification
 * Changes status from 'draft' to 'submitted'
 * Notifies DPJP for review
 */
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');
        });
}

// ============================================================================
// DIGITAL SIGNATURE MANAGEMENT
// ============================================================================

/**
 * Initialize signature canvases
 * Sets up event listeners for drawing on both trainee and DPJP canvases
 * Supports both mouse and touch input
 */
function initializeSignatureCanvases() {
    // Trainee signature setup
    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);
        
        traineeCanvas.addEventListener('touchstart', startDrawingTraineeTouch);
        traineeCanvas.addEventListener('touchmove', drawTraineeTouch);
        traineeCanvas.addEventListener('touchend', stopDrawingTrainee);
    }
    
    // DPJP signature setup
    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);
        
        dpjpCanvas.addEventListener('touchstart', startDrawingDPJPTouch);
        dpjpCanvas.addEventListener('touchmove', drawDPJPTouch);
        dpjpCanvas.addEventListener('touchend', stopDrawingDPJP);
    }
}

/**
 * Start drawing trainee signature (mouse)
 * Records initial position for line drawing
 */
function startDrawingTrainee(e) {
    const rect = portfolioState.traineeSignatureCanvas.getBoundingClientRect();
    portfolioState.lastX = e.clientX - rect.left;
    portfolioState.lastY = e.clientY - rect.top;
    portfolioState.isDrawingTrainee = true;
}

/**
 * Draw on trainee signature canvas (mouse)
 * Draws smooth lines using Bezier curves
 */
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;
    
    // Draw line segment
    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;
}

/**
 * Stop drawing trainee signature
 * Automatically saves to hidden input field
 */
function stopDrawingTrainee() {
    portfolioState.isDrawingTrainee = false;
    saveTraineeSignature();
}

/**
 * Start drawing trainee signature (touch)
 * Touch version of startDrawingTrainee
 */
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;
}

/**
 * Draw on trainee signature canvas (touch)
 * Touch version of drawTrainee with preventDefault
 */
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;
}

/**
 * Clear trainee signature canvas
 * Erases all drawn content
 */
function clearTraineeSignature() {
    if (portfolioState.traineeSignatureCanvas && portfolioState.traineeCtx) {
        portfolioState.traineeCtx.clearRect(0, 0, portfolioState.traineeSignatureCanvas.width, portfolioState.traineeSignatureCanvas.height);
        document.getElementById('portfolio-trainee-signature').value = '';
    }
}

/**
 * Save trainee signature to hidden field
 * Converts canvas to PNG base64 data URL
 */
function saveTraineeSignature() {
    if (portfolioState.traineeSignatureCanvas) {
        const signatureData = portfolioState.traineeSignatureCanvas.toDataURL('image/png');
        document.getElementById('portfolio-trainee-signature').value = signatureData;
    }
}

// DPJP signature functions follow same pattern as trainee
// See code for complete implementation
// startDrawingDPJP, drawDPJP, stopDrawingDPJP, etc.

// ============================================================================
// VIEW MANAGEMENT
// ============================================================================

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

/**
 * Render portfolio list in table
 * Creates HTML table rows from portfolio data
 * 
 * @param {Array} items - Array of portfolio objects
 */
function renderPortfolioList(items) {
    const tbody = document.getElementById('portfolioTableBody');
    
    if (!items || items.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="7" style="text-align: center; padding: 20px; color: #999;">
                    Tidak ada data portofolio. <a href="#" onclick="openPortfolioForm(null); return false;">Tambah yang pertama</a>
                </td>
            </tr>
        `;
        return;
    }
    
    const statusLabels = {
        'draft': 'Draft',
        'submitted': 'Menunggu Verifikasi',
        'verified': 'Terverifikasi'
    };
    
    tbody.innerHTML = items.map(item => `
        <tr>
            <td>${item.nomor}</td>
            <td>${formatDate(item.tanggal)}</td>
            <td>${item.identifikasi_pasien.substring(0, 50)}...</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('');
}

// ============================================================================
// UTILITY FUNCTIONS
// ============================================================================

/**
 * Format date string to Indonesian format
 * 
 * @param {string} dateString - Date string in YYYY-MM-DD format
 * @returns {string} Formatted date (e.g., "25 Februari 2026")
 */
function formatDate(dateString) {
    const options = { year: 'numeric', month: 'long', day: 'numeric' };
    return new Date(dateString).toLocaleDateString('id-ID', options);
}

/**
 * Draw signature from previously saved image
 * Loads base64 image data into canvas
 * 
 * @param {string} canvasId - Canvas element ID
 * @param {string} imageData - Base64 data URL of signature
 */
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);
        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;
}

// ============================================================================
// EVENT LISTENERS
// ============================================================================

/**
 * Initialize form submission handler
 * Attached to portfolioForm on document load
 */
document.addEventListener('DOMContentLoaded', function() {
    const portfolioForm = document.getElementById('portfolioForm');
    if (portfolioForm) {
        portfolioForm.addEventListener('submit', function(e) {
            e.preventDefault();
            savePortfolio();
        });
    }
});

/**
 * Handle ESC key to close portfolio form
 */
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        const modal = document.getElementById('portfolioFormModal');
        if (modal && modal.style.display !== 'none') {
            closePortfolioForm();
        }
    }
});

// ============================================================================
// EXPORT FOR EXTERNAL USE
// ============================================================================

// Functions available for external calls:
// - initializePortfolio(divisi, semester, settingType)
// - openPortfolioForm(portfolioId)
// - closePortfolioForm()
// - loadPortfolioList()
// - savePortfolio()
// - deletePortfolio(id)
// - submitPortfolioForVerification()

