// Admin Panel JavaScript
$(document).ready(function() {
    // Initialize tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // Initialize popovers
    var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
    var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
        return new bootstrap.Popover(popoverTriggerEl);
    });

    // Auto-hide alerts after 5 seconds
    $('.alert').each(function() {
        var alert = $(this);
        setTimeout(function() {
            alert.fadeOut();
        }, 5000);
    });

    // Confirm delete actions
    $('.btn-delete').on('click', function(e) {
        if (!confirm('Are you sure you want to delete this item?')) {
            e.preventDefault();
        }
    });

    // Table row hover effects
    $('.table tbody tr').hover(
        function() {
            $(this).addClass('table-hover-row');
        },
        function() {
            $(this).removeClass('table-hover-row');
        }
    );

    // Search functionality
    $('#searchInput').on('keyup', function() {
        var value = $(this).val().toLowerCase();
        $('#dataTable tbody tr').filter(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
        });
    });

    // Select all checkbox functionality
    $('#selectAll').on('change', function() {
        $('.item-checkbox').prop('checked', this.checked);
        updateBulkActions();
    });

    $('.item-checkbox').on('change', function() {
        updateBulkActions();
    });

    function updateBulkActions() {
        var checkedBoxes = $('.item-checkbox:checked');
        var count = checkedBoxes.length;
        
        if (count > 0) {
            $('#bulkActions').show();
            $('#selectedCount').text(count);
        } else {
            $('#bulkActions').hide();
        }
        
        // Update select all checkbox
        var totalBoxes = $('.item-checkbox').length;
        $('#selectAll').prop('checked', count === totalBoxes);
    }

    // Status toggle functionality
    $('.status-toggle').on('click', function(e) {
        e.preventDefault();
        var button = $(this);
        var url = button.data('url');
        var status = button.data('status');
        
        if (confirm('Are you sure you want to change the status?')) {
            $.ajax({
                url: url,
                method: 'POST',
                data: {
                    _token: $('meta[name="csrf-token"]').attr('content'),
                    status: status
                },
                success: function(response) {
                    location.reload();
                },
                error: function() {
                    alert('An error occurred. Please try again.');
                }
            });
        }
    });

    // Form validation
    $('form').on('submit', function() {
        var form = $(this);
        var requiredFields = form.find('[required]');
        var isValid = true;
        
        requiredFields.each(function() {
            var field = $(this);
            if (!field.val().trim()) {
                field.addClass('is-invalid');
                isValid = false;
            } else {
                field.removeClass('is-invalid');
            }
        });
        
        return isValid;
    });

    // Real-time form validation
    $('input[required], textarea[required], select[required]').on('blur', function() {
        var field = $(this);
        if (!field.val().trim()) {
            field.addClass('is-invalid');
        } else {
            field.removeClass('is-invalid');
        }
    });
});

// Global functions
function deleteItem(url, itemName) {
    if (confirm('Are you sure you want to delete ' + itemName + '?')) {
        var form = $('<form>', {
            'method': 'POST',
            'action': url
        });
        
        form.append($('<input>', {
            'type': 'hidden',
            'name': '_token',
            'value': $('meta[name="csrf-token"]').attr('content')
        }));
        
        form.append($('<input>', {
            'type': 'hidden',
            'name': '_method',
            'value': 'DELETE'
        }));
        
        $('body').append(form);
        form.submit();
    }
}

function toggleStatus(url, status) {
    if (confirm('Are you sure you want to change the status?')) {
        $.ajax({
            url: url,
            method: 'POST',
            data: {
                _token: $('meta[name="csrf-token"]').attr('content'),
                status: status
            },
            success: function(response) {
                location.reload();
            },
            error: function() {
                alert('An error occurred. Please try again.');
            }
        });
    }
}
