document.addEventListener('DOMContentLoaded', () => {
    // Sidebar Toggle
    const toggleBtn = document.getElementById('sidebarToggle');
    const sidebar = document.getElementById('sidebar');
    
    if (toggleBtn && sidebar) {
        toggleBtn.addEventListener('click', () => {
            sidebar.classList.toggle('closed');
        });
    }

    // Modal Handling
    window.openModal = function(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) modal.classList.add('active');
    }

    window.closeModal = function(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) modal.classList.remove('active');
    }

    // Close modal on outside click
    document.querySelectorAll('.modal-overlay').forEach(overlay => {
        overlay.addEventListener('click', (e) => {
            if (e.target === overlay) {
                overlay.classList.remove('active');
            }
        });
    });

    // Close modal on escape key
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
            document.querySelectorAll('.modal-overlay.active').forEach(modal => {
                modal.classList.remove('active');
            });
        }
    });
});

// Helper to initialize DataTables with Export Buttons
function initDataTable(tableId) {
    if ($.fn.DataTable.isDataTable(tableId)) {
        $(tableId).DataTable().destroy();
    }

    // Cari kolom "Aksi" agar diexclude dari export
    var aksiColIndex = [];
    $(tableId + ' thead th').each(function(i) {
        var text = $(this).text().trim().toLowerCase();
        if (text === 'aksi' || text === 'foto' || text === 'bukti bayar' || text === 'bukti realisasi' || text === 'foto dokumen') {
            aksiColIndex.push(i);
        }
    });

    // Dapatkan judul halaman dari card-title atau page title
    var pageTitle = document.querySelector('.card-title')
        ? document.querySelector('.card-title').textContent.trim()
        : (document.title || 'Data Export');

    $(tableId).DataTable({
        dom: '<"top"Bf>rt<"bottom"lip><"clear">',
        buttons: [
            // ===== EXCEL =====
            {
                extend: 'excelHtml5',
                className: 'btn btn-success',
                text: '<i class="fas fa-file-excel"></i> Excel',
                title: pageTitle + ' - SARPRAS MI MUHAMMADIYAH 27 SURABAYA',
                exportOptions: {
                    columns: function(idx) {
                        return aksiColIndex.indexOf(idx) === -1;
                    },
                    format: {
                        body: function(data, row, column, node) {
                            // Strip HTML tags
                            var stripped = data.replace(/<[^>]*>/g, '').trim();
                            // Deteksi kolom Rp: hapus "Rp", titik pemisah ribuan, dan spasi
                            if (stripped.indexOf('Rp') === 0) {
                                var numStr = stripped.replace(/Rp\s*/g, '').replace(/\./g, '').replace(/,/g, '').trim();
                                var num = parseInt(numStr);
                                return isNaN(num) ? stripped : num;
                            }
                            return stripped;
                        }
                    }
                },
                customize: function(xlsx) {
                    var sheet = xlsx.xl.worksheets['sheet1.xml'];
                    // Style semua cell agar ada border tipis
                    $('row c', sheet).attr('s', '25');
                    // Header row bold
                    $('row:first c', sheet).attr('s', '2');
                }
            },

            // ===== PDF =====
            {
                extend: 'pdfHtml5',
                className: 'btn btn-danger',
                text: '<i class="fas fa-file-pdf"></i> PDF',
                title: pageTitle,
                orientation: 'landscape',
                pageSize: 'A4',
                exportOptions: {
                    columns: function(idx) {
                        return aksiColIndex.indexOf(idx) === -1;
                    },
                    format: {
                        body: function(data, row, column, node) {
                            return data.replace(/<[^>]*>/g, '').trim();
                        }
                    }
                },
                customize: function(doc) {
                    // Header info
                    doc.content.splice(0, 0, {
                        text: 'SARPRAS MI MUHAMMADIYAH 27 SURABAYA',
                        style: 'header',
                        alignment: 'center',
                        margin: [0, 0, 0, 5]
                    });

                    doc.styles.header = {
                        fontSize: 11,
                        bold: true,
                        color: '#333333'
                    };

                    // Title styling
                    doc.styles.title = {
                        fontSize: 10,
                        bold: true,
                        alignment: 'center',
                        margin: [0, 0, 0, 10]
                    };

                    // Page margin A4
                    doc.pageMargins = [20, 20, 20, 30];

                    // Default style
                    doc.defaultStyle = {
                        fontSize: 7,
                        font: 'Roboto'
                    };

                    // Style tabel: garis tipis semua sisi
                    var tableBody = doc.content[doc.content.length - 1];
                    if (tableBody && tableBody.table) {
                        tableBody.layout = {
                            hLineWidth: function() { return 0.3; },
                            vLineWidth: function() { return 0.3; },
                            hLineColor: function() { return '#333333'; },
                            vLineColor: function() { return '#333333'; },
                            paddingLeft: function() { return 3; },
                            paddingRight: function() { return 3; },
                            paddingTop: function() { return 3; },
                            paddingBottom: function() { return 3; }
                        };

                        // Header row: background gelap + teks putih
                        if (tableBody.table.body && tableBody.table.body.length > 0) {
                            tableBody.table.body[0].forEach(function(cell) {
                                cell.fillColor = '#a9a9a9';
                                cell.color = '#000000';
                                cell.bold = true;
                                cell.fontSize = 7;
                                cell.alignment = 'center';
                            });
                        }

                        // Auto width agar muat A4
						//tableBody.table.widths = Array(tableBody.table.body[0].length).fill('auto');
						const colCount = tableBody.table.body[0].length;
						tableBody.table.widths = Array(colCount)
						.fill(0)
						.map((_, i) => i < 3 ? 'auto' : '*');
                    }

                    // Footer halaman
                    doc.footer = function(currentPage, pageCount) {
                        return {
                            columns: [
                                { text: 'Dicetak: ' + new Date().toLocaleDateString('id-ID'), alignment: 'left', fontSize: 7, margin: [20, 0] },
                                { text: 'Halaman ' + currentPage + ' dari ' + pageCount, alignment: 'right', fontSize: 7, margin: [0, 0, 20, 0] }
                            ]
                        };
                    };
                }
            },

            // ===== PRINT =====
            {
                extend: 'print',
                className: 'btn btn-primary',
                text: '<i class="fas fa-print"></i> Print',
                title: '',
                exportOptions: {
                    columns: function(idx) {
                        return aksiColIndex.indexOf(idx) === -1;
                    },
                    format: {
                        body: function(data, row, column, node) {
                            return data.replace(/<[^>]*>/g, '').trim();
                        }
                    }
                },
                customize: function(win) {
                    // Inject CSS untuk print: A4, garis tipis, font kecil
                    $(win.document.body).css({
                        'font-family': "'Inter', 'Segoe UI', Arial, sans-serif",
                        'font-size': '10px',
                        'color': '#333'
                    });

                    // Tambahkan header sekolah
                    $(win.document.body).prepend(
                        '<div style="text-align:center; margin-bottom:15px; border-bottom:2px solid #333; padding-bottom:10px;">' +
                            '<h2 style="margin:0; font-size:16px; font-weight:700;">SARPRAS MI MUHAMMADIYAH 27 SURABAYA</h2>' +
                            '<p style="margin:2px 0 0; font-size:12px; font-weight:600;">' + pageTitle + '</p>' +
                        '</div>'
                    );

                    // Style tabel print: border tipis rapi
                    $(win.document.body).find('table')
                        .css({
                            'width': '100%',
                            'border-collapse': 'collapse',
                            'font-size': '9px',
                            'margin-top': '10px'
                        })
                        .find('th, td')
                        .css({
                            'border': '1px solid #555',
                            'padding': '4px 6px',
                            'text-align': 'left',
                            'vertical-align': 'top'
                        });

                    // Header tabel
                    $(win.document.body).find('table thead th')
                        .css({
                            'background-color': '#4361ee',
                            'color': '#fff',
                            'font-weight': '600',
                            'text-align': 'center',
                            'font-size': '9px'
                        });

                    // Zebra stripe
                    $(win.document.body).find('table tbody tr:nth-child(even)')
                        .css('background-color', '#f8f9fa');

                    // Footer cetak
                    $(win.document.body).append(
                        '<div style="margin-top:15px; display:flex; justify-content:space-between; font-size:9px; color:#666; border-top:1px solid #ccc; padding-top:5px;">' +
                            '<span>Dicetak: ' + new Date().toLocaleDateString('id-ID') + '</span>' +
                        '</div>'
                    );

                    // Print setting: landscape A4
                    var style = win.document.createElement('style');
                    style.textContent = '@page { size: A4 landscape; margin: 10mm; } @media print { body { -webkit-print-color-adjust: exact; print-color-adjust: exact; } }';
                    win.document.head.appendChild(style);
                }
            }
        ],
        language: {
            search: "Cari:",
            lengthMenu: "Tampilkan _MENU_ data",
            info: "Menampilkan _START_ sampai _END_ dari _TOTAL_ data",
            infoEmpty: "Menampilkan 0 sampai 0 dari 0 data",
            infoFiltered: "(disaring dari _MAX_ total data)",
            paginate: {
                first: "Pertama",
                last: "Terakhir",
                next: "Selanjutnya",
                previous: "Sebelumnya"
            }
        },
        pageLength: 50,
        responsive: true
    });
}
