// Fetch query parameters (email, profile_id, and account_name) from the URL
const params = new URLSearchParams(window.location.search);
const email = params.get('email');
const profileId = params.get('profile_id');
const accountName = params.get('account_name');

// Display the values on the page
document.getElementById('email').textContent = email;
document.getElementById('profile_id').textContent = profileId;
document.getElementById('account_name').textContent = accountName;

// Back button functionality
document.getElementById('back-button').addEventListener('click', function() {
    window.history.back(); // Go back to the previous page
});

// JavaScript to handle modal popup and form loading
// JavaScript to handle modal popup and form loading
const modal = document.getElementById('tradeModal');
const openButton = document.getElementById('open-form-button');
const formContainer = document.getElementById('form-container');

// Function to load the trade form
function loadTradeForm() {
    fetch('../html/register_trade.html')  // Path to the trade form HTML file
        .then(response => response.text())
        .then(html => {
            formContainer.innerHTML = html; // Insert the form HTML into the modal
            modal.style.display = 'block';  // Display the modal

            // Set leverage to 1 by default and ensure it can't go below 1
            const leverageInput = document.getElementById('leverage');
            leverageInput.value = 1;  // Set default value
            leverageInput.min = 1;    // Set minimum value

            const openprice = document.getElementById('open_price');
            openprice.min = 0; 

            const closeprice = document.getElementById('close_price');
            closeprice.min = 0; 

            // Attach event listeners after loading the form
            document.getElementById('close-form-button').addEventListener('click', function() {
                modal.style.display = 'none';  // Hide the modal when "Close" is clicked
            });

            // Handle form submission using AJAX
            document.getElementById('submit-button').addEventListener('click', function() {
                var coin = document.getElementById('coin').value;
                var coinpair = document.getElementById('coinpair').value;
                var direction = document.getElementById('direction').value;
                var open_price = document.getElementById('open_price').value;
                var close_price = document.getElementById('close_price').value;
                var leverage = document.getElementById('leverage').value;
                var close_date = document.getElementById('close_date').value;
                var photo = document.getElementById('photo').files[0];
                var account_name = document.getElementById('account_name').innerText;

                var formData = new FormData();
                formData.append('coin', coin);
                formData.append('coinpair', coinpair);
                formData.append('direction', direction);
                formData.append('open_price', open_price);
                formData.append('close_price', close_price);
                formData.append('leverage', leverage);
                formData.append('close_date', close_date);
                formData.append('photo', photo);
                formData.append('account_name', account_name);

                // AJAX request to send the form data to the PHP file
                fetch('../php/register_trade.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        alert("Trade data successfully submitted.");

                        // Reset the form to its default state
                        document.getElementById('trade-form').reset();
                        leverageInput.value = 1; 
     
                    } else {
                        alert("Error: " + data.message);
                    }
                })
                .catch(error => {
                    console.error('There was a problem with the fetch operation:', error);
                    alert('Error: ' + error.message);
                });
            });
        })
        .catch(error => console.log('Error loading trade form:', error));
}


async function fetchTradeInfo(tradeId) {
    try {
        const response = await fetch(`../php/get_trade_info.php?trade_id=${tradeId}`);
        const tradeDetails = await response.json();

        if (tradeDetails.error) {
            tradeInfoContent.innerHTML = `<p>${tradeDetails.error}</p>`;
        } else {
            // Fill the modal with the trade details
            tradeInfoContent.innerHTML = `
                <h2>Trade Info</h2>
                <p><strong>Trade ID:</strong> ${tradeDetails.trade_id}</p>
                <p><strong>Coin Name:</strong> ${tradeDetails.coin_name}</p>
                <p><strong>Coin Pair:</strong> ${tradeDetails.coinpair_name}</p>
                <p><strong>Direction:</strong> ${tradeDetails.direction}</p>
                <p><strong>Leverage:</strong> ${tradeDetails.leverage}X</p>
                <p><strong>Open Price:</strong> ${tradeDetails.open_price}</p>
                <p><strong>Close Price:</strong> ${tradeDetails.close_price}</p>
                <p><strong>Percents:</strong> ${tradeDetails.percents}%</p>
                <p><strong>Close Date:</strong> ${tradeDetails.close_date}</p>
                ${tradeDetails.photo ? `<img src="${tradeDetails.photo}" alt="Trade Photo" />` : ''}
            `;
        }

        // Display the modal
        tradeInfoModal.style.display = 'block';
    } catch (error) {
        console.error('Error fetching trade details:', error);
        tradeInfoContent.innerHTML = '<p>Error loading trade details.</p>';
    }
}


// Open modal when button is clicked
openButton.addEventListener('click', loadTradeForm);



