<?php
/**
 * Stablezact Admin Dashboard Template
 */

if (!defined('ABSPATH')) {
    exit;
}

// Check if API is configured
$stablezact_is_configured = !empty($this->gateway_settings['public_key']);
?>


<div class="wrap stablezact-admin">
    <div class="stablezact-header">
        <div class="stablezact-header-logo">
            <img src="<?php echo esc_url(STABLEZACT_PLUGIN_URL); ?>assets/images/stablezact-logo.png" alt="Stablezact" style="height: 40px;">
        </div>
        <div class="stablezact-header-content">
            <h1><?php esc_html_e('Stablezact Dashboard', 'stablezact-crypto-payments'); ?></h1>
            <p><?php esc_html_e('Manage your cryptocurrency payments and view transaction analytics', 'stablezact-crypto-payments'); ?></p>
        </div>
        <?php if ($stablezact_is_configured): ?>
        <div class="stablezact-header-actions">
            <button class="button button-primary" id="refresh-dashboard" aria-label="<?php esc_attr_e('Refresh dashboard data', 'stablezact-crypto-payments'); ?>">
                <span class="dashicons dashicons-update" aria-hidden="true"></span>
                <?php esc_html_e('Refresh Data', 'stablezact-crypto-payments'); ?>
            </button>
        </div>
        <?php endif; ?>
    </div>

    <?php if (!$stablezact_is_configured): ?>
    <div class="notice notice-warning">
        <p>
            <strong><?php esc_html_e('Setup Required', 'stablezact-crypto-payments'); ?></strong><br>
            <?php
            printf(
                /* translators: %s: link to WooCommerce settings */
                esc_html__('Please configure your Stablezact Public Key in the %s to start accepting crypto payments.', 'stablezact-crypto-payments'),
                '<a href="' . esc_url( admin_url('admin.php?page=wc-settings&tab=checkout&section=stablezact') ) . '">' . esc_html__('WooCommerce payment settings', 'stablezact-crypto-payments') . '</a>'
            );
            ?>
        </p>
    </div>
    <?php else: ?>

    <!-- Merchant Info Card -->
    <?php if ($merchant_data): ?>
    <div class="stablezact-merchant-card">
        <div class="merchant-info">
            <h3><?php esc_html_e('Merchant Profile', 'stablezact-crypto-payments'); ?></h3>
            <div class="merchant-details">
                <div class="merchant-detail">
                    <label><?php esc_html_e('Merchant Name:', 'stablezact-crypto-payments'); ?></label>
                    <span><?php echo esc_html($merchant_data['name'] ?? 'Merchant'); ?></span>
                </div>
                <div class="merchant-detail">
                    <label><?php esc_html_e('Merchant ID:', 'stablezact-crypto-payments'); ?></label>
                    <span><?php echo esc_html($merchant_data['id'] ?? 'N/A'); ?></span>
                </div>
                <div class="merchant-detail">
                    <label><?php esc_html_e('Status:', 'stablezact-crypto-payments'); ?></label>
                    <span class="status-badge status-<?php echo esc_attr($merchant_data['status'] ?? 'active'); ?>">
                        <?php echo esc_html(ucfirst($merchant_data['status'] ?? 'Active')); ?>
                    </span>
                </div>
                <div class="merchant-detail">
                    <label><?php esc_html_e('Fee Rate:', 'stablezact-crypto-payments'); ?></label>
                    <span><?php echo esc_html(number_format(($merchant_data['customFeePercentage'] ?? STABLEZACT_DEFAULT_FEE_PERCENTAGE) * 100, 2)); ?>%</span>
                </div>
                <div class="merchant-detail">
                    <label><?php esc_html_e('Fee Charged To:', 'stablezact-crypto-payments'); ?></label>
                    <span class="fee-charged-badge">
                        <?php 
                        // Fixed, and deliberately not read from the account's
                        // feeChargedTo field: settlement always deducts the fee from
                        // the payout and never branches on that field, so rendering
                        // "Customer" would misstate where the merchant's money goes.
                        echo '<span style="font-weight: 600;">' . esc_html__('Merchant', 'stablezact-crypto-payments') . '</span>';
                        echo '<small style="display: block; color: #6b7280; font-size: 0.875em;">' . esc_html__('Deducted from your payout — the customer is not charged extra', 'stablezact-crypto-payments') . '</small>';
                        ?>
                    </span>
                </div>
            </div>
        </div>
        
        <div class="wallet-addresses">
            <h4><?php esc_html_e('Wallet Addresses', 'stablezact-crypto-payments'); ?></h4>
            <?php if (isset($merchant_data['merchantWallets']) && !empty($merchant_data['merchantWallets'])): ?>
            <div class="wallet-grid">
                <?php
                // Network display config with icons and colors
                $stablezact_network_config = array(
                    'ethereum' => array('icon' => '⟠', 'color' => '#627EEA', 'name' => 'Ethereum'),
                    'bsc' => array('icon' => '◆', 'color' => '#F0B90B', 'name' => 'BNB Chain'),
                    'polygon' => array('icon' => '⬡', 'color' => '#8247E5', 'name' => 'Polygon'),
                    'arbitrum' => array('icon' => '◈', 'color' => '#28A0F0', 'name' => 'Arbitrum'),
                    'optimism' => array('icon' => '◉', 'color' => '#FF0420', 'name' => 'Optimism'),
                    'avalanche' => array('icon' => '▲', 'color' => '#E84142', 'name' => 'Avalanche'),
                    'base' => array('icon' => '◐', 'color' => '#0052FF', 'name' => 'Base'),
                    'solana' => array('icon' => '◎', 'color' => '#9945FF', 'name' => 'Solana'),
                    'tron' => array('icon' => '◆', 'color' => '#FF0013', 'name' => 'Tron'),
                    'algorand' => array('icon' => '◇', 'color' => '#000000', 'name' => 'Algorand'),
                    'celo' => array('icon' => '○', 'color' => '#35D07F', 'name' => 'Celo'),
                );

                // Networks to hide (not yet supported)
                $stablezact_hidden_networks = array('algorand', 'solana', 'tron');

                foreach ($merchant_data['merchantWallets'] as $stablezact_network => $stablezact_wallet_data):
                    // Skip unsupported networks
                    if (in_array(strtolower($stablezact_network), $stablezact_hidden_networks)) continue;

                    // Handle both string and array formats
                    $stablezact_wallet_address = '';
                    if (is_string($stablezact_wallet_data)) {
                        $stablezact_wallet_address = $stablezact_wallet_data;
                    } elseif (is_array($stablezact_wallet_data)) {
                        if (isset($stablezact_wallet_data['walletAddress'])) {
                            $stablezact_wallet_address = $stablezact_wallet_data['walletAddress'];
                        } elseif (isset($stablezact_wallet_data['address'])) {
                            $stablezact_wallet_address = $stablezact_wallet_data['address'];
                        }
                    }

                    if (empty($stablezact_wallet_address) || !is_string($stablezact_wallet_address)) continue;

                    $stablezact_config = isset($stablezact_network_config[strtolower($stablezact_network)]) ? $stablezact_network_config[strtolower($stablezact_network)] : array('icon' => '●', 'color' => '#6B7280', 'name' => ucfirst($stablezact_network));
                    $stablezact_short_address = substr($stablezact_wallet_address, 0, 6) . '...' . substr($stablezact_wallet_address, -4);
                ?>
                <div class="wallet-chip" title="<?php echo esc_attr($stablezact_wallet_address); ?>">
                    <span class="wallet-chip-icon" style="background: <?php echo esc_attr($stablezact_config['color']); ?>">
                        <?php echo esc_html($stablezact_config['icon']); ?>
                    </span>
                    <div class="wallet-chip-content">
                        <span class="wallet-chip-network"><?php echo esc_html($stablezact_config['name']); ?></span>
                        <code class="wallet-chip-address"><?php echo esc_html($stablezact_short_address); ?></code>
                    </div>
                    <button class="wallet-chip-copy copy-address" data-address="<?php echo esc_attr($stablezact_wallet_address); ?>" title="<?php esc_attr_e('Copy address to clipboard', 'stablezact-crypto-payments'); ?>" aria-label="<?php esc_attr_e('Copy wallet address to clipboard', 'stablezact-crypto-payments'); ?>">
                        <span class="dashicons dashicons-admin-page" aria-hidden="true"></span>
                    </button>
                </div>
                <?php endforeach; ?>
            </div>
            <?php else: ?>
            <p class="no-wallets"><?php esc_html_e('No wallet addresses configured yet.', 'stablezact-crypto-payments'); ?></p>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Stats Cards -->
    <?php if ($stats): ?>
    <div class="stablezact-stats-grid" role="region" aria-label="<?php esc_attr_e('Payment statistics', 'stablezact-crypto-payments'); ?>">
        <div class="stat-card">
            <div class="stat-icon" aria-hidden="true">
                <span class="dashicons dashicons-chart-line"></span>
            </div>
            <div class="stat-content">
                <h3><?php echo esc_html(number_format($stats['totalPayments'] ?? 0)); ?></h3>
                <p><?php esc_html_e('Total Payments', 'stablezact-crypto-payments'); ?></p>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-icon" aria-hidden="true">
                <span class="dashicons dashicons-yes-alt"></span>
            </div>
            <div class="stat-content">
                <h3><?php echo esc_html(number_format($stats['completedPayments'] ?? 0)); ?></h3>
                <p><?php esc_html_e('Completed', 'stablezact-crypto-payments'); ?></p>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-icon" aria-hidden="true">
                <span class="dashicons dashicons-clock"></span>
            </div>
            <div class="stat-content">
                <h3><?php echo esc_html(number_format($stats['pendingPayments'] ?? 0)); ?></h3>
                <p><?php esc_html_e('Pending', 'stablezact-crypto-payments'); ?></p>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-icon" aria-hidden="true">
                <span class="dashicons dashicons-money-alt"></span>
            </div>
            <div class="stat-content">
                <h3>$<?php echo esc_html(number_format($stats['totalVolume'] ?? 0, 2)); ?></h3>
                <p><?php esc_html_e('Total Volume', 'stablezact-crypto-payments'); ?></p>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Recent Transactions -->
    <div class="stablezact-recent-transactions">
        <div class="section-header">
            <h2><?php esc_html_e('Recent Transactions', 'stablezact-crypto-payments'); ?></h2>
            <a href="<?php echo esc_url(admin_url('admin.php?page=stablezact-transactions')); ?>" class="button">
                <?php esc_html_e('View All Transactions', 'stablezact-crypto-payments'); ?>
            </a>
        </div>

        <?php if (!empty($recent_transactions)): ?>
        <div class="transactions-table-wrapper">
            <table class="wp-list-table widefat fixed striped" aria-label="<?php esc_attr_e('Recent cryptocurrency transactions', 'stablezact-crypto-payments'); ?>">
                <thead>
                    <tr>
                        <th scope="col"><?php esc_html_e('Payment ID', 'stablezact-crypto-payments'); ?></th>
                        <th scope="col"><?php esc_html_e('Amount', 'stablezact-crypto-payments'); ?></th>
                        <th scope="col"><?php esc_html_e('Currency', 'stablezact-crypto-payments'); ?></th>
                        <th scope="col"><?php esc_html_e('Network', 'stablezact-crypto-payments'); ?></th>
                        <th scope="col"><?php esc_html_e('Status', 'stablezact-crypto-payments'); ?></th>
                        <th scope="col"><?php esc_html_e('Date', 'stablezact-crypto-payments'); ?></th>
                        <th scope="col"><?php esc_html_e('Actions', 'stablezact-crypto-payments'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($recent_transactions as $stablezact_transaction):
                        // Get network info from the Network object
                        $stablezact_network_name = $stablezact_transaction['Network']['name'] ?? '';
                        $stablezact_network_short = $stablezact_transaction['Network']['shortName'] ?? '';
                        $stablezact_explorer_url = $stablezact_transaction['Network']['explorerUrl'] ?? '';

                        // Transaction hash
                        $stablezact_tx_hash = $stablezact_transaction['transactionHash'] ?? '';
                    ?>
                    <tr>
                        <td>
                            <code><?php echo esc_html($stablezact_transaction['id']); ?></code>
                        </td>
                        <td>
                            <strong>$<?php echo esc_html(number_format($stablezact_transaction['amount'], 2)); ?></strong>
                        </td>
                        <td>
                            <span class="currency-badge"><?php echo esc_html($stablezact_transaction['currency']); ?></span>
                        </td>
                        <td>
                            <?php echo esc_html(!empty($stablezact_network_name) ? $stablezact_network_name : 'N/A'); ?>
                        </td>
                        <td>
                            <span class="status-badge status-<?php echo esc_attr($stablezact_transaction['status']); ?>">
                                <?php echo esc_html(ucfirst($stablezact_transaction['status'])); ?>
                            </span>
                        </td>
                        <td>
                            <?php echo esc_html(gmdate('M j, Y H:i', strtotime($stablezact_transaction['createdAt']))); ?>
                        </td>
                        <td>
                            <?php if (!empty($stablezact_tx_hash) && !empty($stablezact_explorer_url)): ?>
                            <a href="<?php echo esc_url($stablezact_explorer_url . '/tx/' . $stablezact_tx_hash); ?>" target="_blank" rel="noopener noreferrer" class="button button-small" aria-label="<?php /* translators: %s: transaction hash (first 8 characters) */ echo esc_attr(sprintf(__('View transaction %s on blockchain explorer (opens in new tab)', 'stablezact-crypto-payments'), substr($stablezact_tx_hash, 0, 8))); ?>">
                                <span class="dashicons dashicons-external" style="vertical-align: middle; margin-top: -2px;" aria-hidden="true"></span>
                                <?php esc_html_e('Explorer', 'stablezact-crypto-payments'); ?>
                            </a>
                            <?php else: ?>
                            <span class="button button-small button-disabled" aria-label="<?php esc_attr_e('Transaction pending - no hash available yet', 'stablezact-crypto-payments'); ?>">
                                <?php esc_html_e('Pending', 'stablezact-crypto-payments'); ?>
                            </span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php else: ?>
        <div class="no-transactions">
            <div class="no-transactions-icon" aria-hidden="true">
                <span class="dashicons dashicons-admin-post"></span>
            </div>
            <h3><?php esc_html_e('No Transactions Yet', 'stablezact-crypto-payments'); ?></h3>
            <p><?php esc_html_e('Your cryptocurrency transactions will appear here once customers start making payments.', 'stablezact-crypto-payments'); ?></p>
        </div>
        <?php endif; ?>
    </div>

    <?php endif; ?>
</div>

<!-- Transaction Details Modal -->
<div id="transaction-modal" class="coinley-modal" style="display: none;" role="dialog" aria-modal="true" aria-labelledby="transaction-modal-title">
    <div class="stablezact-modal-content">
        <div class="stablezact-modal-header">
            <h3 id="transaction-modal-title"><?php esc_html_e('Transaction Details', 'stablezact-crypto-payments'); ?></h3>
            <button type="button" class="stablezact-modal-close" aria-label="<?php esc_attr_e('Close transaction details', 'stablezact-crypto-payments'); ?>">&times;</button>
        </div>
        <div class="stablezact-modal-body">
            <div class="loading"><?php esc_html_e('Loading transaction details...', 'stablezact-crypto-payments'); ?></div>
        </div>
    </div>
</div>

<?php
// Output this page's script as an inline script on the enqueued admin handle
// (wp_enqueue policy) instead of a raw inline script. ob_start captures the
// rendered JS, including any translated strings, unchanged.
ob_start();
?>
document.addEventListener('DOMContentLoaded', function() {
    // Copy wallet address functionality
    document.querySelectorAll('.copy-address').forEach(function(button) {
        button.addEventListener('click', function() {
            const address = this.dataset.address;
            navigator.clipboard.writeText(address).then(function() {
                button.innerHTML = '<span class="dashicons dashicons-yes"></span>';
                setTimeout(function() {
                    button.innerHTML = '<span class="dashicons dashicons-admin-page"></span>';
                }, 2000);
            });
        });
    });

    // View transaction details
    document.querySelectorAll('.view-transaction').forEach(function(button) {
        button.addEventListener('click', function() {
            const paymentId = this.dataset.paymentId;
            showTransactionDetails(paymentId);
        });
    });

    // Refresh dashboard
    const refreshBtn = document.getElementById('refresh-dashboard');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', function() {
            location.reload();
        });
    }

    // Modal functionality
    const modal = document.getElementById('transaction-modal');
    const closeBtn = modal.querySelector('.stablezact-modal-close');
    
    closeBtn.addEventListener('click', function() {
        modal.style.display = 'none';
    });

    window.addEventListener('click', function(event) {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    });

    function showTransactionDetails(paymentId) {
        const modal = document.getElementById('transaction-modal');
        const modalBody = modal.querySelector('.stablezact-modal-body');
        
        modalBody.innerHTML = '<div class="loading"><?php esc_html_e('Loading transaction details...', 'stablezact-crypto-payments'); ?></div>';
        modal.style.display = 'block';

        // Make AJAX request to get transaction details
        jQuery.post(stablezact_admin.ajax_url, {
            action: 'stablezact_get_transaction_details',
            nonce: stablezact_admin.nonce,
            payment_id: paymentId
        }, function(response) {
            if (response.success) {
                const transaction = response.data;
                modalBody.innerHTML = buildTransactionDetailsHTML(transaction);
            } else {
                modalBody.innerHTML = '<div class="error"><?php esc_html_e('Failed to load transaction details', 'stablezact-crypto-payments'); ?></div>';
            }
        });
    }

    function buildTransactionDetailsHTML(transaction) {
        return `
            <div class="transaction-details">
                <div class="detail-row">
                    <label><?php esc_html_e('Payment ID:', 'stablezact-crypto-payments'); ?></label>
                    <span><code>${transaction.id}</code></span>
                </div>
                <div class="detail-row">
                    <label><?php esc_html_e('Amount:', 'stablezact-crypto-payments'); ?></label>
                    <span><strong>$${parseFloat(transaction.amount).toFixed(2)}</strong></span>
                </div>
                <div class="detail-row">
                    <label><?php esc_html_e('Currency:', 'stablezact-crypto-payments'); ?></label>
                    <span class="currency-badge">${transaction.currency}</span>
                </div>
                <div class="detail-row">
                    <label><?php esc_html_e('Network:', 'stablezact-crypto-payments'); ?></label>
                    <span>${transaction.network}</span>
                </div>
                <div class="detail-row">
                    <label><?php esc_html_e('Status:', 'stablezact-crypto-payments'); ?></label>
                    <span class="status-badge status-${transaction.status}">${transaction.status}</span>
                </div>
                ${transaction.transactionHash ? `
                <div class="detail-row">
                    <label><?php esc_html_e('Transaction Hash:', 'stablezact-crypto-payments'); ?></label>
                    <span><code>${transaction.transactionHash}</code></span>
                </div>
                ` : ''}
                <div class="detail-row">
                    <label><?php esc_html_e('Created:', 'stablezact-crypto-payments'); ?></label>
                    <span>${new Date(transaction.createdAt).toLocaleString()}</span>
                </div>
                ${transaction.processedAt ? `
                <div class="detail-row">
                    <label><?php esc_html_e('Processed:', 'stablezact-crypto-payments'); ?></label>
                    <span>${new Date(transaction.processedAt).toLocaleString()}</span>
                </div>
                ` : ''}
            </div>
        `;
    }
});
<?php
wp_add_inline_script('stablezact-admin', ob_get_clean()); 