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

// Import the populateDropdowns function
import { populateDropdowns } from './get_coin_names.js'; // Ensure the path matches your file structure

const modal = document.getElementById('tradeModal');
const openButton = document.getElementById('open-form-button');
const formContainer = document.getElementById('form-container');

/**
 * Load the trade form into the modal and set up its functionality.
 */
function loadTradeForm() {
    fetch('../html/register_trade.html')
        .then(response => response.text())
        .then(html => {
            formContainer.innerHTML = html;
            modal.style.display = 'block';

            // Populate dropdowns when the form loads
            populateDropdowns();

            // Set up default values for inputs
            const leverageInput = document.getElementById('leverage');
            leverageInput.value = 1;
            leverageInput.min = 1;

            const closeDate = document.getElementById('close_date');
            closeDate.valueAsDate = new Date();
            closeDate.max = closeDate.value;

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

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

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

            // Set up trade form submission
            document.getElementById('trade-form').addEventListener('submit', function (event) {
                event.preventDefault(); // Prevent default form submission

                // Collect form data
                const coin = document.getElementById('coin').value;
                const coinPair = document.getElementById('coinpair').value;
                const direction = document.getElementById('direction').value;
                const openPrice = document.getElementById('open_price').value;
                const closePrice = document.getElementById('close_price').value;
                const leverage = document.getElementById('leverage').value;
                const closeDate = document.getElementById('close_date').value;
                const photo = document.getElementById('photo').files[0];
                const accountName = document.getElementById('account_name').innerText;
                const profileId = document.getElementById('profile_id').innerText;

                const formData = new FormData();
                formData.append('coin', coin);
                formData.append('coinpair', coinPair);
                formData.append('direction', direction);
                formData.append('open_price', openPrice);
                formData.append('close_price', closePrice);
                formData.append('leverage', leverage);
                formData.append('close_date', closeDate);
                formData.append('photo', photo);
                formData.append('account_name', accountName);
                formData.append('profile_id', profileId);

                // Submit the form data via fetch
                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 registered.");
                            document.getElementById('trade-form').reset(); // Reset form fields
                            leverageInput.value = 1; // Reset leverage input
                            modal.style.display = 'none'; // Close the modal

                            // Dispatch the custom event to refresh the trade history
                            window.dispatchEvent(new Event('updateTable'));
                        } 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.error('Error loading trade form:', error));
}

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

