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

<div class="container">
    <h1>Pedido <?= htmlspecialchars($pedido['numero_pedido'] ?? $pedido['id']) ?></h1>

    <div class="card" style="margin-top: 1rem;">
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 1rem;">
            <div>
                <strong>Cliente</strong>
                <div><?= htmlspecialchars($pedido['cliente_nome'] ?? '') ?></div>
                <div><?= htmlspecialchars($pedido['cliente_email'] ?? '') ?></div>
                <div><?= htmlspecialchars($pedido['cliente_telefone'] ?? '') ?></div>
            </div>
            <div>
                <strong>Status</strong>
                <div><span class="status-badge status-<?= htmlspecialchars($pedido['status'] ?? 'pendente') ?>"><?= htmlspecialchars($pedido['status'] ?? 'pendente') ?></span></div>
            </div>
            <div>
                <strong>Totais</strong>
                <div>Subtotal: R$ <?= number_format((float)($pedido['subtotal'] ?? 0), 2, ',', '.') ?></div>
                <div>Frete: R$ <?= number_format((float)($pedido['frete'] ?? 0), 2, ',', '.') ?></div>
                <div>Desconto: R$ <?= number_format((float)($pedido['desconto'] ?? 0), 2, ',', '.') ?></div>
                <div><strong>Total: R$ <?= number_format((float)($pedido['total'] ?? 0), 2, ',', '.') ?></strong></div>
            </div>
            <div>
                <strong>Pagamento</strong>
                <div>Provider: <?= htmlspecialchars($pedido['payment_provider'] ?? '-') ?></div>
                <div>ID: <?= htmlspecialchars($pedido['payment_id'] ?? '-') ?></div>
                <div>Status: <?= htmlspecialchars($pedido['payment_status'] ?? '-') ?></div>
            </div>
        </div>
    </div>

    <div class="card" style="margin-top: 1.5rem;">
        <h2>Itens</h2>
        <?php if (!$itens || count($itens) === 0): ?>
            <p>Nenhum item encontrado.</p>
        <?php else: ?>
            <table class="table" style="width: 100%; border-collapse: collapse; margin-top: 0.5rem;">
                <thead>
                    <tr style="border-bottom: 2px solid #e5e7eb;">
                        <th style="text-align: left; padding: 0.5rem;">Código</th>
                        <th style="text-align: left; padding: 0.5rem;">Nome</th>
                        <th style="text-align: right; padding: 0.5rem;">Qtd</th>
                        <th style="text-align: right; padding: 0.5rem;">Preço</th>
                        <th style="text-align: right; padding: 0.5rem;">Subtotal</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($itens as $item): ?>
                        <tr style="border-bottom: 1px solid #e5e7eb;">
                            <td style="padding: 0.5rem;"><?= htmlspecialchars($item['codigo'] ?? '') ?></td>
                            <td style="padding: 0.5rem;"><?= htmlspecialchars($item['nome'] ?? '') ?></td>
                            <td style="padding: 0.5rem; text-align: right;"><?= (int)($item['quantidade'] ?? 0) ?></td>
                            <td style="padding: 0.5rem; text-align: right;">R$ <?= number_format((float)($item['preco_unitario'] ?? 0), 2, ',', '.') ?></td>
                            <td style="padding: 0.5rem; text-align: right;">R$ <?= number_format((float)($item['subtotal'] ?? 0), 2, ',', '.') ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

    <div class="card" style="margin-top: 1.5rem;">
        <h2>Ações</h2>
        <div style="display: flex; gap: 0.5rem; flex-wrap: wrap;">
            <button class="btn btn-secondary" onclick="updateStatus('pago')">Marcar como Pago</button>
            <button class="btn btn-secondary" onclick="updateStatus('processando')">Processando</button>
            <button class="btn btn-secondary" onclick="updateStatus('enviado')">Enviado</button>
            <button class="btn btn-secondary" onclick="updateStatus('entregue')">Entregue</button>
            <button class="btn btn-danger" onclick="updateStatus('cancelado')">Cancelar</button>
            <a href="/vendas/ecommerce/pedidos" class="btn">Voltar</a>
        </div>
    </div>
</div>

<script>
function updateStatus(status) {
    if (!confirm('Confirmar alteração de status para "' + status + '"?')) return;
    const token = localStorage.getItem('auth_token') || getCookie('auth_token');
    const tenantId = getCookie('tenant_id') || 'default';
    const id = <?= (int)($pedido['id'] ?? 0) ?>;
    fetch('/api/ecommerce/pedidos/' + id + '/status', {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`,
            'X-Tenant-Id': tenantId
        },
        body: JSON.stringify({ status })
    }).then(async res => {
        if (res.ok) {
            alert('Status atualizado com sucesso');
            location.reload();
        } else {
            const err = await res.json().catch(() => ({}));
            alert('Erro: ' + (err.error?.message || 'Falha ao atualizar status'));
        }
    }).catch(err => {
        console.error(err);
        alert('Erro de rede ao atualizar status');
    });
}

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>