const API_URL = '';

document.addEventListener('DOMContentLoaded', () => {
    // === LOGIN LOGIC ===
    const loginView = document.getElementById('loginView');
    const mainNav = document.getElementById('mainNav');
    const formView = document.getElementById('formView');
    
    const showAdminFormBtn = document.getElementById('showAdminFormBtn');
    const guestLoginBtn = document.getElementById('guestLoginBtn');
    const adminLoginForm = document.getElementById('adminLoginForm');
    const loginOptions = document.querySelector('.login-options');
    
    const adminUsername = document.getElementById('adminUsername');
    const adminPassword = document.getElementById('adminPassword');
    const loginErrorMsg = document.getElementById('loginErrorMsg');
    const cancelAdminBtn = document.getElementById('cancelAdminBtn');
    const doAdminLoginBtn = document.getElementById('doAdminLoginBtn');
    
    const recapBtn = document.querySelector('[data-target="recapView"]');
    const configBtn = document.querySelector('[data-target="configView"]');

    function doLogin(role) {
        loginView.classList.add('hidden');
        mainNav.classList.remove('hidden');
        formView.classList.remove('hidden');
        formView.classList.add('active');
        
        if (role === 'guest') {
            recapBtn.style.display = 'none';
            configBtn.style.display = 'none';
        } else {
            recapBtn.style.display = 'inline-block';
            configBtn.style.display = 'inline-block';
        }
        
        loadFormFields(); // Load forms after login
    }

    guestLoginBtn.addEventListener('click', () => {
        doLogin('guest');
    });

    showAdminFormBtn.addEventListener('click', () => {
        loginOptions.classList.add('hidden');
        adminLoginForm.classList.remove('hidden');
    });

    cancelAdminBtn.addEventListener('click', () => {
        adminLoginForm.classList.add('hidden');
        loginOptions.classList.remove('hidden');
        loginErrorMsg.classList.add('hidden');
    });

    doAdminLoginBtn.addEventListener('click', () => {
        if (adminUsername.value === 'admin' && adminPassword.value === 'admin123') {
            doLogin('admin');
        } else {
            loginErrorMsg.classList.remove('hidden');
        }
    });

    // Handle Enter key for login
    adminPassword.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') doAdminLoginBtn.click();
    });
    // ==================

    // ---- SPA Navigation ----
    const navBtns = document.querySelectorAll('.nav-btn');
    const views = document.querySelectorAll('.view-container');

    navBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            navBtns.forEach(b => b.classList.remove('active'));
            views.forEach(v => v.classList.add('hidden'));
            
            btn.classList.add('active');
            const targetId = btn.getAttribute('data-target');
            document.getElementById(targetId).classList.remove('hidden');

            // Trigger load based on view
            if (targetId === 'formView') loadFormFields();
            if (targetId === 'configView') loadConfigFields();
            if (targetId === 'recapView') loadRecap();
        });
    });

    // Global Data
    let currentFields = [];
    let currentResponses = [];

    // ---- FORM VIEW LOGIC ----
    const formContainer = document.getElementById('dynamicFormFields');
    const attendanceForm = document.getElementById('attendanceForm');
    const formMessage = document.getElementById('formMessage');
    const signaturePads = {};

    async function loadFormFields() {
        try {
            const res = await fetch('/api/fields');
            currentFields = await res.json();
            renderForm(currentFields);
        } catch (e) {
            console.error('Error loading fields for form:', e);
        }
    }

    function renderForm(fields) {
        formContainer.innerHTML = '';
        // Clear previous pads
        Object.keys(signaturePads).forEach(k => delete signaturePads[k]);

        fields.forEach(field => {
            const group = document.createElement('div');
            group.className = 'form-group';
            
            const label = document.createElement('label');
            label.textContent = field.label + (field.is_required ? ' *' : '');
            group.appendChild(label);

            if (field.type === 'text') {
                const input = document.createElement('input');
                input.type = 'text';
                input.className = 'form-control';
                input.name = `field_${field.id}`;
                input.required = !!field.is_required;
                group.appendChild(input);
            } else if (field.type === 'date') {
                const input = document.createElement('input');
                input.type = 'date';
                input.className = 'form-control';
                input.name = `field_${field.id}`;
                input.required = !!field.is_required;
                group.appendChild(input);
            } else if (field.type === 'select') {
                const select = document.createElement('select');
                select.className = 'form-control';
                select.name = `field_${field.id}`;
                select.required = !!field.is_required;
                
                const options = JSON.parse(field.options || '[]');
                options.forEach(opt => {
                    const optionEl = document.createElement('option');
                    optionEl.value = opt.trim();
                    optionEl.textContent = opt.trim();
                    select.appendChild(optionEl);
                });
                group.appendChild(select);
            } else if (field.type === 'signature') {
                const sigContainer = document.createElement('div');
                sigContainer.className = 'signature-container';
                
                const canvas = document.createElement('canvas');
                canvas.className = 'signature-pad';
                canvas.width = 400;
                canvas.height = 150;
                // Add hidden input to store base64 data to bypass native form validation or handle custom
                const hiddenInput = document.createElement('input');
                hiddenInput.type = 'hidden';
                hiddenInput.name = `field_${field.id}`;
                if (field.is_required) hiddenInput.dataset.required = "true";

                const clearBtn = document.createElement('button');
                clearBtn.type = 'button';
                clearBtn.className = 'btn btn-secondary clear-sig-btn';
                clearBtn.textContent = 'Hapus Tanda Tangan';

                sigContainer.appendChild(canvas);
                sigContainer.appendChild(clearBtn);
                group.appendChild(sigContainer);
                group.appendChild(hiddenInput);

                // Setup drawing logic
                setupSignaturePad(canvas, hiddenInput, clearBtn);
                signaturePads[field.id] = canvas;
            }

            formContainer.appendChild(group);
        });
    }

    function setupSignaturePad(canvas, hiddenInput, clearBtn) {
        const ctx = canvas.getContext('2d');
        let isDrawing = false;
        
        ctx.strokeStyle = '#0f172a'; // black for drawing
        ctx.lineWidth = 2;
        ctx.lineJoin = 'round';
        ctx.lineCap = 'round';

        function getPos(e) {
            const rect = canvas.getBoundingClientRect();
            let clientX = e.clientX;
            let clientY = e.clientY;
            if (e.touches && e.touches.length > 0) {
                clientX = e.touches[0].clientX;
                clientY = e.touches[0].clientY;
            }
            return {
                x: clientX - rect.left,
                y: clientY - rect.top
            };
        }

        function start(e) {
            isDrawing = true;
            canvas.classList.add('active-pad');
            canvas.classList.remove('input-error'); // remove error if exists
            const pos = getPos(e);
            ctx.beginPath();
            ctx.moveTo(pos.x, pos.y);
            e.preventDefault();
        }

        function draw(e) {
            if (!isDrawing) return;
            const pos = getPos(e);
            ctx.lineTo(pos.x, pos.y);
            ctx.stroke();
            hiddenInput.value = canvas.toDataURL('image/png');
            e.preventDefault();
        }

        function end(e) {
            isDrawing = false;
            canvas.classList.remove('active-pad');
        }

        canvas.addEventListener('mousedown', start);
        canvas.addEventListener('mousemove', draw);
        canvas.addEventListener('mouseup', end);
        canvas.addEventListener('mouseout', end);

        canvas.addEventListener('touchstart', start);
        canvas.addEventListener('touchmove', draw);
        canvas.addEventListener('touchend', end);

        clearBtn.addEventListener('click', () => {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            hiddenInput.value = '';
        });
    }

    attendanceForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        // Validate signatures visually
        let valid = true;
        attendanceForm.querySelectorAll('input[type="hidden"][data-required="true"]').forEach(input => {
            if (!input.value) {
                valid = false;
                const canvas = input.parentElement.querySelector('canvas');
                canvas.classList.add('input-error');
                setTimeout(() => canvas.classList.remove('input-error'), 400); // animation duration
            }
        });
        
        if (!valid) {
            formMessage.className = 'message error';
            formMessage.textContent = 'Harap lengkapi semua isian yang wajib, termasuk Tanda Tangan!';
            formMessage.classList.remove('hidden');
            return;
        }

        const formData = new FormData(attendanceForm);
        const dataObj = {};
        
        currentFields.forEach(field => {
            const val = formData.get(`field_${field.id}`);
            dataObj[field.label] = val;
        });

        const submitBtn = attendanceForm.querySelector('button[type="submit"]');
        submitBtn.disabled = true;
        submitBtn.querySelector('.btn-text').textContent = 'Mengirim...';

        try {
            const res = await fetch('/api/responses', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ data: dataObj })
            });

            if (res.ok) {
                formMessage.className = 'message success';
                formMessage.textContent = 'Berhasil! Data kehadiran telah disimpan.';
                attendanceForm.reset();
                // clear canvases
                Object.values(signaturePads).forEach(canvas => {
                    canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
                });
                attendanceForm.querySelectorAll('input[type="hidden"]').forEach(inp => inp.value = '');
            } else {
                throw new Error('Gagal');
            }
        } catch (error) {
            formMessage.className = 'message error';
            formMessage.textContent = 'Gagal menyimpan data. Silakan coba lagi.';
        } finally {
            submitBtn.disabled = false;
            submitBtn.querySelector('.btn-text').textContent = 'Kirim Absensi';
            formMessage.classList.remove('hidden');
            setTimeout(() => { formMessage.classList.add('hidden'); }, 3000);
        }
    });


    // ---- CONFIG VIEW LOGIC ----
    const fieldsList = document.getElementById('fieldsList');
    const editType = document.getElementById('editType');
    const optionsGroup = document.getElementById('optionsGroup');
    const addFieldBtn = document.getElementById('addFieldBtn');
    const fieldEditorForm = document.getElementById('fieldEditorForm');
    const saveFieldBtn = document.getElementById('saveFieldBtn');
    const cancelFieldBtn = document.getElementById('cancelFieldBtn');
    
    let editingFieldId = null;

    editType.addEventListener('change', () => {
        if (editType.value === 'select') {
            optionsGroup.classList.remove('hidden');
        } else {
            optionsGroup.classList.add('hidden');
        }
    });

    async function loadConfigFields() {
        try {
            const res = await fetch('/api/fields');
            currentFields = await res.json();
            renderConfigFields(currentFields);
        } catch (e) {
            console.error('Error loading config fields:', e);
        }
    }

    function renderConfigFields(fields) {
        fieldsList.innerHTML = '';
        fields.forEach((field, index) => {
            const item = document.createElement('div');
            item.className = 'field-item';
            
            const info = document.createElement('div');
            info.className = 'field-info';
            
            let typeText = field.type;
            if (typeText === 'text') typeText = 'Teks Pendek';
            if (typeText === 'date') typeText = 'Tanggal';
            if (typeText === 'select') typeText = 'Pilihan Ganda';
            if (typeText === 'signature') typeText = 'Tanda Tangan';

            info.innerHTML = `
                <strong>${field.label} ${field.is_required ? '<span style="color:red">*</span>' : ''}</strong>
                <span>Tipe: ${typeText} | Urutan: ${field.order_index}</span>
            `;
            
            const actions = document.createElement('div');
            actions.className = 'actions';
            
            if (index > 0) {
                const btnUp = document.createElement('button');
                btnUp.className = 'btn-icon';
                btnUp.innerHTML = '⬆️';
                btnUp.title = 'Naik';
                btnUp.onclick = () => swapOrder(index, index - 1);
                actions.appendChild(btnUp);
            }
            if (index < fields.length - 1) {
                const btnDown = document.createElement('button');
                btnDown.className = 'btn-icon';
                btnDown.innerHTML = '⬇️';
                btnDown.title = 'Turun';
                btnDown.onclick = () => swapOrder(index, index + 1);
                actions.appendChild(btnDown);
            }

            const btnEdit = document.createElement('button');
            btnEdit.className = 'btn-icon';
            btnEdit.innerHTML = '✏️';
            btnEdit.title = 'Edit';
            btnEdit.onclick = () => editField(field);
            actions.appendChild(btnEdit);

            const btnDel = document.createElement('button');
            btnDel.className = 'btn-icon';
            btnDel.innerHTML = '🗑️';
            btnDel.title = 'Hapus';
            btnDel.onclick = () => deleteField(field.id);
            actions.appendChild(btnDel);
            
            item.appendChild(info);
            item.appendChild(actions);
            fieldsList.appendChild(item);
        });
    }

    async function swapOrder(idx1, idx2) {
        const f1 = currentFields[idx1];
        const f2 = currentFields[idx2];
        const tempOrder = f1.order_index;
        f1.order_index = f2.order_index;
        f2.order_index = tempOrder;

        try {
            await Promise.all([
                fetch(`/api/fields/${f1.id}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(f1)
                }),
                fetch(`/api/fields/${f2.id}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(f2)
                })
            ]);
            loadConfigFields();
        } catch (e) {
            alert('Gagal mengubah urutan');
            loadConfigFields();
        }
    }

    function editField(field) {
        editingFieldId = field.id;
        document.getElementById('editLabel').value = field.label;
        document.getElementById('editType').value = field.type;
        document.getElementById('editOptions').value = field.options ? JSON.parse(field.options).join(', ') : '';
        document.getElementById('editRequired').checked = !!field.is_required;
        
        if (field.type === 'select') optionsGroup.classList.remove('hidden');
        else optionsGroup.classList.add('hidden');
        
        saveFieldBtn.textContent = 'Simpan Perubahan';
        fieldEditorForm.classList.remove('hidden');
        addFieldBtn.classList.add('hidden');
    }

    addFieldBtn.addEventListener('click', () => {
        editingFieldId = null;
        document.getElementById('editLabel').value = '';
        document.getElementById('editType').value = 'text';
        document.getElementById('editOptions').value = '';
        document.getElementById('editRequired').checked = true;
        optionsGroup.classList.add('hidden');
        
        saveFieldBtn.textContent = 'Simpan Kolom';
        fieldEditorForm.classList.remove('hidden');
        addFieldBtn.classList.add('hidden');
    });

    cancelFieldBtn.addEventListener('click', () => {
        fieldEditorForm.classList.add('hidden');
        addFieldBtn.classList.remove('hidden');
    });

    saveFieldBtn.addEventListener('click', async () => {
        const label = document.getElementById('editLabel').value.trim();
        const type = document.getElementById('editType').value;
        const optionsRaw = document.getElementById('editOptions').value;
        const is_required = document.getElementById('editRequired').checked;

        if (!label) {
            const el = document.getElementById('editLabel');
            el.classList.add('input-error');
            setTimeout(() => el.classList.remove('input-error'), 400);
            return;
        }
        
        let options = null;
        if (type === 'select') {
            options = optionsRaw.split(',').map(s => s.trim()).filter(s => s);
            if (options.length === 0) return alert('Minimal isi 1 pilihan opsi');
        }

        const payload = { label, type, options, is_required, order_index: currentFields.length + 1 };

        if (editingFieldId) {
            const existingField = currentFields.find(f => f.id === editingFieldId);
            payload.order_index = existingField.order_index;
            try {
                await fetch(`/api/fields/${editingFieldId}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                });
                fieldEditorForm.classList.add('hidden');
                addFieldBtn.classList.remove('hidden');
                loadConfigFields(); // refresh
            } catch (e) {
                alert('Gagal menyimpan perubahan');
            }
        } else {
            try {
                await fetch('/api/fields', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                });
                fieldEditorForm.classList.add('hidden');
                addFieldBtn.classList.remove('hidden');
                loadConfigFields(); // refresh
            } catch (e) {
                alert('Gagal menyimpan');
            }
        }
    });

    async function deleteField(id) {
        if (!confirm('Yakin ingin menghapus kolom ini? (Data yang sudah ada mungkin tidak selaras)')) return;
        try {
            await fetch(`/api/fields/${id}`, { method: 'DELETE' });
            loadConfigFields();
        } catch (e) {
            alert('Gagal menghapus');
        }
    }


    // ---- RECAP VIEW LOGIC ----
    const recapThead = document.getElementById('recapThead');
    const recapTbody = document.getElementById('recapTbody');
    const searchInput = document.getElementById('searchInput');

    async function loadRecap() {
        recapThead.innerHTML = '<tr><th>Loading...</th></tr>';
        recapTbody.innerHTML = '';
        searchInput.value = '';
        try {
            const [fieldsRes, respRes] = await Promise.all([
                fetch('/api/fields'),
                fetch('/api/responses')
            ]);
            
            currentFields = await fieldsRes.json();
            let rawResponses = await respRes.json();
            
            // Parse stringified JSON from database
            currentResponses = rawResponses.map(r => {
                if (typeof r.data === 'string') {
                    try { r.data = JSON.parse(r.data); } catch(e) {}
                }
                return r;
            });
            
            renderRecapTable(currentFields, currentResponses);
        } catch (e) {
            console.error('Error loading recap:', e);
            recapThead.innerHTML = '<tr><th>Gagal memuat data</th></tr>';
        }
    }

    function formatDateId(dateString) {
        const dateObj = new Date(dateString);
        return new Intl.DateTimeFormat('id-ID', {
            day: '2-digit',
            month: 'long',
            year: 'numeric'
        }).format(dateObj);
    }

    function renderRecapTable(fields, responsesToRender) {
        // Build Header
        let headHTML = '<tr><th style="width:40px; text-align:center;"><input type="checkbox" id="selectAllCb"></th><th>Tanggal</th>';
        fields.forEach(f => {
            headHTML += `<th>${f.label}</th>`;
        });
        headHTML += '</tr>';
        recapThead.innerHTML = headHTML;

        // Build Body
        recapTbody.innerHTML = '';
        if (responsesToRender.length === 0) {
            recapTbody.innerHTML = `<tr><td colspan="${fields.length + 2}">Belum ada data</td></tr>`;
            updateBulkDeleteBtn();
            return;
        }

        responsesToRender.forEach(resp => {
            const tr = document.createElement('tr');
            
            const timeStr = formatDateId(resp.created_at);
            
            let rowHTML = `<td style="text-align:center;"><input type="checkbox" class="row-checkbox" value="${resp.id}"></td><td>${timeStr}</td>`;
            const dataObj = resp.data || {};
            
            fields.forEach(f => {
                let val = dataObj[f.label] || '-';
                if (f.type === 'signature' && val !== '-' && val.startsWith('data:image')) {
                    val = `<img src="${val}" class="sig-thumb" alt="Tanda Tangan" onclick="window.open('${val}')" title="Klik untuk memperbesar">`;
                }
                rowHTML += `<td>${val}</td>`;
            });

            tr.innerHTML = rowHTML;
            recapTbody.appendChild(tr);
        });

        // Event Listeners for Checkboxes
        const selectAllCb = document.getElementById('selectAllCb');
        const rowCbs = document.querySelectorAll('.row-checkbox');
        
        selectAllCb.addEventListener('change', (e) => {
            rowCbs.forEach(cb => cb.checked = e.target.checked);
            updateBulkDeleteBtn();
        });

        rowCbs.forEach(cb => {
            cb.addEventListener('change', () => {
                const allChecked = Array.from(rowCbs).every(c => c.checked);
                selectAllCb.checked = allChecked;
                updateBulkDeleteBtn();
            });
        });

        updateBulkDeleteBtn();
    }

    function updateBulkDeleteBtn() {
        const btn = document.getElementById('bulkDeleteBtn');
        const checkedCount = document.querySelectorAll('.row-checkbox:checked').length;
        if (checkedCount > 0) {
            btn.textContent = `Hapus Terpilih (${checkedCount})`;
            btn.classList.remove('hidden');
        } else {
            btn.classList.add('hidden');
        }
    }

    document.getElementById('bulkDeleteBtn').addEventListener('click', async () => {
        const selectedIds = Array.from(document.querySelectorAll('.row-checkbox:checked')).map(cb => Number(cb.value));
        if (selectedIds.length === 0) return;
        
        if (!confirm(`Yakin ingin menghapus ${selectedIds.length} data terpilih secara permanen?`)) return;

        const btn = document.getElementById('bulkDeleteBtn');
        const originalText = btn.textContent;
        btn.textContent = 'Menghapus...';
        btn.disabled = true;

        try {
            await fetch('/api/responses/bulk', {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ ids: selectedIds })
            });
            loadRecap();
        } catch (e) {
            alert('Gagal menghapus data');
        } finally {
            btn.disabled = false;
            btn.textContent = originalText;
        }
    });

    // Filter Logic
    searchInput.addEventListener('input', () => {
        const query = searchInput.value.toLowerCase();
        if (!query) {
            renderRecapTable(currentFields, currentResponses);
            return;
        }
        
        const filtered = currentResponses.filter(resp => {
            // Search inside the JSON data
            const data = resp.data || {};
            return Object.values(data).some(val => 
                String(val).toLowerCase().includes(query) && !String(val).startsWith('data:image')
            );
        });
        renderRecapTable(currentFields, filtered);
    });

    // EXPORT MODAL LOGIC
    const exportModal = document.getElementById('exportModal');
    let currentExportType = '';

    document.getElementById('exportExcelBtn').addEventListener('click', () => {
        if (!currentResponses.length) return alert('Tidak ada data untuk di-export.');
        currentExportType = 'excel';
        exportModal.classList.remove('hidden');
    });

    document.getElementById('exportPdfBtn').addEventListener('click', () => {
        if (!currentResponses.length) return alert('Tidak ada data untuk di-export.');
        currentExportType = 'pdf';
        exportModal.classList.remove('hidden');
    });

    document.getElementById('cancelExportBtn').addEventListener('click', () => {
        exportModal.classList.add('hidden');
    });

    document.getElementById('confirmExportBtn').addEventListener('click', () => {
        exportModal.classList.add('hidden');
        
        const kopData = {
            agenda: document.getElementById('expAgenda').value,
            tanggal: document.getElementById('expTanggal').value,
            notulis: document.getElementById('expNotulis').value,
            tempat: document.getElementById('expTempat').value,
            peserta: document.getElementById('expPeserta').value,
            dikirim: document.getElementById('expDikirim').value
        };

        if (currentExportType === 'excel') {
            exportToExcel(kopData);
        } else if (currentExportType === 'pdf') {
            exportToPdf(kopData);
        }
    });

    function getTargetResponses() {
        const selectedIds = Array.from(document.querySelectorAll('.row-checkbox:checked')).map(cb => Number(cb.value));
        return selectedIds.length > 0 ? currentResponses.filter(r => selectedIds.includes(r.id)) : currentResponses;
    }

    // EXPORT TO EXCEL
    function exportToExcel(kopData) {
        const targetData = getTargetResponses();
        
        // Prepare main data
        const exportData = targetData.map(resp => {
            const row = { "Tanggal": formatDateId(resp.created_at) };
            const dataObj = resp.data || {};
            currentFields.forEach(f => {
                let val = dataObj[f.label] || '-';
                if (f.type === 'signature') val = val.startsWith('data:image') ? '[Tanda Tangan Tersimpan]' : '-';
                row[f.label] = val;
            });
            return row;
        });

        // Create Worksheet
        const worksheet = XLSX.utils.json_to_sheet([]);
        
        // Add Kop Surat manually
        XLSX.utils.sheet_add_aoa(worksheet, [
            ["NOTULEN RAPAT"],
            [],
            [`Agenda: ${kopData.agenda}`, `Tanggal :\n${kopData.tanggal}`, "Disusun", ""],
            ["", "", `Oleh :`, `${kopData.notulis}`],
            ["", `Tempat : ${kopData.tempat}`, "", ""],
            [`Peserta Rapat : ${kopData.peserta}`, `Notulen rapat ini dikirim kepada :\n${kopData.dikirim}`, "", ""],
            [],
            ["Daftar Hadir"]
        ], { origin: "A1" });

        // Merge cells for Kop Surat
        worksheet['!merges'] = [
            { s: { r: 0, c: 0 }, e: { r: 0, c: 5 } }, // NOTULEN RAPAT
            { s: { r: 2, c: 0 }, e: { r: 4, c: 0 } }, // Agenda
            { s: { r: 2, c: 1 }, e: { r: 3, c: 1 } }, // Tanggal
            { s: { r: 2, c: 2 }, e: { r: 2, c: 3 } }, // Disusun
            { s: { r: 4, c: 1 }, e: { r: 4, c: 3 } }, // Tempat
            { s: { r: 5, c: 1 }, e: { r: 5, c: 3 } }, // Dikirim Kepada
            { s: { r: 7, c: 0 }, e: { r: 7, c: 5 } }  // Daftar Hadir
        ];

        // Append Data after Kop Surat (starting row 10 / index 9)
        XLSX.utils.sheet_add_json(worksheet, exportData, { origin: "A10" });

        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, "Rekap Absensi");
        XLSX.writeFile(workbook, "Rekap_Absensi_Notulen.xlsx");
    }

    // EXPORT TO PDF
    function exportToPdf(kopData) {
        const targetData = getTargetResponses();
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF('portrait');
        
        // Add Header Title
        doc.setFontSize(14);
        doc.setTextColor(0, 0, 0);
        doc.setFont("helvetica", "bold");
        doc.text('NOTULEN RAPAT', 105, 30, { align: 'center' });

        // Add Kop Surat Table
        doc.autoTable({
            startY: 35,
            theme: 'grid',
            styles: { fontSize: 10, textColor: [0,0,0], lineColor: [0,0,0], lineWidth: 0.1, valign: 'middle' },
            body: [
                [{ content: `Agenda: ${kopData.agenda}`, rowSpan: 3, styles: { cellWidth: 85 } },
                 { content: `Tanggal :\n${kopData.tanggal}`, rowSpan: 2 },
                 { content: `Disusun`, colSpan: 2, styles: { halign: 'center' } }
                ],
                [{ content: `Oleh :`, styles: { halign: 'center', cellWidth: 20 } },
                 { content: `${kopData.notulis}` }
                ],
                [{ content: `Tempat : ${kopData.tempat}`, colSpan: 3 }
                ],
                [{ content: `Peserta Rapat : ${kopData.peserta}` },
                 { content: `Notulen rapat ini dikirim kepada :\n${kopData.dikirim}`, colSpan: 3 }
                ]
            ]
        });

        // Prepare Main Data
        let finalY = doc.lastAutoTable.finalY;
        
        // Add "Daftar Hadir" subtitle
        doc.setFontSize(12);
        doc.setFont("helvetica", "bold");
        doc.text('Daftar Hadir', 14, finalY + 10);

        const head = [['Tanggal', ...currentFields.map(f => f.label)]];
        const body = [];
        const signatureCells = []; 

        targetData.forEach((resp, rowIndex) => {
            const timeStr = formatDateId(resp.created_at);
            const row = [timeStr];
            const dataObj = resp.data || {};
            
            currentFields.forEach((f, colIndex) => {
                let val = dataObj[f.label] || '-';
                if (f.type === 'signature' && val.startsWith('data:image')) {
                    signatureCells.push({ row: rowIndex, col: colIndex + 1, imgData: val });
                    row.push(''); 
                } else {
                    row.push(val);
                }
            });
            body.push(row);
        });

        // Draw Main Data Table
        doc.autoTable({
            head: head,
            body: body,
            startY: finalY + 14,
            theme: 'plain',
            styles: { 
                valign: 'middle', 
                cellPadding: 1.5
            },
            headStyles: { 
                fillColor: [59, 130, 246],
                textColor: [255, 255, 255],
                fontStyle: 'bold'
            },
            bodyStyles: {
                lineColor: [0, 0, 0],
                lineWidth: 0.1,
                minCellHeight: 10 
            },
            didDrawCell: function(data) {
                if (data.section === 'body') {
                    const match = signatureCells.find(c => c.row === data.row.index && c.col === data.column.index);
                    if (match) {
                        try {
                            const pad = 2;
                            const cellW = data.cell.width;
                            const cellH = data.cell.height;
                            
                            // Proporsional ratio (not too wide)
                            let imgH = cellH - (pad * 2);
                            let imgW = imgH * 1.8;
                            
                            // If it's too wide for the cell, scale it down
                            if (imgW > cellW - (pad * 2)) {
                                imgW = cellW - (pad * 2);
                                imgH = imgW / 1.8;
                            }
                            
                            // Center in cell
                            const offsetX = (cellW - imgW) / 2;
                            const offsetY = (cellH - imgH) / 2;

                            doc.addImage(match.imgData, 'PNG', data.cell.x + offsetX, data.cell.y + offsetY, imgW, imgH);
                        } catch (e) {
                            console.error('Error drawing image in PDF', e);
                        }
                    }
                }
            }
        });

        doc.save("Rekap_Absensi_Notulen.pdf");
    }

    // Initial load
    loadFormFields();
});
