document.addEventListener('DOMContentLoaded', function() {
  // Variables to hold interval IDs
  let intervalFun;
    let intervalFun2;

    // Function Definitions

    function runInterval() {
    intervalFun = setInterval(qrcodeRequest, 5000);
}

function stopInterval() {
    clearInterval(intervalFun);
}

    function runInterval2() {
        qrcodeRequest2();
        intervalFun2 = setInterval(qrcodeRequest2, 5000);
    }

    function stopInterval2() {
        clearInterval(intervalFun2);
        document.getElementById("qrcode2").classList.remove("d-block");
        document.getElementById("qrcode2").classList.add("d-none");
        document.getElementById("spinner2").classList.remove("d-none");
    }

    // Define addPhoneRequest function
    function addPhoneRequest() {
        var whatsapp_phone = $('#whatsapp_phone').val();  // Get the phone value from input
        var tokenAuth = $("#myToken").val();  // Get the token value

        console.log("request sent");  // <-- Added this line

        $.ajax({
            url: "{{ route('whatsapp.phone') }}",
            method: "post",
            data: {
                phone: whatsapp_phone,  // Pass the phone number correctly
                token: tokenAuth  // Add the token to the request data
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(data) {
                if (data.success == true) {
                    $("#whatsapp_phone_error").addClass("d-none");
                    document.getElementById("spinner").classList.remove("d-none");
                    document.getElementById("whatsapp_phone_form").classList.add("d-none");
                    $("#qrcode_phone").val(data.phone);
                    runInterval();
                } else {
                    $("#whatsapp_phone_error").removeClass("d-none");
                    $("#whatsapp_phone_error").html(data.message);
                }
            }
        });
    }

    // Define qrcodeRequest function
    function qrcodeRequest() {
        var phone = $("#qrcode_phone").val();
        var myToken = $("#myToken").val();

        console.log("request sent");  // <-- Added this line

        $.ajax({
            method: "get",
            url: "{{ route('whatsapp.qrcode') }}",
            data: {
                phone: phone,
                token: myToken
            },
            success: function(data) {
                if (data.status == 'success') {
                    if (data.qrcode.startsWith('data')) {
                        document.getElementById("qrcode").classList.remove("d-none");
                        document.getElementById("qrcode").classList.add("d-block");
                        document.getElementById("spinner").classList.add("d-none");
                        document.getElementById("qrcode").src = data.qrcode;
                    }
                }
                if (data.status == 'connected') {
                    console.log("request sent");  // <-- Added this line
                    $.ajax({
                        method: "put",
                        url: "{{ route('whatsapp.session.status') }}",
                        data: {
                            status: "connected",
                            phone: phone,
                            token: myToken  
                        },
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success: function(data) {
                            location.reload();
                        }
                    });
                }
            }
        });
    }

    // Define qrcodeRequest2 function
    function qrcodeRequest2() {
        var defCheckbox = document.getElementById('defCheckbox').checked;
        var selectedCheckbox = document.querySelector('.row-checkbox:checked');

        if (!selectedCheckbox) {
            document.getElementById("error_phone").classList.remove("d-none");
            clearInterval(intervalFun2);
            return;
        }

        document.getElementById("error_phone").classList.add("d-none");
        var row = selectedCheckbox.closest('tr');
        var phone = row.cells[2].textContent.trim();
        var myToken = $("#myToken").val();

        console.log("request sent");  // <-- Added this line

        $.ajax({
            method: "get",
            url: "{{ route('whatsapp.qrcode') }}",
            data: {
                phone: phone,
                default_phone: defCheckbox,
                token: myToken
            },
            success: function(data) {
                if (data.status == 'success') {
                    if (data.qrcode.startsWith('data')) {
                        document.getElementById("qrcode2").classList.remove("d-none");
                        document.getElementById("qrcode2").classList.add("d-block");
                        document.getElementById("spinner2").classList.add("d-none");
                        document.getElementById("qrcode2").src = data.qrcode;
                    }
                }
                if (data.status == 'connected') {
                    console.log("request sent");  // <-- Added this line
                    $.ajax({
                        method: "put",
                        url: "{{ route('whatsapp.session.status') }}",
                        data: {
                            status: "connected",
                            phone: phone,
                            token: myToken  
                        },
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success: function(data) {
                            location.reload();
                        }
                    });
                }
            }
        });
    }

    // Event Listeners

    document.getElementById('addPhoneButton').addEventListener('click', function() {
        addPhoneRequest();
    });

    document.getElementById('runInterval2Button').addEventListener('click', function() {
        runInterval2();
    });

    document.getElementById('stopIntervalButton').addEventListener('click', function() {
        stopInterval();
    });

    document.getElementById('stopInterval2Button').addEventListener('click', function() {
        stopInterval2();
    });
            const selectedPhones = new Set();
            const deleteBtn = document.getElementById('delbtn');
            const selectAllCheckbox = document.getElementById('selectAllCheckbox');
            const checkboxes = document.querySelectorAll('.row-checkbox');
            const deleteConfirmationModal = document.getElementById('deleteConfirmationModal');
            const closeDeleteModalElements = deleteConfirmationModal.querySelectorAll('.close, #cancelDelete');
            const confirmDeleteButton = document.getElementById('confirmDelete');

            /**
             * دالة لإظهار المودال
             * @param {HTMLElement} modal - عنصر المودال المراد إظهاره
             */
            function showModal(modal) {
                modal.style.display = 'block';
                document.body.classList.add('modal-open');
            }

            /**
             * دالة لإخفاء المودال
             * @param {HTMLElement} modal - عنصر المودال المراد إخفاءه
             */
            function hideModal(modal) {
                modal.style.display = 'none';
                document.body.classList.remove('modal-open');
            }

         
            function setupDeleteModal() {
                closeDeleteModalElements.forEach(element => {
                    element.addEventListener('click', () => hideModal(deleteConfirmationModal));
                });

                confirmDeleteButton.addEventListener('click', () => {
                    hideModal(deleteConfirmationModal);
                    deleteSelectedRows();
                });

                deleteBtn.addEventListener('click', function(event) {
                    event.preventDefault(); // منع السلوك الافتراضي للنقر
                    if (selectedPhones.size === 0) {
                        alert('يرجى تحديد جلسات للحذف.');
                        return;
                    }
                    showModal(deleteConfirmationModal);
                });
            }

        
            function deleteSelectedRows() {
                const phonesArray = Array.from(selectedPhones);

                fetch('/delete-sessions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify({phones: phonesArray})
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        phonesArray.forEach(phone => {
                            const rows = document.querySelectorAll('tr');
                            for (let row of rows) {
                                if (row.cells[2] && row.cells[2].textContent.trim() === phone) {
                                    row.remove();
                                    break;
                                }
                            }
                        });
                        selectedPhones.clear();
                        deleteBtn.disabled = true;
                        checkboxes.forEach(checkbox => {
                            checkbox.checked = false;
                        });
                        alert('تم حذف الجلسات المحددة بنجاح.');
                    } else {
                        window.location.reload();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    window.location.reload();
                });
            }

         
            function setupCheckboxes() {
                selectAllCheckbox.addEventListener('change', function() {
                    checkboxes.forEach(checkbox => {
                        checkbox.checked = this.checked;
                        const row = checkbox.closest('tr');
                        const phone = row.cells[2].textContent.trim();
                        if (checkbox.checked) {
                            selectedPhones.add(phone);
                        } else {
                            selectedPhones.delete(phone);
                        }
                    });
                    deleteBtn.disabled = selectedPhones.size === 0;
                });

                checkboxes.forEach(checkbox => {
                    checkbox.addEventListener('change', function() {
                        const row = this.closest('tr');
                        const phone = row.cells[2].textContent.trim();
                        if (this.checked) {
                            selectedPhones.add(phone);
                        } else {
                            selectedPhones.delete(phone);
                        }
                        const allChecked = Array.from(checkboxes).every(cb => cb.checked);
                        selectAllCheckbox.checked = allChecked;
                        deleteBtn.disabled = selectedPhones.size === 0;
                    });
                });
            }

            setupCheckboxes();
            setupDeleteModal();
        });

        $(document).ready(function() {
          $("#table").DataTable({
            pagingType: "full_numbers",
            scrollX: true,
            autoWidth: false,
          });
        }); request is not getting send and elemebt Uncaught TypeError: document.getElementById(...) is null
    <anonymous> http://127.0.0.1:8000/sessionss:660
    EventListener.handleEvent* http://127.0.0.1:8000/sessionss:497
sessionss:660:14
    <anonymous> http://127.0.0.1:8000/sessionss:660
    (Async: EventListener.handleEvent)
    <anonymous> http://127.0.0.1:8000/sessionss:497