$(document).ready(function() {
    var emailQueueReport;
    // Function to initialize and fill the WhatsApp data table
    function fill_datatables_email_report(startdatetime ='',enddatetime ='',I_Status ='',from_email ='',to_email = '') {
        var startdatetime = $('#startdatetime').val();
        var enddatetime = $('#enddatetime').val();
      
    emailQueueReport = $('#email_queue_report').DataTable({
        "processing": true,
        "serverSide": true,
        "order": [],
        "pageLength": 10, // Default records per page
        "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
        "searching": false,
        "paging": true, // Ensure paging is enabled
        "dom": "lBfrtip", // "p" ensures pagination is included in the layout
            "buttons": [
                {
                    extend: 'csvHtml5',
                    text: '<i class="fa fa-file-excel-o"></i>',
                    titleAttr: 'CSV',
                    filename: 'csv',
                    title: $('.download_label').html(),
                    exportOptions: {
                        columns: ':visible'
                    }
                },{
                    extend: 'excelHtml5',
                    text: '<i class="fa fa-file-excel-o"></i>',
                    titleAttr: 'Excel',
                    filename: 'Excel',
                    title: $('.download_label').html(),
                    exportOptions: {
                        columns: ':visible'
                    }
                },{
                        extend: 'pdfHtml5',
                        filename : $('.report_name').text(),
                        messageTop : $('.download_label').html(),
                        orientation: 'landscape',
                        pageSize: 'A3',
                        text: '<i class="fa fa-file-pdf-o"></i>',
                        titleAttr: 'PDF',
                        // changed logo code [vastvikta][05-05-2025]
                    customize: function ( doc ) {
                            
                            var logoBase64 = document.getElementById('pdf-logo-base64').innerText;
                            doc.images = doc.images || {};
                            doc.images.logo = logoBase64;
                        
                        doc.content.splice( 1, 0, {
                            margin: [ 0, 0, 0, 5 ],
                                alignment: 'left',
                                image: 'logo', 
                                 width: 250
                            } );
                        },
                        title: '.',
                        exportOptions: {
                            columns: ':visible'
                            
                        }
                    },{
                    extend: 'colvis',
                    text: '<i class="fa fa-columns"></i>',
                    titleAttr: 'Columns',
                    title: $('.download_label').html(),
                    postfixButtons: ['colvisRestore']
                },
            ],
        "ajax": {
            url: "Report/report_function.php",
            type: "POST",
            data: function(d) {
                d.startdatetime = $('#startdatetime').val();
                d.enddatetime = $('#enddatetime').val();
                d.from_email = $('#from_email').val();
                d.to_email = $('#to_email').val();
                d.I_Status = $('#I_Status').val();
                d.action = 'email_queue_report';
            }
        }
    });
    }

    // Initialize WhatsApp report table
    fill_datatables_email_report();

    // Set an interval to refresh the table every 10 seconds
    setInterval(function() {
        emailQueueReport.ajax.reload(null, false); // Reload data without resetting pagination
    }, 20000);

    // Submit form and reload data based on new filters
    $('#email_report_form').submit(function(e) {
        e.preventDefault();

        $('#email_queue_report').DataTable().destroy();
        var startdatetime = $('#startdatetime').val();
        var enddatetime = $('#enddatetime').val();
        var I_Status = $('#I_Status').val();
        var from_email = $('#from_email').val();
        var to_email = $('#to_email').val();
        fill_datatables_email_report(startdatetime,enddatetime,I_Status,from_email,to_email);// Refresh the table with the new filter parameters
    });

    // Reset button functionality
    $('.reset_email_report').click(function () { 
        // Destroy the existing DataTable
        emailQueueReport.destroy();
        // Get the current date and time
        var currentDate = new Date();
        // Format the first day of the current month as '01-mm-yyyy 00:00:00'
        var startOfMonth = '01-' + ('0' + (currentDate.getMonth() + 1)).slice(-2) + '-' + currentDate.getFullYear() + ' 00:00:00';

        // Format the current date as 'dd-mm-yyyy 23:59:59'
        var formattedEndDate = ('0' + currentDate.getDate()).slice(-2) + '-' +
                            ('0' + (currentDate.getMonth() + 1)).slice(-2) + '-' +
                            currentDate.getFullYear() + ' 23:59:59';
        // Reset the form fields
        $('#startdatetime').val(startOfMonth);
        $('#enddatetime').val(formattedEndDate);
        $('#I_Status').val('');
        $('#from_email').val('');
        $('#to_email').val('');
        
        // Reinitialize the table with default filters
        fill_datatables_email_report(); // Ensure this function initializes the table correctly
    });
});

// Handle "Select All" checkbox
$('#select-all').on('click', function () {
    const isChecked = $(this).prop('checked');
    $('.row-checkbox').prop('checked', isChecked);
});

// Collect selected row IDs
function getSelectedRowIds() {
    const selectedIds = [];
    $('.row-checkbox:checked').each(function () {
        selectedIds.push($(this).data('id'));
    });
    return selectedIds;
}

// Handle bulk actions
$('#bulk-reschedule').on('click', function () {
    const selectedIds = getSelectedRowIds();
    if (selectedIds.length === 0) {
        alert('No rows selected!');
        return;
    }
    // Open reschedule popup and pass selected IDs
    $('#reschedule-popup').fadeIn();
    $('#bulk-data-ids').val(selectedIds.join(','));
});

// Reschedule Selected
$('#confirm-reschedule').on('click', function () {
    const selectedIds = $('#bulk-data-ids').val();
    const rescheduleDate = $('#reschedule-date').val();
    if (selectedIds.length === 0) {
        alert('Please select at least one Email to reschedule.');
        return;
    }
    $.ajax({
        url: 'Report/reschedule.php',
        type: 'POST',
        data: {
            ids: selectedIds.split(','),
            DateNew: rescheduleDate,
            action: 'email_reschedule'
        },
        success: function(response) {
           alert('Rescheduling successful!');
            $('#reschedule-popup').fadeOut();
            window.location.reload();
        },
        error: function(xhr) {
            alert('Error rescheduling Email.');
        }
    });
});
document.getElementById('cancel-reschedule').addEventListener('click', function () {
    document.getElementById('reschedule-popup').style.display = 'none';
});
// Expire Selected
$('#expire_selected').on('click', function() {
    const selectedIds = getSelectedRowIds();
    if (selectedIds.length === 0) {
        alert('Please select at least one Email to expire.');
        return;
    }
    // Show confirmation dialog
    const confirmation = confirm('Are you sure you want to mark the selected Email as expired?');
    if (!confirmation) {
        return; // Exit if the user cancels
    }
    $.ajax({
        url: 'Report/reschedule.php',
        type: 'POST',
        data: {
            ids:selectedIds,
            action: 'email_expire'
        },
        success: function(response) {
            alert('Email marked as expired.');
            // window.location.reload();
        },
        error: function(xhr) {
            alert('Error expiring Email.');
        }
    });
});