function openSendModal(currency) {
    document.getElementById('send-currency').value = currency;
    document.getElementById('send-modal-title').innerText = 'Send ' + currency;
    document.getElementById('send-to-addr').value = '';
    document.getElementById('send-amount').value = '';
    document.getElementById('crypto-send-modal').style.display = 'flex';
}
function submitCryptoSend() {
    var cur = document.getElementById('send-currency').value;
    var to = document.getElementById('send-to-addr').value;
    var amt = document.getElementById('send-amount').value;
    if (!to || !amt) { alert('Fill all fields'); return; }
    if (!confirm('Are you sure you want to send ' + amt + ' ' + cur + ' to ' + to + '?')) return;
    
    fetch('?action=send_crypto', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'currency=' + encodeURIComponent(cur) + '&to=' + encodeURIComponent(to) + '&amount=' + encodeURIComponent(amt) + '&csrf=<?= CSRF::getToken() ?>'
    })
    .then(r => r.json())
    .then(d => {
        if (d.ok) { alert('Transaction sent! Hash: ' + d.tx_hash); document.getElementById('crypto-send-modal').style.display = 'none'; }
        else { alert('Error: ' + d.error); }
    })
    .catch(e => alert('Network error'));
}
function openTxModal(currency) {
    document.getElementById('tx-modal-title').innerText = currency + ' Transactions';
    document.getElementById('tx-modal-body').innerText = 'Loading...';
    document.getElementById('crypto-tx-modal').style.display = 'flex';
    
    fetch('?action=crypto_history&currency=' + encodeURIComponent(currency))
    .then(r => r.json())
    .then(d => {
        if (!d.ok) { document.getElementById('tx-modal-body').innerText = 'Error: ' + d.error; return; }
        if (!d.data || d.data.length === 0) { document.getElementById('tx-modal-body').innerText = 'No transactions found.'; return; }
        
        var html = '<table class="data-table" style="width:100%"><thead><tr><th>Time</th><th>Hash</th><th>Type</th><th>Amount</th></tr></thead><tbody>';
        d.data.forEach(function(tx) {
            html += '<tr>';
            html += '<td>' + tx.created_at + '</td>';
            html += '<td style="word-break:break-all">' + tx.tx_hash + '</td>';
            html += '<td style="color:' + (tx.type === 'receive' ? 'var(--success)' : 'var(--danger)') + '">' + tx.type.toUpperCase() + '</td>';
            html += '<td>' + tx.amount + '</td>';
            html += '</tr>';
        });
        html += '</tbody></table>';
        document.getElementById('tx-modal-body').innerHTML = html;
    })
    .catch(e => { document.getElementById('tx-modal-body').innerText = 'Network error'; });
}