<?php
/**
 * Meus Pedidos - MontaLoja
 * Página para visualizar histórico de pedidos do cliente
 */

require_once __DIR__ . '/includes/store-config.php';

// Verificar se está logado
if (!isCustomerLoggedIn()) {
    $_SESSION['redirect_after_login'] = storeUrl('meus-pedidos');
    header("Location: " . storeUrl('entrar'));
    exit;
}

$customer = getLoggedCustomer();
$customerId = $customer['id'];
$customerEmail = $customer['email'] ?? '';

// Buscar pedidos do cliente
$ordersStmt = $pdo->prepare("
    SELECT o.*, 
           (SELECT COUNT(*) FROM order_items WHERE order_id = o.id) as items_count
    FROM orders o 
    WHERE o.store_id = ? AND (o.customer_id = ? OR o.customer_email = ?) 
    ORDER BY o.created_at DESC
");
$ordersStmt->execute([$currentStoreId, $customerId, $customerEmail]);
$orders = $ordersStmt->fetchAll(PDO::FETCH_ASSOC);

// Função para traduzir status com ícones
function getStatusInfo($status) {
    $statusMap = [
        'pending' => ['label' => 'Pendente', 'icon' => 'solar:clock-circle-bold', 'color' => '#F59E0B', 'bg' => '#FEF3C7'],
        'sent_whatsapp' => ['label' => 'Aguardando Confirmação', 'icon' => 'solar:chat-round-dots-bold', 'color' => '#F59E0B', 'bg' => '#FEF3C7'],
        'awaiting_payment' => ['label' => 'Aguardando Pagamento', 'icon' => 'solar:wallet-bold', 'color' => '#F59E0B', 'bg' => '#FEF3C7'],
        'confirmed' => ['label' => 'Confirmado', 'icon' => 'solar:check-circle-bold', 'color' => '#3B82F6', 'bg' => '#DBEAFE'],
        'paid' => ['label' => 'Pago', 'icon' => 'solar:check-square-bold', 'color' => '#10B981', 'bg' => '#D1FAE5'],
        'processing' => ['label' => 'Em Preparação', 'icon' => 'solar:box-bold', 'color' => '#8B5CF6', 'bg' => '#EDE9FE'],
        'preparing' => ['label' => 'Preparando', 'icon' => 'solar:chef-hat-bold', 'color' => '#8B5CF6', 'bg' => '#EDE9FE'],
        'shipped' => ['label' => 'Enviado', 'icon' => 'solar:delivery-bold', 'color' => '#06B6D4', 'bg' => '#CFFAFE'],
        'out_for_delivery' => ['label' => 'Saiu para Entrega', 'icon' => 'solar:scooter-bold', 'color' => '#0891B2', 'bg' => '#CFFAFE'],
        'delivered' => ['label' => 'Entregue', 'icon' => 'solar:verified-check-bold', 'color' => '#059669', 'bg' => '#D1FAE5'],
        'completed' => ['label' => 'Concluído', 'icon' => 'solar:check-circle-bold', 'color' => '#059669', 'bg' => '#D1FAE5'],
        'cancelled' => ['label' => 'Cancelado', 'icon' => 'solar:close-circle-bold', 'color' => '#EF4444', 'bg' => '#FEE2E2'],
        'canceled' => ['label' => 'Cancelado', 'icon' => 'solar:close-circle-bold', 'color' => '#EF4444', 'bg' => '#FEE2E2'],
        'refunded' => ['label' => 'Reembolsado', 'icon' => 'solar:undo-left-bold', 'color' => '#6B7280', 'bg' => '#F3F4F6'],
    ];
    return $statusMap[$status] ?? ['label' => ucfirst(str_replace('_', ' ', $status)), 'icon' => 'solar:question-circle-bold', 'color' => '#6B7280', 'bg' => '#F3F4F6'];
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Meus Pedidos - <?php echo htmlspecialchars($storeName); ?></title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/iconify-icon@1.0.7/dist/iconify-icon.min.js"></script>
<link rel="stylesheet" href="/pages/storefront/templates/retail/modern/includes/styles.css?v=1.0.4">
<?php include __DIR__ . "/includes/dynamic-styles.php"; ?>
<style>
/* Dynamic Color Variables from Store Settings */
:root {
    --primary: <?php echo htmlspecialchars($primaryColor ?? '#2563EB'); ?>;
    --primary-soft: <?php echo htmlspecialchars($primaryColor ?? '#2563EB'); ?>14;
    --primary-hover: <?php echo htmlspecialchars($customSettings['colors']['secondary'] ?? $primaryColor ?? '#1D4ED8'); ?>;
    --accent: <?php echo htmlspecialchars($accentColor ?? '#10B981'); ?>;
    --accent-soft: <?php echo htmlspecialchars($accentColor ?? '#10B981'); ?>1A;
    --bg: <?php echo htmlspecialchars($bgColor ?? '#FAFBFC'); ?>;
    --bg-white: <?php echo htmlspecialchars($cardColor ?? '#FFFFFF'); ?>;
    --surface: <?php echo htmlspecialchars($cardColor ?? '#FFFFFF'); ?>;
    --text: <?php echo htmlspecialchars($textColor ?? '#111827'); ?>;
    --text-secondary: <?php echo htmlspecialchars($textSecondary ?? '#6B7280'); ?>;
}

.orders-page {
    max-width: 900px;
    margin: 0 auto;
    padding: 24px 16px;
    min-height: 60vh;
}

/* Header com botão voltar */
.page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 28px;
    flex-wrap: wrap;
    gap: 16px;
}

.page-header h1 {
    font-size: 1.75rem;
    font-weight: 800;
    color: #1F2937;
    display: flex;
    align-items: center;
    gap: 12px;
    margin: 0;
}

.page-header h1 iconify-icon {
    color: var(--primary, #3B82F6);
}

.btn-back {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 10px 20px;
    background: white;
    color: #374151;
    border: 1px solid #E5E7EB;
    border-radius: 12px;
    font-weight: 600;
    font-size: 0.9rem;
    text-decoration: none;
    transition: all 0.2s;
    box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

.btn-back:hover {
    background: #F9FAFB;
    border-color: #D1D5DB;
    color: #1F2937;
    transform: translateX(-2px);
}

.btn-back iconify-icon {
    font-size: 1.1rem;
}

.orders-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.order-card {
    background: white;
    border-radius: 16px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
    overflow: hidden;
    transition: transform 0.2s, box-shadow 0.2s;
    border: 1px solid #F3F4F6;
}

.order-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 24px rgba(0,0,0,0.1);
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 18px 22px;
    background: linear-gradient(135deg, #F8FAFC 0%, #F1F5F9 100%);
    border-bottom: 1px solid #E5E7EB;
}

.order-number {
    font-size: 1.1rem;
    font-weight: 700;
    color: #1F2937;
}

.order-date {
    font-size: 0.85rem;
    color: #6B7280;
    margin-top: 4px;
    display: flex;
    align-items: center;
    gap: 6px;
}

.order-date iconify-icon {
    font-size: 1rem;
}

/* Status elegante */
.order-status {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 8px 16px;
    border-radius: 50px;
    font-size: 0.85rem;
    font-weight: 600;
    box-shadow: 0 2px 4px rgba(0,0,0,0.06);
    transition: transform 0.2s;
}

.order-status:hover {
    transform: scale(1.02);
}

.order-status iconify-icon {
    font-size: 1.1rem;
}

/* Status wrapper com expiração */
.status-wrapper {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 6px;
}

.order-expires {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 0.8rem;
    color: #EF4444;
    font-weight: 600;
    padding: 4px 12px;
    background: #FEE2E2;
    border-radius: 20px;
}

.order-expires iconify-icon {
    font-size: 0.95rem;
}

.order-expires.urgent {
    animation: pulse-red 1.5s infinite;
}

@keyframes pulse-red {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.6; }
}

.order-body {
    padding: 22px;
}

.order-info {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 18px;
}

.info-item {
    display: flex;
    align-items: flex-start;
    gap: 12px;
}

.info-item iconify-icon {
    font-size: 1.3rem;
    color: #9CA3AF;
    flex-shrink: 0;
    margin-top: 2px;
}

.info-label {
    font-size: 0.7rem;
    color: #9CA3AF;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    font-weight: 600;
    margin-bottom: 2px;
}

.info-value {
    font-size: 0.95rem;
    color: #374151;
    font-weight: 500;
}

.order-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 18px 22px;
    background: linear-gradient(135deg, #F8FAFC 0%, #F1F5F9 100%);
    border-top: 1px solid #E5E7EB;
}

.order-total {
    font-size: 1.4rem;
    font-weight: 800;
    color: #059669;
}

.order-total span {
    font-size: 0.85rem;
    font-weight: 500;
    color: #6B7280;
    margin-right: 6px;
}

.order-items-count {
    font-size: 0.85rem;
    color: #6B7280;
    margin-top: 4px;
}

.btn-details {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 12px 24px;
    background: linear-gradient(135deg, #3B82F6 0%, #2563EB 100%);
    color: white;
    border-radius: 12px;
    font-weight: 600;
    font-size: 0.9rem;
    text-decoration: none;
    transition: all 0.2s;
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.btn-details:hover {
    background: linear-gradient(135deg, #2563EB 0%, #1D4ED8 100%);
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(59, 130, 246, 0.4);
}

.btn-details iconify-icon {
    font-size: 1.1rem;
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: 70px 24px;
    background: white;
    border-radius: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
    border: 1px solid #F3F4F6;
}

.empty-state iconify-icon {
    font-size: 5rem;
    color: #D1D5DB;
    margin-bottom: 20px;
}

.empty-state h3 {
    font-size: 1.4rem;
    font-weight: 700;
    color: #374151;
    margin-bottom: 10px;
}

.empty-state p {
    color: #6B7280;
    margin-bottom: 28px;
    font-size: 1rem;
}

.btn-shop {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    padding: 14px 28px;
    background: linear-gradient(135deg, #10B981 0%, #059669 100%);
    color: white;
    border-radius: 14px;
    font-weight: 600;
    font-size: 1rem;
    text-decoration: none;
    transition: all 0.2s;
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

.btn-shop:hover {
    background: linear-gradient(135deg, #059669 0%, #047857 100%);
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(16, 185, 129, 0.4);
}

@media (max-width: 640px) {
    .page-header {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .btn-back {
        order: -1;
        padding: 8px 16px;
        font-size: 0.85rem;
    }
    
    .order-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 14px;
    }
    
    .order-footer {
        flex-direction: column;
        gap: 18px;
        text-align: center;
    }
    
    .btn-details {
        width: 100%;
        justify-content: center;
    }
    
    .order-info {
        grid-template-columns: 1fr;
    }
}
</style>
</head>
<body>

<?php include __DIR__ . '/includes/header.php'; ?>

<div class="orders-page">
    <div class="page-header">
        <h1>
            <iconify-icon icon="solar:bag-check-bold"></iconify-icon>
            Meus Pedidos
        </h1>
        <a href="<?php echo storeUrl('minha-conta'); ?>" class="btn-back">
            <iconify-icon icon="solar:arrow-left-linear"></iconify-icon>
            Voltar
        </a>
    </div>

    <?php if (empty($orders)): ?>
        <div class="empty-state">
            <iconify-icon icon="solar:bag-smile-linear"></iconify-icon>
            <h3>Nenhum pedido encontrado</h3>
            <p>Você ainda não fez nenhum pedido. Que tal começar a comprar?</p>
            <a href="<?php echo storeUrl('produtos'); ?>" class="btn-shop">
                <iconify-icon icon="solar:shop-bold"></iconify-icon>
                Ver Produtos
            </a>
        </div>
    <?php else: ?>
        <div class="orders-list">
            <?php foreach ($orders as $order): 
                $status = getStatusInfo($order['status']);
                
                // Calcular tempo de expiração para pedidos aguardando pagamento
                $expiresIn = null;
                $isUrgent = false;
                if (($order['status'] === 'awaiting_payment' || $order['status'] === 'pending') && !empty($order['expires_at'])) {
                    $expiresAt = strtotime($order['expires_at']);
                    $now = time();
                    $diff = $expiresAt - $now;
                    
                    if ($diff > 0) {
                        $hours = floor($diff / 3600);
                        $minutes = floor(($diff % 3600) / 60);
                        
                        if ($hours > 0) {
                            $expiresIn = $hours . 'h ' . $minutes . 'min';
                        } else {
                            $expiresIn = $minutes . ' min';
                        }
                        
                        // Urgente se menos de 1 hora
                        $isUrgent = $diff < 3600;
                    } else {
                        $expiresIn = 'Expirado';
                        $isUrgent = true;
                    }
                }
            ?>
            <div class="order-card">
                <div class="order-header">
                    <div>
                        <div class="order-number">Pedido #<?php echo str_pad($order['id'], 6, '0', STR_PAD_LEFT); ?></div>
                        <div class="order-date">
                            <iconify-icon icon="solar:calendar-linear"></iconify-icon>
                            <?php echo date('d/m/Y \à\s H:i', strtotime($order['created_at'])); ?>
                        </div>
                    </div>
                    <div class="status-wrapper">
                        <div class="order-status" style="background: <?php echo $status['bg']; ?>; color: <?php echo $status['color']; ?>">
                            <iconify-icon icon="<?php echo $status['icon']; ?>"></iconify-icon>
                            <?php echo $status['label']; ?>
                        </div>
                        <?php if ($expiresIn): ?>
                        <div class="order-expires <?php echo $isUrgent ? 'urgent' : ''; ?>">
                            <iconify-icon icon="solar:alarm-bold"></iconify-icon>
                            Expira em <?php echo $expiresIn; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="order-body">
                    <div class="order-info">
                        <div class="info-item">
                            <iconify-icon icon="solar:user-bold"></iconify-icon>
                            <div>
                                <div class="info-label">Cliente</div>
                                <div class="info-value"><?php echo htmlspecialchars($order['customer_name']); ?></div>
                            </div>
                        </div>
                        
                        <?php if (!empty($order['delivery_address'])): ?>
                        <div class="info-item">
                            <iconify-icon icon="solar:map-point-bold"></iconify-icon>
                            <div>
                                <div class="info-label">Endereço</div>
                                <div class="info-value"><?php echo htmlspecialchars($order['delivery_address']); ?></div>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <?php if (!empty($order['payment_method'])): ?>
                        <div class="info-item">
                            <iconify-icon icon="solar:card-bold"></iconify-icon>
                            <div>
                                <div class="info-label">Pagamento</div>
                                <div class="info-value"><?php echo htmlspecialchars(ucfirst($order['payment_method'])); ?></div>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="order-footer">
                    <div>
                        <div class="order-total">
                            <span>Total:</span>
                            R$ <?php echo number_format($order['total_amount'], 2, ',', '.'); ?>
                        </div>
                        <div class="order-items-count">
                            <?php echo $order['items_count']; ?> <?php echo $order['items_count'] == 1 ? 'item' : 'itens'; ?>
                        </div>
                    </div>
                    <a href="<?php echo storeUrl('pedido/' . $order['id']); ?>" class="btn-details">
                        <iconify-icon icon="solar:eye-bold"></iconify-icon>
                        Ver Detalhes
                    </a>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>

</body>
</html>
