// inwardent_new_search.js
$(document).ready(function () {
    // Variables for new search
    var newRangeFrom = 0,
        newRangeTo = 40;
    var searchTimeout = null;
    
    // Initialize New Search Modal
    $(".newSearchModal").on('shown.bs.modal', function () {
        $(".new-ssearch").focus();
        $(".new-ssearch").val("");
        $(".new-sfield").val("1");
        newRangeFrom = 0;
        newRangeTo = 40;
        getNewSearchData();
    });
    
    // New Search Button Click
    $("#newSearchBtn").click(function(e) {
        e.preventDefault();
        $(".newSearchModal").modal('show');
    });
    
    // New Search Function
    function getNewSearchData(pagination) {
        // Add searching class to input
        $(".new-ssearch").addClass("searching");
        
        $(".new-sloader").show();
        $(".new-snoRecord").hide();
        
        // Handle pagination
        if (pagination == 'prev') {
            if (newRangeFrom > 0) {
                newRangeFrom = Math.max(0, newRangeFrom - 40);
                newRangeTo = newRangeFrom + 40;
            }
        } else if (pagination == 'next') {
            newRangeFrom = newRangeFrom + 40;
            newRangeTo = newRangeFrom + 40;
        }
        
        var ssearch = $(".new-ssearch").val(),
            sfield = $(".new-sfield").val(),
            soperator = $(".new-soperator").val(),
            data = {
                ssearch: ssearch,
                sfield: sfield,
                soperator: soperator,
                rangeFrom: newRangeFrom,
                rangeTo: newRangeTo
            },
            values = "";
        
        $.ajax({
            type: 'GET',
            dataType: 'json',
            url: "inwardent_new_search.php",
            data: data,
            success: function (response) {
                // Remove searching class
                $(".new-ssearch").removeClass("searching");
                
                if (response && response.length > 0) {
                    $.each(response, function () {
                        values += "<tr class='new-clickable-row' data-href='" + this.action + "'>" +
                                "<td align='center'>" + this.vouchno + "</td>" +
                                "<td align='center'>" + this.vouchdt + "</td>" +
                                "<td align='left'>" + (this.barcode || '') + "</td>" +
                                "<td align='left'>" + (this.itemname || '') + "</td>" +
                                "<td align='left'>" + (this.batch || '') + "</td>" +
                                "<td align='right'>" + (this.qty || 0) + "</td>" +
                                "<td align='left'>" + (this.unitname || '') + "</td>" +
                                "<td align='center'><a href='" + this.action + "'><i class='fa fa-pencil' style='font-size:1.3em;cursor:pointer;'></i></a></td>" +
                                "</tr>";
                    });
                    
                    $(".new-search-action-bar").show();
                } else {
                    values = "<tr><td colspan='19' class='text-center'>No records found</td></tr>";
                    $(".new-search-action-bar").hide();
                }
                
                $(".new-sloader").hide();
                $(".new-sTbody").empty();
                $(".new-sTbody").html(values);
                
                // Add click handler for rows
                $(".new-clickable-row").click(function() {
                    window.location = $(this).data("href");
                    $(".newSearchModal").modal('hide');
                });
            },
            error: function (request, textStatus, errorThrown) {
                // Remove searching class on error too
                $(".new-ssearch").removeClass("searching");
                
                $(".new-sloader").hide();
                $(".new-sTbody").html("<tr><td colspan='19' class='text-center'>Error loading data</td></tr>");
                console.error("New search error:", errorThrown);
            }
        });
    }
    
    // REAL-TIME SEARCH ON KEYUP (Automatic search as you type)
    $(".new-ssearch").on('keyup', function (e) {
        clearTimeout(searchTimeout);
        
        // Reset pagination on new search
        newRangeFrom = 0;
        newRangeTo = 40;
        
        // Add searching indicator
        $(this).addClass("searching");
        
        // Debounce - wait 500ms after user stops typing
        searchTimeout = setTimeout(function() {
            getNewSearchData();
        }, 500);
    });
    
    // Also search on blur (when user clicks out of search box)
    $(".new-ssearch").on('blur', function () {
        clearTimeout(searchTimeout);
        if ($(this).val().trim() !== '') {
            newRangeFrom = 0;
            newRangeTo = 40;
            getNewSearchData();
        }
        $(this).removeClass("searching");
    });
    
    // Search when dropdowns change
    $(".new-sfield, .new-soperator").on('change', function () {
        clearTimeout(searchTimeout);
        newRangeFrom = 0;
        newRangeTo = 40;
        $(".new-ssearch").addClass("searching");
        getNewSearchData();
    });
    
    // Pagination buttons
    $(".new-sprevious").click(function () {
        clearTimeout(searchTimeout);
        $(".new-ssearch").addClass("searching");
        getNewSearchData('prev');
    });
    
    $(".new-snext").click(function () {
        clearTimeout(searchTimeout);
        $(".new-ssearch").addClass("searching");
        getNewSearchData('next');
    });
    
    // Clear search when modal closes
    $(".newSearchModal").on('hidden.bs.modal', function () {
        clearTimeout(searchTimeout);
        $(".new-ssearch").val("").removeClass("searching");
    });
    
    // Handle escape key to remove searching class
    $(document).on('keydown', function(e) {
        if (e.keyCode === 27) { // ESC key
            $(".new-ssearch").removeClass("searching");
            clearTimeout(searchTimeout);
        }
    });
});