<?php
require __DIR__ . '/../../_layout.php';
?>

<div class="container">
    <h1>Pedidos do E-commerce</h1>

    <div class="card" style="margin-top: 2rem;">
        <div style="display: flex; gap: 1rem; margin-bottom: 1rem;">
            <button class="btn" onclick="loadPedidos()">Todos</button>
            <button class="btn btn-secondary" onclick="loadPedidos('pendente')">Pendentes</button>
            <button class="btn btn-secondary" onclick="loadPedidos('pago')">Pagos</button>
            <button class="btn btn-secondary" onclick="loadPedidos('enviado')">Enviados</button>
            <button class="btn btn-secondary" onclick="loadPedidos('entregue')">Entregues</button>
        </div>

        <div id="pedidos-list">
            <p>Carregando pedidos...</p>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    loadPedidos();
});

async function loadPedidos(status = null) {
    const token = localStorage.getItem('auth_token') || getCookie('auth_token');
    const tenantId = getCookie('tenant_id') || 'default';
    
    let url = '/api/ecommerce/pedidos';
    if (status) {
        url += '?status=' + status;
    }
    
    try {
        const res = await fetch(url, {
            headers: {
                'Authorization': `Bearer ${token}`,
                'X-Tenant-Id': tenantId
            }
        });
        
        if (res.ok) {
            const { data } = await res.json();
            const list = document.getElementById('pedidos-list');
            
            if (data.length === 0) {
                list.innerHTML = '<p>Nenhum pedido encontrado.</p>';
                return;
            }
            
            list.innerHTML = `
                <table style="width: 100%; border-collapse: collapse;">
                    <thead>
                        <tr style="border-bottom: 2px solid #e5e7eb;">
                            <th style="text-align: left; padding: 0.5rem;">Número</th>
                            <th style="text-align: left; padding: 0.5rem;">Cliente</th>
                            <th style="text-align: left; padding: 0.5rem;">Status</th>
                            <th style="text-align: right; padding: 0.5rem;">Total</th>
                            <th style="text-align: left; padding: 0.5rem;">Data</th>
                            <th style="text-align: right; padding: 0.5rem;">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${data.map(pedido => `
                            <tr style="border-bottom: 1px solid #e5e7eb;">
                                <td style="padding: 0.5rem;">${pedido.numero_pedido}</td>
                                <td style="padding: 0.5rem;">${pedido.cliente_nome}</td>
                                <td style="padding: 0.5rem;">
                                    <span class="status-badge status-${pedido.status}">${pedido.status}</span>
                                </td>
                                <td style="padding: 0.5rem; text-align: right;">R$ ${parseFloat(pedido.total).toFixed(2).replace('.', ',')}</td>
                                <td style="padding: 0.5rem;">${new Date(pedido.created_at).toLocaleDateString('pt-BR')}</td>
                                <td style="padding: 0.5rem; text-align: right;">
                                    <button onclick="viewPedido(${pedido.id})" class="btn btn-secondary" style="padding: 0.25rem 0.5rem; font-size: 0.9rem;">Ver</button>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            `;
        }
    } catch (error) {
        console.error('Erro ao carregar pedidos:', error);
        document.getElementById('pedidos-list').innerHTML = '<p style="color: #dc3545;">Erro ao carregar pedidos.</p>';
    }
}

function viewPedido(id) {
    window.location.href = `/vendas/ecommerce/pedidos/${id}`;
}

function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
}
</script>

<style>
.status-badge {
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-size: 0.85rem;
    font-weight: 600;
}
.status-pendente { background: #fef3c7; color: #92400e; }
.status-pago { background: #d1fae5; color: #065f46; }
.status-processando { background: #dbeafe; color: #1e40af; }
.status-enviado { background: #e0e7ff; color: #3730a3; }
.status-entregue { background: #d1fae5; color: #065f46; }
.status-cancelado { background: #fee2e2; color: #991b1b; }
</style>

