// 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');

function loadTradeForm() {
    fetch('../html/register_trade.html')
        .then(response => response.text())
        .then(html => {
            formContainer.innerHTML = html;
            modal.style.display = 'block';

            // Use populateDropdowns here to populate dropdowns when form loads
        populateDropdowns()
            
            

            const leverageInput = document.getElementById('leverage');
            leverageInput.value = 1;
            leverageInput.min = 1;

            const close_date = document.getElementById('close_date');
            close_date.valueAsDate = new Date();
            close_date.max = close_date.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';
            });

            // Submit trade form data
            document.getElementById('trade-form').addEventListener('submit', function (event) {
                event.preventDefault(); 
                const coin = document.getElementById('coin').value;
                const coinpair = document.getElementById('coinpair').value;
                const direction = document.getElementById('direction').value;
                const open_price = document.getElementById('open_price').value;
                const close_price = document.getElementById('close_price').value;
                const leverage = document.getElementById('leverage').value;
                const close_date = document.getElementById('close_date').value;
                const photo = document.getElementById('photo').files[0];
                const account_name = document.getElementById('account_name').innerText;
                const profile_id = 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', 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);
                formData.append('profile_id', profile_id);

                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();
                        leverageInput.value = 1;
                        modal.style.display = 'none';

                        const event = new Event('tradeUpdated');
                        window.dispatchEvent(event);
                    } 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));
}

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

window.addEventListener('tradeAdded', function() {
    fetchTradeHistory();
});