<?php
$pageTitle = "Meus Pedidos - CATÁLOGO 44";
include 'header.php';
include '../adm/config/db.php';

// Segurança: Verificar se está logado
if (!isset($_SESSION['usuario_id'])) {
    echo "<script>window.location.href='login.php';</script>";
    exit;
}

$uId = $_SESSION['usuario_id'];

// Buscar pedidos do usuário
$sql = "SELECT p.*, 
        (SELECT COUNT(*) FROM pedidos_itens WHERE pedido_id = p.id) as total_itens
        FROM pedidos p 
        WHERE p.usuario_id = ? 
        ORDER BY p.id DESC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $uId);
$stmt->execute();
$result = $stmt->get_result();

// Função para formatar status
function formatarStatus($status) {
    switch ($status) {
        case 'pendente': 
            return '<span class="badge bg-warning-subtle text-warning p-2 fw-bold" style="font-size: 12px;">Pendente</span>';
        case 'processando': 
            return '<span class="badge bg-info-subtle text-info p-2 fw-bold" style="font-size: 12px;">Processando</span>';
        case 'pago': 
            return '<span class="badge bg-primary-subtle text-primary p-2 fw-bold" style="font-size: 12px;">Pago</span>';
        case 'enviado': 
            return '<span class="badge bg-purple-subtle text-purple p-2 fw-bold" style="font-size: 12px;">Enviado</span>';
        case 'entregue': 
            return '<span class="badge bg-success-subtle text-success p-2 fw-bold" style="font-size: 12px;">Entregue</span>';
        case 'cancelado': 
            return '<span class="badge bg-danger-subtle text-danger p-2 fw-bold" style="font-size: 12px;">Cancelado</span>';
        default: 
            return '<span class="badge bg-secondary-subtle text-secondary p-2 fw-bold" style="font-size: 12px;">'.ucfirst($status).'</span>';
    }
}
?>
<style>
    .bg-warning-subtle { background-color: rgba(255, 193, 7, 0.1) !important; }
    .bg-info-subtle { background-color: rgba(13, 202, 240, 0.1) !important; }
    .bg-primary-subtle { background-color: rgba(13, 110, 253, 0.1) !important; }
    .bg-success-subtle { background-color: rgba(25, 135, 84, 0.1) !important; }
    .bg-danger-subtle { background-color: rgba(220, 53, 69, 0.1) !important; }
    .bg-purple-subtle { background-color: rgba(111, 66, 193, 0.1) !important; }
    .bg-secondary-subtle { background-color: rgba(108, 117, 125, 0.1) !important; }

    .text-warning { color: #ffc107 !important; }
    .text-info { color: #0dcaf0 !important; }
    .text-primary { color: #0d6efd !important; }
    .text-success { color: #198754 !important; }
    .text-danger { color: #dc3545 !important; }
    .text-purple { color: #6f42c1 !important; }
    .text-secondary { color: #6c757d !important; }
</style>

    <!-- Hero Start -->
    <div class="container-fluid bg-primary py-5 hero-header mb-5">
        <div class="row py-3">
            <div class="col-12 text-center">
                <h1 class="display-3 text-white animated zoomIn">Seus Pedidos</h1>
                <a href="index.php" class="h4 text-white">Início</a>
                <i class="far fa-circle text-white px-2"></i>
                <span class="h4 text-white">Meus Pedidos</span>
            </div>
        </div>
    </div>
    <!-- Hero End -->

    <div class="container-fluid py-5">
        <div class="container">
            <div class="row g-5 justify-content-center">
                <div class="col-lg-10">
                    <div class="bg-light rounded p-5 shadow-sm">
                        <div class="section-title mb-5">
                            <h5 class="position-relative d-inline-block text-primary text-uppercase">Histórico</h5>
                            <h1 class="display-6 mb-0">Acompanhe suas compras</h1>
                        </div>

                        <?php if ($result->num_rows > 0): ?>
                            <div class="table-responsive">
                                <table class="table table-hover align-middle">
                                    <thead class="table-dark">
                                        <tr>
                                            <th class="py-3 px-4">Pedido</th>
                                            <th class="py-3 px-4">Data</th>
                                            <th class="py-3 px-4">Itens</th>
                                            <th class="py-3 px-4">Total</th>
                                            <th class="py-3 px-4">Status</th>
                                            <th class="py-3 px-4">Ação</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php while ($pedido = $result->fetch_assoc()): ?>
                                            <tr>
                                                <td class="px-4 fw-bold text-primary">#<?= $pedido['id'] ?></td>
                                                <td class="px-4 text-muted"><?= date('d/m/Y H:i', strtotime($pedido['criado_em'])) ?></td>
                                                <td class="px-4"><?= $pedido['total_itens'] ?> produto(s)</td>
                                                <td class="px-4 fw-bold">R$ <?= number_format($pedido['total'], 2, ',', '.') ?></td>
                                                <td class="px-4"><?= formatarStatus($pedido['status']) ?></td>
                                                <td class="px-4">
                                                    <?php if ($pedido['status'] == 'pendente' && !empty($pedido['preference_id'])): ?>
                                                        <a href="https://www.mercadopago.com.br/checkout/v1/redirect?pref_id=<?= $pedido['preference_id'] ?>" class="btn btn-sm btn-primary px-3 shadow-sm" target="_blank">Pagar Agora</a>
                                                    <?php else: ?>
                                                        <span class="text-muted small">Sem ações</span>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endwhile; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-5">
                                <i class="bi bi-cart-x display-1 text-muted mb-4"></i>
                                <h3>Você ainda não realizou nenhum pedido.</h3>
                                <p class="mb-4">Explore nosso catálogo e encontre os melhores produtos!</p>
                                <a href="index.php" class="btn btn-primary py-3 px-5">Ver Produtos Agora</a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

<?php 
$marginTop = 'style="margin-top: -75px;"'; 
include 'footer.php'; 
?>
