<?php
/**
 * Minha Conta - MontaLoja
 * Dashboard do cliente logado
 */

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

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

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

// Buscar dados completos do cliente
$stmt = $pdo->prepare("SELECT * FROM customers WHERE id = ? AND store_id = ?");
$stmt->execute([$customerId, $currentStoreId]);
$customerData = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$customerData) {
    session_destroy();
    header("Location: " . storeUrl('entrar'));
    exit;
}

// Buscar resumo de pedidos
$ordersStmt = $pdo->prepare("SELECT COUNT(*) as total, COALESCE(SUM(total_amount), 0) as valor_total FROM orders WHERE customer_id = ? AND store_id = ?");
$ordersStmt->execute([$customerId, $currentStoreId]);
$ordersStats = $ordersStmt->fetch(PDO::FETCH_ASSOC);

// Filtro de período para pedidos
$filterPeriod = $_GET["periodo"] ?? "todos";
$filterStatus = $_GET["status"] ?? "todos";

// Construir query com filtros
// Construir query com filtros (Igual ao meus-pedidos.php)
$ordersSql = "SELECT * FROM orders WHERE store_id = ? AND (customer_id = ? OR customer_email = ?)";
$ordersParams = [$currentStoreId, $customerId, $customer['email']];

// Filtro de período
switch ($filterPeriod) {
    case "7dias":
        $ordersSql .= " AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
        break;
    case "30dias":
        $ordersSql .= " AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
        break;
    case "90dias":
        $ordersSql .= " AND created_at >= DATE_SUB(NOW(), INTERVAL 90 DAY)";
        break;
    case "6meses":
        $ordersSql .= " AND created_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH)";
        break;
    case "1ano":
        $ordersSql .= " AND created_at >= DATE_SUB(NOW(), INTERVAL 1 YEAR)";
        break;
}

// Filtro de status
if ($filterStatus !== "todos") {
    $ordersSql .= " AND status = ?";
    $ordersParams[] = $filterStatus;
}

$ordersSql .= " ORDER BY created_at DESC";

$recentOrdersStmt = $pdo->prepare($ordersSql);
$recentOrdersStmt->execute($ordersParams);
$recentOrders = $recentOrdersStmt->fetchAll(PDO::FETCH_ASSOC);


// Buscar endereços
$addressesStmt = $pdo->prepare("SELECT COUNT(*) as total FROM customer_addresses WHERE customer_id = ?");
$addressesStmt->execute([$customerId]);
$addressCount = $addressesStmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;

// Função para traduzir status com ícones - IGUAL à página de pedidos
function getStatusInfo($status) {
    $statusMap = [
        'pending' => ['label' => 'Pendente', 'icon' => 'solar:clock-circle-bold', 'color' => '#F59E0B', 'bg' => '#FEF3C7'],
        'sent_whatsapp' => ['label' => 'Aguardando', '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'],
        'cart_abandoned' => ['label' => 'Abandonado', 'icon' => 'solar:cart-cross-bold', 'color' => '#6B7280', 'bg' => '#F3F4F6'],
        '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>Minha Conta - <?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'); ?>;
}

:root {
    --primary: <?php echo $primaryColor; ?>;
    --primary-soft: <?php echo $primaryColor; ?>15;
    --bg: <?php echo $bgColor; ?>;
    --text: <?php echo $textColor; ?>;
    --text-secondary: #6B7280;
    --muted: #9CA3AF;
    --surface: #FFFFFF;
    --surface-hover: #F9FAFB;
    --border: #E5E7EB;
    --radius: 12px;
    --radius-lg: 16px;
    --shadow: 0 1px 3px rgba(0,0,0,0.1);
}

body {
    font-family: 'Plus Jakarta Sans', sans-serif;
    background: var(--bg);
    color: var(--text);
    margin: 0;
}

.main-content {
    padding: 24px;
    max-width: 1200px;
    margin: 0 auto;
}

.page-header {
    margin-bottom: 32px;
}

.page-title {
    font-size: 1.75rem;
    font-weight: 800;
    margin-bottom: 8px;
}

.page-subtitle {
    color: var(--text-secondary);
}

.account-grid {
    display: grid;
    grid-template-columns: 260px 1fr;
    gap: 24px;
}

/* Sidebar */
.account-sidebar {
    background: var(--surface);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border);
    overflow: hidden;
    height: fit-content;
}

.profile-card {
    padding: 24px;
    text-align: center;
    border-bottom: 1px solid var(--border);
}

