const paymentContent = document.getElementById('paymentContent');
const paymentLoader = document.getElementById('paymentLoader');
const item_id = document.getElementById('itemId').textContent;

function initiateCheckout(item_id, selectedCycleId) {
    const csrftoken = getCookie('csrftoken');
    console.log(item_id);
    console.log('Selected Cycle ID:', selectedCycleId);

    console.log('CSRF Token:', csrftoken);

    paymentLoader.classList.remove('hidden');

    fetch('/payment/buy-now-checkout/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': csrftoken,
        },
        body: JSON.stringify({ item_id: item_id, cycle_id: selectedCycleId }),
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            console.log("Session ID: " + data.session_id);
            // Update Checkout session with the fetched session ID and show the embedded page
            Checkout.configure({
                session: {
                    id: data.session_id,
                }
            });
            $('#paymentContent').empty();
            Checkout.showEmbeddedPage('#paymentContent');
            sessionStorage.clear();

            paymentLoader.classList.add('hidden'); 
        })
        .catch(error => {
            console.error('There was a problem with the fetch operation:', error);

            paymentLoader.classList.add('hidden'); 
        });
}

// Add an event listener to the select element
const cycleSelect = document.getElementById('cycle');
cycleSelect.addEventListener('change', function() {
    // Get the selected cycle ID when the user changes the selection
    const selectedCycleId = cycleSelect.value;
    console.log('Selected Cycle ID:', selectedCycleId);
    
    // Call initiateCheckout with the updated cycle ID
    initiateCheckout(item_id, selectedCycleId);
});

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// Call initiateCheckout initially with the default selected cycle ID
const selectedCycleId = cycleSelect.value;
initiateCheckout(item_id, selectedCycleId);
