// bidding.js - Bidding JavaScript
// File location: /bidwheels.net/assets/js/bidding.js

$(document).ready(function() {
    
    // Bid form validation
    $('.bid-form').submit(function(e) {
        const bidAmount = parseFloat($('#bid_amount').val());
        const currentBid = parseFloat($('#current_bid').val());
        const startingPrice = parseFloat($('#starting_price').val());
        const minBid = currentBid > 0 ? currentBid + 1 : startingPrice;
        
        if (isNaN(bidAmount)) {
            alert('Please enter a valid bid amount.');
            e.preventDefault();
            return false;
        }
        
        if (bidAmount < minBid) {
            alert('Bid must be at least $' + minBid.toFixed(2));
            e.preventDefault();
            return false;
        }
        
        return true;
    });
    
    // Countdown timer for auctions
    function updateCountdowns() {
        $('.countdown').each(function() {
            const endTime = $(this).data('end');
            if (!endTime) return;
            
            const now = new Date().getTime();
            const end = new Date(endTime).getTime();
            const distance = end - now;
            
            if (distance < 0) {
                $(this).html('<span class="ended">Auction Ended</span>');
                $(this).closest('.bid-form-container').find('.bid-form').hide();
                return;
            }
            
            const days = Math.floor(distance / (1000 * 60 * 60 * 24));
            const hours = Math.floor((distance % (86400000)) / (3600000));
            const minutes = Math.floor((distance % (3600000)) / (60000));
            const seconds = Math.floor((distance % (60000)) / 1000);
            
            let display = '';
            if (days > 0) display += days + 'd ';
            if (hours > 0) display += hours + 'h ';
            if (minutes > 0) display += minutes + 'm ';
            display += seconds + 's';
            
            $(this).html(display);
        });
    }
    
    updateCountdowns();
    setInterval(updateCountdowns, 1000);
    
    // Real-time bid update simulation (for demo)
    if ($('.auto-refresh').length) {
        setInterval(function() {
            const productId = $('#product_id').val();
            if (productId) {
                $.ajax({
                    url: '/ajax/get_latest_bid.php',
                    type: 'POST',
                    data: { product_id: productId },
                    success: function(response) {
                        if (response.new_bid) {
                            $('.current-bid').text('$' + response.new_bid);
                            $('.total-bids').text(response.total_bids);
                            
                            // Add notification
                            if (response.new_bid > currentUserBid) {
                                $('.bid-notification').fadeIn().delay(3000).fadeOut();
                            }
                        }
                    }
                });
            }
        }, 30000);
    }
    
    // Outbid notification alert
    if ($('.outbid-alert').length) {
        setTimeout(function() {
            $('.outbid-alert').fadeOut('slow');
        }, 5000);
    }
    
    // Bid history show/hide
    $('.show-bid-history').click(function() {
        $('#bidHistoryModal').fadeIn();
    });
    
    $('.close-modal').click(function() {
        $('#bidHistoryModal').fadeOut();
    });
    
    // Quick bid buttons
    $('.quick-bid').click(function() {
        const amount = $(this).data('amount');
        $('#bid_amount').val(amount);
        $('#bid_amount').focus();
    });
    
    // Payment method selection
    $('.payment-method-card').click(function() {
        $('.payment-method-card').removeClass('selected');
        $(this).addClass('selected');
        const method = $(this).data('method');
        $('#selected_payment_method').val(method);
        loadPaymentFields(method);
    });
    
    function loadPaymentFields(method) {
        $.ajax({
            url: '/ajax/get_payment_fields.php',
            type: 'POST',
            data: { method: method },
            success: function(response) {
                $('.payment-fields-container').html(response);
            }
        });
    }
    
    // Save payment method for future bids
    $('#save_payment_method').change(function() {
        if ($(this).is(':checked')) {
            $('#save_method_confirm').show();
        } else {
            $('#save_method_confirm').hide();
        }
    });
    
    // Email check for returning bidders
    $('#check_email_btn').click(function() {
        const email = $('#bidder_email').val();
        if (!email) {
            alert('Please enter your email address');
            return;
        }
        
        $.ajax({
            url: '/ajax/check_returning_bidder.php',
            type: 'POST',
            data: { email: email },
            success: function(response) {
                if (response.has_payment_method) {
                    $('#saved_payment_section').show();
                    $('#new_payment_section').hide();
                    displaySavedMethods(response.payment_methods);
                } else {
                    $('#saved_payment_section').hide();
                    $('#new_payment_section').show();
                }
                $('#contact_section').show();
            }
        });
    });
});