/* Main menu actions */
jQuery('.burger').on('click', function () {
	jQuery('.burger').toggleClass('opened');
	jQuery('.menumain').toggleClass('mopen');
	jQuery('nav').slideToggle("fast");
});
jQuery('.dropdown').on('click', function () {
	jQuery(this).children(".shaddow").slideToggle("fast");
	jQuery(this).toggleClass('opened');
});

/* to top */
jQuery('.submenu.f-up').click(function() {
	jQuery("body,html").animate({scrollTop:0},1);
});


/* Hide menu on scroll */
jQuery(function(){
	var lastScrollTop=0;
	jQuery(document).scroll(function(){
		var st=jQuery(window).scrollTop();
		if(st>50){
			if (jQuery('.menumain').hasClass("mopen")) {
				jQuery('.menumobile').addClass('hidden');
			};
			if(st<lastScrollTop){
				jQuery('.menumobile').removeClass('hidden');
			}else{
				jQuery('.menumobile').removeClass('');
			}
		}
		lastScrollTop=st;
	});
});// Confimation
$('.confirmation').on('click', function () {
    return confirm('Ar tikrai?');
});$(document).ready(function () {
    // Search for products
    $('#product-search').on('input', function () {
        const query = $(this).val();
        const department = $('#department').val();
        
        // Send GET request to fetch products based on search query and department
        $.get('/fetch/products/0/', { query, department }, function (data) {
            //console.log(data); // Debugging: check the received data

            const suggestions = $('#suggestions');
            suggestions.empty(); // Clear previous suggestions

            // Display search suggestions
            data.forEach(product => {
                const item = $(`
                    <div class="suggestion-item" 
                         data-id="${product.product_id}" 
                         data-name="${product.product_name}" 
                         data-price="${product.product_price}">
                        ${product.product_name} - $${product.product_price}
                    </div>
                `);
                suggestions.append(item);
            });
        });
    });

    // Add selected product to the cart
    $(document).on('click', '.suggestion-item', function () {
        const id = $(this).data('id');
        const name = $(this).data('name');
        const price = parseFloat($(this).data('price'));
        const quantity = 1;

        // Create a new row in the cart table
        const row = $(`
            <tr data-id="${id}">
                <td>${name}</td>
                <td><input type="number" class="quantity" value="${quantity}" min="1"></td>
                <td>${price.toFixed(2)}EUR</td>
                <td class="item-total">${(price * quantity).toFixed(2)}EUR</td>
                <td><button class="remove-item">Pašalinti</button></td>
            </tr>
        `);

        $('#cart-items').append(row);
        updateTotal(); // Update total after adding an item

        $('#suggestions').empty(); // Clear suggestions
        $('#product-search').val(''); // Clear the search input
    });

    // Update item total when quantity is changed
    $(document).on('input', '.quantity', function () {
        const row = $(this).closest('tr');
        const price = parseFloat(row.find('td').eq(2).text().replace('$', ''));
        const quantity = parseInt($(this).val());
        const total = price * quantity;

        row.find('.item-total').text(`$${total.toFixed(2)}`);
        updateTotal(); // Recalculate the cart total
    });

    // Remove an item from the cart
    $(document).on('click', '.remove-item', function () {
        $(this).closest('tr').remove();
        updateTotal(); // Update total after removing an item
    });

    // Recalculate the total amount for the cart
    function updateTotal() {
        let total = 0;
        $('.item-total').each(function () {
            total += parseFloat($(this).text().replace('$', ''));
        });
        $('#total').text(total.toFixed(2)); // Update the total display
    }
});

// Handle Pay button click
$('#pay').on('click', function () {
    const cartItems = [];

    $('#cart-items tr').each(function () {
        const id = $(this).data('id');
        const name = $(this).find('td').eq(0).text();
        const quantity = parseInt($(this).find('.quantity').val());
        const price = parseFloat($(this).find('td').eq(2).text().replace('$', ''));
        const total = parseFloat($(this).find('.item-total').text().replace('$', ''));

        cartItems.push({ id, name, quantity, price, total });
    });

    const totalAmount = parseFloat($('#total').text());

    if (cartItems.length === 0) {
        alert('Your cart is empty!');
        return;
    }

    // Send payment request directly without confirmation
    $.ajax({
        url: '/process/payment',
        type: 'POST',
        data: JSON.stringify({ items: cartItems, total: totalAmount }),
        contentType: 'application/json', // Specify content type as JSON
        success: function(response) {
            if (response.success) {
                clearCart();
                // Display a success message after the payment is processed
                $('#payment-message').text('Kvitas buvo sėkmingai sugeneruotas!').show();

                // Hide the message after 5 seconds
                setTimeout(function() {
                    $('#payment-message').fadeOut();
                }, 5000);
            } else {
                console.error('Payment Error:', response.message);
                $('#payment-message').text('Payment failed: ' + response.message).show();

                // Hide the error message after 5 seconds
                setTimeout(function() {
                    $('#payment-message').fadeOut();
                }, 5000); // 5000ms = 5 seconds
            }
        }
    });
});

// Clear the cart after successful payment
function clearCart() {
    $('#cart-items').empty();  // Remove all items from the cart
    $('#total').text('0.00');  // Reset the total amount
}