.profile-avatar {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: var(--primary-soft);
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 16px;
    font-size: 2rem;
    font-weight: 700;
    color: var(--primary);
}

.profile-name {
    font-weight: 700;
    font-size: 1.1rem;
    margin-bottom: 4px;
}

.profile-email {
    color: var(--text-secondary);
    font-size: 0.9rem;
}

.account-nav {
    padding: 12px 0;
}

.nav-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 14px 24px;
    text-decoration: none;
    color: var(--text);
    transition: all 0.2s;
    font-weight: 500;
}

.nav-item:hover {
    background: var(--surface-hover);
    color: var(--primary);
}

.nav-item.active {
    background: var(--primary-soft);
    color: var(--primary);
    border-right: 3px solid var(--primary);
}

.nav-item iconify-icon {
    font-size: 1.2rem;
    color: inherit;
}

/* Main Content */
.account-main {
    display: flex;
    flex-direction: column;
    gap: 24px;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
}

.stat-card {
    background: var(--surface);
    border-radius: var(--radius);
    border: 1px solid var(--border);
    padding: 20px;
}

.stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 16px;
    font-size: 1.5rem;
}

.stat-icon.orders { background: #EEF2FF; color: #4F46E5; }
.stat-icon.total { background: #ECFDF5; color: #10B981; }
.stat-icon.addresses { background: #FEF3C7; color: #F59E0B; }

.stat-value {
    font-size: 1.75rem;
    font-weight: 800;
    color: var(--text);
    margin-bottom: 4px;
}

.stat-label {
    color: var(--text-secondary);
    font-size: 0.9rem;
}

/* Quick Actions */
.account-main .quick-actions {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    width: 100%;
}

.account-main .quick-actions .action-btn {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 24px 16px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 12px;
    text-decoration: none;
    color: var(--text);
    transition: all 0.2s;
    text-align: center;
    min-height: 120px;
    box-sizing: border-box;
    width: 100%;
}

.account-main .quick-actions .action-btn:hover {
    border-color: var(--primary);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.account-main .quick-actions .action-btn iconify-icon {
    font-size: 2rem;
    color: var(--primary);
    flex-shrink: 0;
}

.account-main .quick-actions .action-btn span {
    font-weight: 600;
    font-size: 0.85rem;
    line-height: 1.3;
    word-wrap: break-word;
    width: 100%;
}

/* Recent Orders */
.section-card {
    background: var(--surface);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border);
    overflow: hidden;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid var(--border);
}

.section-title {
    font-weight: 700;
    font-size: 1.1rem;
}

.section-link {
    color: var(--primary);
    text-decoration: none;
    font-weight: 600;
    font-size: 0.9rem;
    display: flex;
    align-items: center;
    gap: 4px;
}

.orders-list {
    padding: 8px 0;
}

.order-item {
    display: grid;
    grid-template-columns: 100px 1fr auto auto;
    gap: 16px;
    align-items: center;
    padding: 16px 24px;
    border-bottom: 1px solid var(--border);
    transition: background 0.2s;
}

.order-item:last-child {
    border-bottom: none;
}

.order-item:hover {
    background: var(--surface-hover);
}

.order-id {
    font-weight: 700;
    color: var(--primary);
}

.order-date {
    color: var(--text-secondary);
    font-size: 0.9rem;
}

/* Status elegante - NOVO DESIGN */
.order-status {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 14px;
    border-radius: 50px;
    font-size: 0.8rem;
    font-weight: 600;
    box-shadow: 0 1px 3px rgba(0,0,0,0.06);
    transition: transform 0.2s;
}

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

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

.order-total {
    font-weight: 700;
    font-size: 1.1rem;
}

/* Expira em */
.order-expires {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 0.75rem;
    color: #EF4444;
    margin-top: 4px;
    font-weight: 500;
}

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

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

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

.status-wrapper {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
}

.empty-orders {
    padding: 48px 24px;
    text-align: center;
    color: var(--text-secondary);
}

.empty-orders iconify-icon {
    font-size: 3rem;
    margin-bottom: 16px;
    color: var(--muted);
}

.empty-orders p {
    margin-bottom: 16px;
}

.empty-orders .btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 12px 24px;
    background: var(--primary);
    color: white;
    border-radius: var(--radius);
    text-decoration: none;
    font-weight: 600;
}

/* Responsivo - Tablets */
@media (max-width: 992px) {
    .main-content {
        padding: 20px;
    }

    .account-grid {
        grid-template-columns: 220px 1fr;
        gap: 20px;
    }

    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }

    .account-main .quick-actions {
        grid-template-columns: repeat(2, 1fr);
    }
}

/* Responsivo - Mobile */
@media (max-width: 768px) {
    .main-content {
        padding: 16px;
    }

    .page-header {
        margin-bottom: 24px;
    }

    .page-title {
        font-size: 1.4rem;
    }

    .page-subtitle {
        font-size: 0.9rem;
    }

    .account-grid {
        grid-template-columns: 1fr;
        gap: 16px;
    }

    .account-sidebar {
        display: flex;
        flex-direction: column;
    }

    .profile-card {
        padding: 20px 16px;
        width: 100%;
    }

    .profile-avatar {
        width: 64px;
        height: 64px;
        font-size: 1.5rem;
        margin-bottom: 12px;
    }

    .profile-name {
        font-size: 1rem;
    }

    .profile-email {
        font-size: 0.85rem;
    }

    .account-nav {
        width: 100%;
        display: flex;
        overflow-x: auto;
        padding: 0;
        -webkit-overflow-scrolling: touch;
        scrollbar-width: none;
    }

    .account-nav::-webkit-scrollbar {
        display: none;
    }

    .nav-item {
        white-space: nowrap;
        padding: 12px 16px;
        border-right: none !important;
        flex-shrink: 0;
    }

    .nav-item.active {
        border-bottom: 3px solid var(--primary);
        border-right: none;
    }

    .nav-item iconify-icon {
        font-size: 1.1rem;
    }

    .stats-grid {
        grid-template-columns: 1fr;
        gap: 12px;
    }

    .stat-card {
        padding: 16px;
        display: flex;
        align-items: center;
        gap: 16px;
    }

    .stat-icon {
        width: 48px;
        height: 48px;
        margin-bottom: 0;
        flex-shrink: 0;
    }

    .stat-content {
        flex: 1;
    }

    .stat-value {
        font-size: 1.4rem;
    }

    .stat-label {
        font-size: 0.85rem;
    }

    .account-main .quick-actions {
        grid-template-columns: repeat(2, 1fr);
        gap: 12px;
    }

    .account-main .quick-actions .action-btn {
        padding: 20px 12px;
        min-height: 100px;
        gap: 10px;
    }

    .account-main .quick-actions .action-btn iconify-icon {
        font-size: 1.6rem;
    }

    .account-main .quick-actions .action-btn span {
        font-size: 0.8rem;
    }

    .section-header {
        padding: 16px;
        flex-wrap: wrap;
        gap: 8px;
    }

    .section-title {
        font-size: 1rem;
    }

    .section-link {
        font-size: 0.85rem;
    }

    .order-item {
        grid-template-columns: 1fr 1fr;
        gap: 8px;
        padding: 14px 16px;
    }

    .order-id {
        font-size: 0.95rem;
    }

    .order-date {
        font-size: 0.8rem;
        text-align: right;
    }

    .order-status {
        padding: 5px 10px;
        font-size: 0.75rem;
    }

    .order-total {
        font-size: 1rem;
        text-align: right;
    }

    .empty-orders {
        padding: 36px 16px;
    }

    .empty-orders iconify-icon {
        font-size: 2.5rem;
    }

    .empty-orders .btn {
        padding: 10px 20px;
        font-size: 0.9rem;
    }
}

/* Responsivo - Mobile pequeno */
@media (max-width: 400px) {
    .main-content {
        padding: 12px;
    }

    .page-title {
        font-size: 1.2rem;
    }

    .profile-card {
        padding: 16px 12px;
    }

    .profile-avatar {
        width: 56px;
        height: 56px;
        font-size: 1.3rem;
    }

    .nav-item {
        padding: 10px 12px;
        font-size: 0.85rem;
    }

    .stat-card {
        padding: 14px;
    }

    .stat-icon {
        width: 40px;
        height: 40px;
        font-size: 1.2rem;
    }

    .stat-value {
        font-size: 1.2rem;
    }

    .account-main .quick-actions {
        gap: 10px;
    }

    .account-main .quick-actions .action-btn {
        padding: 16px 10px;
        min-height: 90px;
    }

    .account-main .quick-actions .action-btn iconify-icon {
        font-size: 1.4rem;
    }

    .account-main .quick-actions .action-btn span {
        font-size: 0.75rem;
    }

    .order-item {
        padding: 12px;
    }
}
/* Filtros de pedidos */
.filter-select {
    padding: 0.5rem 1rem;
    border: 1px solid var(--border, #e5e7eb);
    border-radius: 8px;
    background: var(--surface, #fff);
    color: var(--text, #111827);
    font-size: 0.875rem;
    font-family: inherit;
    cursor: pointer;
    outline: none;
    transition: all 0.2s ease;
    min-width: 140px;
}
.filter-select:hover {
    border-color: var(--primary);
}
.filter-select:focus {
    border-color: var(--primary);
    box-shadow: 0 0 0 3px var(--primary-soft, rgba(37, 99, 235, 0.1));
}
.orders-filters {
    margin-left: auto;
}
@media (max-width: 768px) {
    .orders-filters {
        width: 100%;
        margin-left: 0;
    }
    .filter-select {
        flex: 1;
        min-width: 120px;
    }
}

</style>
</head>
<body>

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

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

<main class="main-content">
    <div class="page-header">
        <h1 class="page-title">Minha Conta</h1>
        <p class="page-subtitle">Gerencie suas informações, pedidos e endereços</p>
    </div>

    <div class="account-grid">
        <!-- Sidebar -->
        <aside class="account-sidebar">
            <div class="profile-card">
                <div class="profile-avatar">
                    <?php echo strtoupper(substr($customerData['name'] ?? 'U', 0, 1)); ?>
                </div>
                <div class="profile-name"><?php echo htmlspecialchars($customerData['name'] ?? 'Cliente'); ?></div>
                <div class="profile-email"><?php echo htmlspecialchars($customerData['email'] ?? ''); ?></div>
            </div>
            <nav class="account-nav">
                <a href="<?php echo storeUrl('minha-conta'); ?>" class="nav-item active">
                    <iconify-icon icon="solar:home-2-bold"></iconify-icon>
                    Visão Geral
                </a>
                <a href="<?php echo storeUrl('meus-pedidos'); ?>" class="nav-item">
                    <iconify-icon icon="solar:bag-5-bold"></iconify-icon>
                    Meus Pedidos
                </a>
                <a href="<?php echo storeUrl('meus-enderecos'); ?>" class="nav-item">
                    <iconify-icon icon="solar:map-point-bold"></iconify-icon>
                    Meus Endereços
                </a>
                <a href="<?php echo storeUrl('meus-dados'); ?>" class="nav-item">
                    <iconify-icon icon="solar:user-bold"></iconify-icon>
                    Meus Dados
                </a>
                <a href="<?php echo storeUrl('alterar-senha'); ?>" class="nav-item">
                    <iconify-icon icon="solar:lock-bold"></iconify-icon>
                    Alterar Senha
                </a>
                <a href="<?php echo storeUrl('sair'); ?>" class="nav-item">
                    <iconify-icon icon="solar:logout-2-bold"></iconify-icon>
                    Sair
                </a>
            </nav>
        </aside>

        <!-- Main Content -->
        <div class="account-main">
            <!-- Stats -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon orders">
                        <iconify-icon icon="solar:bag-5-bold"></iconify-icon>
                    </div>
                    <div class="stat-value"><?php echo $ordersStats['total'] ?? 0; ?></div>
                    <div class="stat-label">Pedidos realizados</div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon total">
                        <iconify-icon icon="solar:wallet-money-bold"></iconify-icon>
                    </div>
                    <div class="stat-value">R$ <?php echo number_format(($ordersStats['valor_total'] ?? 0), 2, ',', '.'); ?></div>
                    <div class="stat-label">Total em compras</div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon addresses">
                        <iconify-icon icon="solar:map-point-bold"></iconify-icon>
                    </div>
                    <div class="stat-value"><?php echo $addressCount; ?></div>
                    <div class="stat-label">Endereços cadastrados</div>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="quick-actions">
                <a href="<?php echo storeUrl(); ?>" class="action-btn">
                    <iconify-icon icon="solar:shop-bold"></iconify-icon>
                    <span>Continuar Comprando</span>
                </a>
                <a href="<?php echo storeUrl('meus-pedidos'); ?>" class="action-btn">
                    <iconify-icon icon="solar:box-bold"></iconify-icon>
                    <span>Rastrear Pedido</span>
                </a>
                <a href="<?php echo storeUrl('meus-enderecos'); ?>" class="action-btn">
                    <iconify-icon icon="solar:map-point-add-bold"></iconify-icon>
                    <span>Novo Endereço</span>
                </a>
                <a href="<?php echo storeUrl('meus-dados'); ?>" class="action-btn">
                    <iconify-icon icon="solar:user-id-bold"></iconify-icon>
                    <span>Editar Perfil</span>
                </a>
            </div>

            <!-- Recent Orders -->
            <div class="section-card">
            <!-- Recent Orders -->
            <div class="section-card">
                <div class="section-header" style="flex-wrap: wrap; gap: 1rem;">
                    <h2 class="section-title">Histórico de Pedidos</h2>
                    <div class="orders-filters" style="display: flex; gap: 0.5rem; flex-wrap: wrap; align-items: center;">
                        <select id="filterPeriod" class="filter-select" onchange="applyFilters()">
                            <option value="todos" <?php echo $filterPeriod === 'todos' ? 'selected' : ''; ?>>Todos os períodos</option>
                            <option value="7dias" <?php echo $filterPeriod === '7dias' ? 'selected' : ''; ?>>Últimos 7 dias</option>
                            <option value="30dias" <?php echo $filterPeriod === '30dias' ? 'selected' : ''; ?>>Últimos 30 dias</option>
                            <option value="90dias" <?php echo $filterPeriod === '90dias' ? 'selected' : ''; ?>>Últimos 3 meses</option>
                            <option value="6meses" <?php echo $filterPeriod === '6meses' ? 'selected' : ''; ?>>Últimos 6 meses</option>
                            <option value="1ano" <?php echo $filterPeriod === '1ano' ? 'selected' : ''; ?>>Último ano</option>
                        </select>
                        <select id="filterStatus" class="filter-select" onchange="applyFilters()">
                            <option value="todos" <?php echo $filterStatus === 'todos' ? 'selected' : ''; ?>>Todos os status</option>
                            <option value="pending" <?php echo $filterStatus === 'pending' ? 'selected' : ''; ?>>Pendente</option>
                            <option value="confirmed" <?php echo $filterStatus === 'confirmed' ? 'selected' : ''; ?>>Confirmado</option>
                            <option value="paid" <?php echo $filterStatus === 'paid' ? 'selected' : ''; ?>>Pago</option>
                            <option value="shipped" <?php echo $filterStatus === 'shipped' ? 'selected' : ''; ?>>Enviado</option>
                            <option value="delivered" <?php echo $filterStatus === 'delivered' ? 'selected' : ''; ?>>Entregue</option>
                            <option value="completed" <?php echo $filterStatus === 'completed' ? 'selected' : ''; ?>>Concluído</option>
                            <option value="cancelled" <?php echo $filterStatus === 'cancelled' ? 'selected' : ''; ?>>Cancelado</option>
                        </select>
                    </div>
                    <a href="<?php echo storeUrl('meus-pedidos'); ?>" class="section-link">
                        Ver todos
                        <iconify-icon icon="solar:arrow-right-linear"></iconify-icon>
                    </a>
                </div>
                <div class="orders-list">
                    <?php if (count($recentOrders) > 0): ?>
                        <?php foreach ($recentOrders as $order): 
                            $status = getStatusInfo($order['status'] ?? 'pending');
                            
                            // 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-item">
                            <div>
                                <div class="order-id">#<?php echo str_pad($order['id'], 5, '0', STR_PAD_LEFT); ?></div>
                            </div>
                            <div class="order-date">
                                <?php echo date('d/m/Y H:i', strtotime($order['created_at'])); ?>
                            </div>
                            <div class="status-wrapper">
                                <span 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']; ?>
                                </span>
                                <?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 class="order-total">
                                R$ <?php echo number_format($order['total_amount'] ?? 0, 2, ',', '.'); ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="empty-orders">
                            <iconify-icon icon="solar:bag-heart-bold"></iconify-icon>
                            <p>Você ainda não fez nenhum pedido</p>
                            <a href="<?php echo storeUrl(); ?>" class="btn">
                                <iconify-icon icon="solar:shop-bold"></iconify-icon>
                                Começar a comprar
                            </a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</main>

<?php include __DIR__ . '/includes/footer.php'; ?>
<script>
function applyFilters() {
    const periodo = document.getElementById("filterPeriod").value;
    const status = document.getElementById("filterStatus").value;
    const baseUrl = window.location.pathname;
    const params = new URLSearchParams();
    
    if (periodo !== "todos") {
        params.set("periodo", periodo);
    }
    if (status !== "todos") {
        params.set("status", status);
    }
    
    const queryString = params.toString();
    window.location.href = baseUrl + (queryString ? "?" + queryString : "");
}
</script>

</body>
</html>
