<?php
if (!defined('ABSPATH')) exit;

$client = new Fusion_WooDoo_API_Client();
$result = $client->request('/woo/api/sales/list', ['customer_id' => get_current_user_id()]);
$orders = $result['success'] ? ($result['data']['orders'] ?? []) : [];
?>
<div class="fusion-woodoo-portal">
    <h2><?php esc_html_e('Sales Orders', 'fusion-woodoo'); ?></h2>

    <?php if (empty($orders)): ?>
        <p class="fusion-woodoo-empty"><?php esc_html_e('No sales orders found.', 'fusion-woodoo'); ?></p>
    <?php else: ?>
        <table class="fusion-woodoo-table woocommerce-orders-table">
            <thead>
                <tr>
                    <th><?php esc_html_e('Order #', 'fusion-woodoo'); ?></th>
                    <th><?php esc_html_e('Date', 'fusion-woodoo'); ?></th>
                    <th><?php esc_html_e('Status', 'fusion-woodoo'); ?></th>
                    <th><?php esc_html_e('Total', 'fusion-woodoo'); ?></th>
                    <th><?php esc_html_e('Actions', 'fusion-woodoo'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($orders as $order): ?>
                    <tr>
                        <td><?php echo esc_html($order['name'] ?? '—'); ?></td>
                        <td><?php echo esc_html($order['date_order'] ?? '—'); ?></td>
                        <td>
                            <span class="fusion-woodoo-badge fusion-woodoo-badge--<?php echo esc_attr($order['state'] ?? 'draft'); ?>">
                                <?php echo esc_html(ucfirst($order['state'] ?? '—')); ?>
                            </span>
                        </td>
                        <td><?php echo '$' . number_format((float) ($order['amount_total'] ?? 0), 2); ?></td>
                        <td>
                            <?php if (!empty($order['wc_order_id'])): ?>
                                <button
                                    class="button fusion-woodoo-reorder"
                                    data-order-id="<?php echo esc_attr($order['wc_order_id']); ?>"
                                    data-nonce="<?php echo esc_attr(wp_create_nonce('fusion_woodoo_nonce')); ?>">
                                    <?php esc_html_e('Reorder', 'fusion-woodoo'); ?>
                                </button>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>

    <?php if (!$result['success']): ?>
        <div class="fusion-woodoo-notice fusion-woodoo-notice--warning">
            <p><?php esc_html_e('Could not load sales orders from Odoo at this time. Please try again later.', 'fusion-woodoo'); ?></p>
        </div>
    <?php endif; ?>
</div>
