let socket_id = "{{md5(Str::random(40))}}";
    let node_url = "http://41.33.3.35:4433";
    let engines = ['Google','Bing','Duck'];
    let social = ['Telegram','Twitter','Instagram'];
    let socialId = [1,6];
    let enginesId = [3,4,5];
    let viewbtn = document.getElementById('viewbtn')
    let table =document.getElementById('latestSearches');

  

    
    $(document).ready(function () {
      viewbtns =document.querySelectorAll('viewbtn')


      $(document).on('click', '.viewbtn', function(){
        let $row = $(this).closest('tr');
    let cellValue = $row.find('td').eq(3).text().trim();
    console.log(cellValue);
    fetch('/view-page', {
        method:'post',
        headers:
        {

            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },
        body:JSON.stringify({"createdat": cellValue})


    })

    .then(()=>{
        setTimeout(()=>{
            window.location.href='box-viewer';
        },2000)
    })


});
 
        $('.searchBtn').on('click', function () {
            $(document).ready(function () {
    $('.searchBtn').on('click', function () 
    {

        var brandID = $(this).val();
        let searchBtnDiv = $(this).closest('.searchBtnDiv');
        let loadingBtnDiv = $(this).parent().siblings('.loadingBtnDiv');
        let form = $(this).closest('.searchForm');
        formattedDateTime = "";
        function getFormattedCurrentDateTime() {
    const now = new Date();

    now.setHours(now.getHours() + 7);

    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); 
    const day = String(now.getDate()).padStart(2, '0');
    
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

     formattedDateTime = `${year}_${month}_${day}_${hours}_${minutes}_${seconds}`;

    return formattedDateTime;
}


console.log(getFormattedCurrentDateTime()); 

        if (document.querySelector("#socialForm.active")) {
            if (document.querySelector("#socialForm select[name=type]").value == "facebook") {
                let keywords = document.querySelector("#socialForm input[name=keyword]").value.split(',');
                keywords = keywords.map(function(keyword) {
                    return keyword.trim();
                });

                searchBtnDiv.addClass('d-none');
                loadingBtnDiv.removeClass('d-none');

                let totalKeywords = keywords.length;
                let processedKeywords = 0;
               
                keywords.forEach(function(keyword) {
                    let keywordSocketId = socket_id + '_' + keyword.replace(/\s+/g, '_');
                    let setInter = setInterval(() => {
                        $.ajax({
                            url: "{{route('facebookExist', '')}}/" + keywordSocketId,
                            type: "POST",
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            data: JSON.stringify({
                                _token: "{{csrf_token()}}",
                                socket_id: keywordSocketId,
                                keyword: keyword,
                                sort: document.querySelector("#socialForm select[name=facebook_sort]").value,
                                searchLimit: document.querySelector("#socialForm select[name=results]").value
                            }),
                            success: function(data2, status) {
                                console.log("Checking status for keyword: " + keyword);

                                if (data2.status) {
                                    data = data2.data;
                                    console.log(data);
                                    clearInterval(setInter);
                                    $.ajax({
                                        type: 'post',
                                        url: "{{route('searchFacebook')}}",
                                        data: {
                                            _token: "{{csrf_token()}}",
                                            data
                                        },
                                        success: function (response) {
                                            console.log(response);
                                            $('#latestSearches').removeClass('d-none');
                                            $.each(response, function (index, dataItem) {
                                                $('#latestSearches > tbody').prepend('<tr> <td><i class="'+dataItem.type_icon+'"></i></td> <td>'+dataItem.type_name+'</td> <td>'+dataItem.keyword+'</td> <td>'+formattedDateTime+'</td> <td>'+dataItem.results+' <a class="downloadBtn" href="'+dataItem.file+'"><i class="ms-2 fas fa-download"></i></a></td></tr>');
                                            });

                                            processTableData();

                                            processedKeywords++;
                                            if (processedKeywords === totalKeywords) {
                                                searchBtnDiv.removeClass('d-none');
                                                loadingBtnDiv.addClass('d-none');
                                            }
                                        },
                                        error: function(e) {
                                            console.log(e);
                                            processedKeywords++;
                                            if (processedKeywords === totalKeywords) {
                                                searchBtnDiv.removeClass('d-none');
                                                loadingBtnDiv.addClass('d-none');
                                            }
                                        }
                                    });
                                }
                            },
                            error: function(e) {
                                console.log(e);
                            }
                        });
                    }, 2000);

                    $.ajax({
                        url: "{{route('facebookApi')}}",
                        type: "POST",
                        data: {
                            _token: "{{csrf_token()}}",
                            socket_id: keywordSocketId,
                            keyword: keyword,
                            sort: document.querySelector("#socialForm select[name=facebook_sort]").value,
                            searchLimit: document.querySelector("#socialForm select[name=results]").value
                        },
                        success: function(data, status) {
                            console.log("Started search for keyword: " + keyword);
                        }
                    });
                });
            }
        } else if (document.querySelector("#trendsForm.active")) {
            searchBtnDiv.addClass('d-none');
            loadingBtnDiv.removeClass('d-none');

            let keywords = document.querySelector("#trendsForm input[name=keyword]").value.split(',');
            keywords = keywords.map(function(keyword) {
                return keyword.trim();
            });

            let totalKeywords = keywords.length;
            let processedKeywords = 0;

            keywords.forEach(function(keyword) {
                let fd = new FormData();
                fd.append('socket_id', socket_id);
                fd.append('keyword', keyword);

                $.ajax({
                    url: "{{route('trendsApi')}}",
                    type: "POST",
                    headers: {
                         'Content-Type': 'application/json',
                    },
                    data: JSON.stringify({
                        _token: "{{csrf_token()}}",
                        socket_id: socket_id,
                        keyword: keyword
                    }),
                    contentType: false,
                    processData: false,
                    success: function(data, status) {
                        console.log(data);

                        document.querySelector("#trendsSearch input[name=json]").value = JSON.stringify(data.data);
                        document.querySelector("#trendsSearch").submit();

                        processedKeywords++;
                        if (processedKeywords === totalKeywords) {
                            searchBtnDiv.removeClass('d-none');
                            loadingBtnDiv.addClass('d-none');
                        }
                    },
                    error: function(e) {
                        console.log(e);
                        processedKeywords++;
                        if (processedKeywords === totalKeywords) {
                            searchBtnDiv.removeClass('d-none');
                            loadingBtnDiv.addClass('d-none');
                        }
                    }
                });
            });
        } else {
            let keywords = form.find('input[name="keyword"]').val().split(',');
            keywords = keywords.map(function(keyword) {
                return keyword.trim();
            });

            let totalKeywords = keywords.length;
            let processedKeywords = 0;

            keywords.forEach(function(keyword) {
                let formData = form.serializeArray();
                formData = formData.filter(function(item) {
                    return item.name !== 'keyword';
                });
                formData.push({ name: 'keyword', value: keyword });

                $.ajax({
                    type: 'post',
                    url: form.attr('action'),
                    data: $.param(formData),
                    success: function (response) {
                        console.log(response);
                        if (response.error)
                            alert(response.error);
                        else {
                            getFormattedCurrentDateTime();
                            $('#latestSearches').removeClass('d-none');
                            $.each(response, function (index, dataItem) {
                                $('#latestSearches > tbody').prepend('<tr> <td><i class="'+dataItem.type_icon+'"></i></td> <td>'+dataItem.type_name+'</td> <td>'+dataItem.keyword+'</td> <td>'+formattedDateTime+'</td> <td>'+dataItem.results+' <a class="downloadBtn" href="'+dataItem.file+'"><i class="ms-2 fas fa-download"></i></a></td> <td><button  class="viewbtn">View</button></td></tr>');
                            });

                            processTableData();
                        }

                        processedKeywords++;
                        if (processedKeywords === totalKeywords) {
                            searchBtnDiv.removeClass('d-none');
                            loadingBtnDiv.addClass('d-none');
                        }
                    },
                    beforeSend: function () {
                        searchBtnDiv.addClass('d-none');
                        loadingBtnDiv.removeClass('d-none');
                    },
                    error: function(e) {
                        console.log(e);
                        alert("Error while exporting");
                        processedKeywords++;
                        if (processedKeywords === totalKeywords) {
                            searchBtnDiv.removeClass('d-none');
                            loadingBtnDiv.addClass('d-none');
                        }
                    }
                });
            });
        }
    });

    function processTableData() {
        var $table = $('#latestSearches');

        var headers = [];
        $table.find('tr:first').find('th, td').each(function() {
            headers.push($(this).text().trim());
        });

        var data = [];

        $table.find('tr').each(function(index) {
            if (index === 0) return; 
            var $row = $(this);
            var $cells = $row.find('td'); 
            var rowData = {};

            $cells.each(function(cellIndex) {
                var header = headers[cellIndex] || 'Column' + (cellIndex + 1);
                rowData[header] = $(this).text().trim();
            });

            if (!$.isEmptyObject(rowData)) {
                data.push(rowData);
            }
        });

        console.log('Data to be sent:', data); 

        var csrfToken = $('meta[name="csrf-token"]').attr('content');

        $.ajax({
            url: '/history-view', 
            method: 'POST',
            data: {
                data: data,
                _token: csrfToken
            },
            success: function(response) {
                console.log('Success:', response);
            },
            error: function(xhr, status, error) {
                console.error('Error:', xhr.responseText);
            }
        });
    }

    $('#select_search').on('change', function () {
        if ($(this).val() == "top") {
            $('#dateFrom').prop('disabled', false).parent().removeClass('d-none');
            $('#dateTo').prop('disabled', false).parent().removeClass('d-none');
            $('#profileTxt').prop('disabled', 'disabled').parent().addClass('d-none');
        } else if($(this).val() == 'profile'){
            $('#profileTxt').prop('disabled', false).parent().removeClass('d-none');
        } else {
            $('#profileTxt').prop('disabled', 'disabled').parent().addClass('d-none');
            $('#dateFrom').prop('disabled', 'disabled').parent().addClass('d-none');
            $('#dateTo').prop('disabled', 'disabled').parent().addClass('d-none');
        }
    });

    $(".social_media_form select[name=type]").on('change', function() {
        if($(this).val() == "facebook") {
            $("#facebookSort").css('display', 'block');
            $("#sort").css('display', "none");
        } else {
            $("#facebookSort").css('display', 'none');
            $("#sort").css('display', "block");
        }
    });
    document.querySelector(".social_media_form select[name=type]").dispatchEvent(new Event('change'));

    $(document).on('change','#platformSel',function (){
        if($(this).val() === 'Google' || $(this).val() === 'Bing' || $(this).val() === 'Duck'){
            $('#sortSel').prop('disabled',true);
            $('#dateFrom').prop('disabled', 'disabled').parent().addClass('d-none');
            $('#dateTo').prop('disabled', 'disabled').parent().addClass('d-none');
        } else {
            $('#sortSel').prop('disabled', false);
        }
        if($(this).val() !== 'twitter')
            $('#profileTxt').prop('disabled', 'disabled').parent().addClass('d-none');
    });

    $(document).on('submit','#searchForm',function(e) {
        e.preventDefault();
        $('#searchBtn').trigger('click');
    });

    $(document).on('click','.downloadBtn',function (){
        $(this).parents('tr').remove();
        if ($('#latestSearches > tbody tr').length == 0){
            $('#latestSearches').addClass('d-none');
        }
    });
});
})}) make the fetch request only can be executed just once of viewpage and send full code