<?php
/**
 * Página de Pedidos - MontaLoja SaaS
 * Gerenciamento de pedidos com integração WhatsApp
 */
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/check-access.php';

$pdo = getDB();
$userId = $_SESSION['user_id'] ?? null;
$storeId = $_SESSION['store_id'] ?? null;

if (!$userId && !$storeId) {
    header('Location: /pages/login.php');
    exit;
}

$userStmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$userStmt->execute([$userId]);
$user = $userStmt->fetch(PDO::FETCH_ASSOC);

$storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ?");
$storeStmt->execute([$storeId]);
$store = $storeStmt->fetch(PDO::FETCH_ASSOC);

// Processar ações
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'update_status' && isset($_POST['order_id'], $_POST['status'])) {
        $orderId = intval($_POST['order_id']);
        $newStatus = $_POST['status'];
        $validStatuses = ['pending', 'awaiting_payment', 'paid', 'preparing', 'shipped', 'delivered', 'cancelled'];

        if (in_array($newStatus, $validStatuses)) {
            try {
                $pdo->beginTransaction();
                $orderStmt = $pdo->prepare("SELECT * FROM orders WHERE id = ? AND store_id = ?");
                $orderStmt->execute([$orderId, $storeId]);
                $order = $orderStmt->fetch(PDO::FETCH_ASSOC);

                if ($order) {
                    $oldStatus = $order['status'];
                    if ($newStatus === 'cancelled' && !in_array($oldStatus, ['cancelled', 'expired'])) {
                        $itemsStmt = $pdo->prepare("SELECT product_id, quantity FROM order_items WHERE order_id = ?");
                        $itemsStmt->execute([$orderId]);
                        $items = $itemsStmt->fetchAll(PDO::FETCH_ASSOC);
                        foreach ($items as $item) {
                            $restoreStmt = $pdo->prepare("UPDATE products SET stock_quantity = stock_quantity + ? WHERE id = ?");
                            $restoreStmt->execute([$item['quantity'], $item['product_id']]);
                        }
                    }
                    $updateStmt = $pdo->prepare("UPDATE orders SET status = ?, updated_at = NOW() WHERE id = ? AND store_id = ?");
                    $updateStmt->execute([$newStatus, $orderId, $storeId]);
                    $pdo->commit();
                    $_SESSION['flash_message'] = 'Status do pedido atualizado com sucesso!';
                    $_SESSION['flash_type'] = 'success';
                } else {
                    $pdo->rollBack();
                    $_SESSION['flash_message'] = 'Pedido não encontrado.';
                    $_SESSION['flash_type'] = 'error';
                }
            } catch (Exception $e) {
                $pdo->rollBack();
                $_SESSION['flash_message'] = 'Erro ao atualizar status: ' . $e->getMessage();
                $_SESSION['flash_type'] = 'error';
            }
        }
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
}

// Verificar mensagens flash
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    $messageType = $_SESSION['flash_type'] ?? 'success';
    unset($_SESSION['flash_message'], $_SESSION['flash_type']);
}

// Filtros
$statusFilter = $_GET['status'] ?? '';
$searchFilter = trim($_GET['search'] ?? '');
$dateFilter = $_GET['date'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Construir query
$where = ['o.store_id = ?'];
$params = [$storeId];

if ($statusFilter) {
    $where[] = 'o.status = ?';
    $params[] = $statusFilter;
}

if ($searchFilter) {
    $where[] = '(o.customer_name LIKE ? OR o.customer_phone LIKE ? OR o.id LIKE ?)';
    $searchTerm = "%$searchFilter%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

if ($dateFilter) {
    $where[] = 'DATE(o.created_at) = ?';
    $params[] = $dateFilter;
}

$whereClause = implode(' AND ', $where);

// Contar pedidos por status
$statusCountStmt = $pdo->prepare("SELECT status, COUNT(*) as count FROM orders WHERE store_id = ? GROUP BY status");
$statusCountStmt->execute([$storeId]);
$statusCounts = [];
while ($row = $statusCountStmt->fetch(PDO::FETCH_ASSOC)) {
    $statusCounts[$row['status']] = $row['count'];
}

// Buscar total
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM orders o WHERE $whereClause");
$countStmt->execute($params);
$total = $countStmt->fetchColumn();
$totalPages = ceil($total / $perPage);

// Buscar pedidos
$ordersStmt = $pdo->prepare("SELECT o.* FROM orders o WHERE $whereClause ORDER BY o.created_at DESC LIMIT $perPage OFFSET $offset");
$ordersStmt->execute($params);
$orders = $ordersStmt->fetchAll(PDO::FETCH_ASSOC);

// Buscar itens dos pedidos
foreach ($orders as &$order) {
    $itemsStmt = $pdo->prepare("SELECT oi.*, p.name as product_name, p.image_url FROM order_items oi LEFT JOIN products p ON oi.product_id = p.id WHERE oi.order_id = ?");
    $itemsStmt->execute([$order['id']]);
    $order['items'] = $itemsStmt->fetchAll(PDO::FETCH_ASSOC);
}
unset($order);

// Labels e cores de status
$statusLabels = [
    'pending' => 'Pendente',
    'awaiting_payment' => 'Aguardando Pgto',
    'paid' => 'Pago',
    'preparing' => 'Preparando',
    'shipped' => 'Enviado',
    'delivered' => 'Entregue',
    'cancelled' => 'Cancelado',
    'expired' => 'Expirado'
];

$statusIcons = [
    'pending' => 'solar:clock-circle-bold',
    'awaiting_payment' => 'solar:wallet-bold',
    'paid' => 'solar:check-circle-bold',
    'preparing' => 'solar:box-bold',
    'shipped' => 'solar:delivery-bold',
    'delivered' => 'solar:verified-check-bold',
    'cancelled' => 'solar:close-circle-bold',
    'expired' => 'solar:alarm-bold'
];

$pageTitle = 'Pedidos';
include __DIR__ . '/../includes/dashboard-header.php';
include __DIR__ . '/../includes/dashboard-styles.php';
?>



<style>
/* Card Principal */
.order-card {
    background: var(--bg-card);
    border-radius: 16px;
    overflow: hidden;
    border: 1px solid var(--border);
    transition: all 0.3s ease;
    display: flex;
    flex-direction: column;
}

.order-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
    border-color: var(--primary);
}

/* Header */
.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.875rem 1rem;
    background: var(--bg-darker);
    border-bottom: 1px solid var(--border);
}

.order-id-badge {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

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

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

/* Status Badge */
.order-status-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.35rem;
    padding: 0.35rem 0.75rem;
    border-radius: 20px;
    font-size: 0.7rem;
    font-weight: 600;
    text-transform: uppercase;
}

.order-status-badge.pending, .order-status-badge.awaiting_payment { background: rgba(245,158,11,0.15); color: #D97706; }
.order-status-badge.paid { background: rgba(16,185,129,0.15); color: #059669; }
.order-status-badge.preparing { background: rgba(59,130,246,0.15); color: #2563EB; }
.order-status-badge.shipped { background: rgba(139,92,246,0.15); color: #7C3AED; }
.order-status-badge.delivered { background: rgba(16,185,129,0.15); color: #059669; }
.order-status-badge.cancelled, .order-status-badge.expired { background: rgba(107,114,128,0.15); color: #6B7280; }

/* Body */
.order-body {
    padding: 1rem;
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 0.875rem;
    
}

/* Cliente */
.order-client {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    
}

.client-avatar {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    background: linear-gradient(135deg, var(--primary));
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    font-size: 1rem;
    flex-shrink: 0;
}

.client-info { flex: 1; min-width: 0; }
.client-name { font-weight: 600; font-size: 0.95rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.client-phone { font-size: 0.8rem; color: var(--text-muted); display: flex; align-items: center; gap: 0.35rem; }

/* WhatsApp Mini */
.whatsapp-mini {
    width: 36px;
    height: 36px;
    border-radius: 10px;
    background: linear-gradient(135deg, #25D366);
    color: white;
    display: flex;
    align-items: center;
    border: 1px solid var(--border);
    justify-content: center;
    text-decoration: none;
    transition: all 0.2s;
}

.whatsapp-mini:hover { transform: scale(1.1); box-shadow: 0 4px 12px rgba(37,211,102,0.4); }
.whatsapp-mini iconify-icon { font-size: 1.25rem; }

/* Items Summary */
.order-items-summary {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.75rem;
    background: var(--bg-darker);
    border-radius: 10px;
}

.items-count { display: flex; align-items: center; gap: 0.5rem; font-size: 0.85rem; color: var(--text-muted); }
.items-count iconify-icon { color: var(--primary); font-size: 1.1rem; }

.items-preview { display: flex; gap: 0.35rem; }
.item-thumb {
    width: 36px;
    height: 36px;
    border-radius: 8px;
    overflow: hidden;
    position: relative;
    border: 2px solid var(--bg-card);
    background: var(--bg-card);
}

.item-thumb img { width: 100%; height: 100%; object-fit: cover; }
.item-thumb .item-qty {
    position: absolute;
    bottom: -2px;
    right: -2px;
    background: var(--primary);
    color: white;
    font-size: 0.65rem;
    font-weight: 700;
    padding: 1px 5px;
    border-radius: 8px;
}

.item-thumb.more {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.75rem;
    font-weight: 600;
    color: var(--text-muted);
}

/* Expire */
.order-expire {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 0.75rem;
    background: rgba(245,158,11,0.1);
    border: 1px solid rgba(245,158,11,0.3);
    border-radius: 8px;
    color: #D97706;
    font-size: 0.8rem;
}

.order-expire.expired { background: rgba(107,114,128,0.1); border-color: rgba(107,114,128,0.3); color: #6B7280; }

/* Note */
.order-note {
    display: flex;
    align-items: flex-start;
    gap: 0.5rem;
    padding: 0.5rem 0.75rem;
    background: rgba(251,191,36,0.1);
    border-radius: 8px;
    color: #92400E;
    font-size: 0.8rem;
}

/* Footer */
.order-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.875rem 1rem;
    background: var(--bg-darker);
    border-top: 1px solid var(--border);
}

.order-total { display: flex; flex-direction: column; }
.total-label { font-size: 0.7rem; color: var(--text-muted); text-transform: uppercase; }
.total-value { font-size: 1.1rem; font-weight: 800; color: var(--success); }

.status-select {
    padding: 0.5rem 0.75rem;
    font-size: 0.8rem;
    border-radius: 8px;
    border: 1px solid var(--border);
    background: var(--bg-card);
    cursor: pointer;
}

/* Grid */
.orders-grid { display: grid; grid-template-columns: 1fr; gap: 1rem; }
@media (min-width: 640px) { .orders-grid { grid-template-columns: repeat(2, 1fr); } }
@media (min-width: 1024px) { .orders-grid { grid-template-columns: repeat(3, 1fr); } }

/* FILTRO STATUS - Design Premium */
.filter-section{background:var(--bg-card);border:1px solid var(--border);border-radius:var(--radius-lg);padding:1.25rem;margin-bottom:1.5rem;box-shadow:var(--shadow);transition:all .2s}
.filter-section:hover{border-color:rgba(var(--primary-rgb), 0.3)}
.filter-header{display:flex;align-items:center;justify-content:space-between;gap:.75rem;margin-bottom:.5rem}
.filter-title{display:flex;align-items:center;gap:.6rem;font-size:.9rem;font-weight:600;color:var(--text-primary);margin:0}
.filter-title iconify-icon{font-size:1.1rem;color:var(--primary);background:var(--primary-light);padding:.35rem;border-radius:8px}
.filter-status-badge{display:none;align-items:center;gap:.3rem;padding:.3rem .7rem;background:linear-gradient(135deg, var(--primary) 0%, #FFD700 100%);border-radius:50px;font-size:.7rem;font-weight:600;color:#000;box-shadow:0 2px 8px rgba(var(--primary-rgb), 0.3)}
.filter-toggle-btn{display:none;align-items:center;justify-content:center;width:36px;height:36px;background:var(--bg-dark);border:1px solid var(--border);border-radius:var(--radius-md);color:var(--text-secondary);cursor:pointer;transition:all .2s}
.filter-toggle-btn:hover,.filter-toggle-btn.active{border-color:var(--primary);color:var(--primary);background:var(--primary-light)}
.filter-toggle-btn iconify-icon{font-size:1.1rem}
.filter-body{display:flex;align-items:center;gap:1rem;margin-top:.75rem;padding-top:.75rem;border-top:1px solid var(--border)}
.filter-scroll{flex:1;overflow:hidden}
.filter-pills{display:flex;gap:.5rem;flex-wrap:wrap}
.filter-pill{display:inline-flex;align-items:center;gap:.4rem;padding:.5rem 1rem;background:var(--bg-dark);border:1px solid var(--border);border-radius:50px;font-size:.8rem;font-weight:500;color:var(--text-secondary);cursor:pointer;transition:all .2s;text-decoration:none;white-space:nowrap}
.filter-pill:hover{border-color:var(--primary);color:var(--primary);background:var(--primary-light);transform:translateY(-1px)}
.filter-pill.active{background:linear-gradient(135deg, var(--primary) 0%, #FFD700 100%);border-color:transparent;color:#000;box-shadow:0 3px 12px rgba(var(--primary-rgb), 0.35);transform:translateY(-1px)}
.filter-pill iconify-icon{font-size:.95rem}
.filter-pill .count{background:rgba(255,255,255,0.35);padding:.15rem .5rem;border-radius:50px;font-size:.7rem;font-weight:700;margin-left:.2rem}
.filter-pill:not(.active) .count{background:var(--bg-card);color:var(--text-muted);border:1px solid var(--border)}

/* TABLET */
@media(max-width:992px){
.filter-body{flex-direction:column;align-items:stretch;gap:.75rem}
.filter-scroll{width:100%}
.filter-pills{flex-wrap:wrap;justify-content:flex-start}
}

/* MOBILE */
@media(max-width:768px){
.filter-status-badge{display:inline-flex}
.filter-section{padding:1rem}
.filter-header{margin-bottom:0}
.filter-toggle-btn{display:flex}
.filter-body{display:none;margin-top:1rem;padding-top:1rem}
.filter-body.show{display:flex}
.filter-pills{gap:.4rem}
.filter-pill{padding:.4rem .7rem;font-size:.75rem}
.filter-pill iconify-icon{font-size:.85rem}
}

/* MOBILE SMALL */
@media(max-width:480px){
.filter-section{padding:.75rem}
.filter-pill{padding:.35rem .55rem;font-size:.7rem}
.filter-pill iconify-icon{display:none}
.filter-status-badge{font-size:.65rem;padding:.25rem .5rem}
.order-footer { flex-direction: column; gap: 0.75rem; }
.order-total { flex-direction: row; justify-content: space-between; width: 100%; }
.status-select { width: 100%; }
.filter-search-input{font-size:.75rem;padding:.4rem .6rem}
}

/* Filter Dates Row - Premium */
.filter-dates{display:flex;align-items:center;gap:.6rem;flex-shrink:0;flex-wrap:wrap}
.filter-dates input[type=date]{padding:.5rem .65rem;background:var(--bg-dark);border:1px solid var(--border);border-radius:50px;color:var(--text-primary);font-size:.8rem;width:140px;transition:all .2s}
.filter-dates input[type=date]:focus{outline:none;border-color:var(--primary);box-shadow:0 0 0 3px var(--primary-light)}
.filter-dates .sep{color:var(--text-muted);font-size:.8rem;white-space:nowrap;font-weight:500}
.filter-dates .btn-apply{display:inline-flex;align-items:center;justify-content:center;width:38px;height:38px;background:linear-gradient(135deg, var(--primary) 0%, #FFD700 100%);border:none;border-radius:50px;color:#000;cursor:pointer;transition:all .2s;box-shadow:0 2px 8px rgba(var(--primary-rgb), 0.3)}
.filter-dates .btn-apply:hover{transform:scale(1.08);box-shadow:0 4px 12px rgba(var(--primary-rgb), 0.4)}
.filter-dates .btn-clear{display:inline-flex;align-items:center;justify-content:center;width:38px;height:38px;background:var(--bg-dark);border:1px solid var(--border);border-radius:50px;color:var(--error);cursor:pointer;text-decoration:none;transition:all .2s}
.filter-dates .btn-clear:hover{background:rgba(239,68,68,0.1);border-color:var(--error);transform:scale(1.05)}

/* Search Input - Premium */
.filter-search-input{flex:1;min-width:180px;height:38px;padding:0 1rem;background:var(--bg-dark);border:1px solid var(--border);border-radius:50px;color:var(--text-primary);font-size:.85rem;transition:all .2s}
.filter-search-input:focus{outline:none;border-color:var(--primary);box-shadow:0 0 0 3px var(--primary-light);background:var(--bg-card)}
.filter-search-input::placeholder{color:var(--text-muted)}
</style>

<main class="main-content">
    <div class="page-header">
        <h1><iconify-icon icon="solar:clipboard-list-bold"></iconify-icon> Pedidos</h1>
        <p>Gerencie os pedidos da sua loja</p>
    </div>

    <?php if ($message): ?>
    <div class="alert alert-<?php echo $messageType; ?>">
        <?php echo $message; ?>
    </div>
    <?php endif; ?>

    <!-- Status Filter - Design Período -->
    <div class="filter-section">
        <div class="filter-header">
            <div style="display:flex;align-items:center;gap:.75rem;flex-wrap:wrap">
                <h3 class="filter-title">
                    <iconify-icon icon="solar:clipboard-list-bold"></iconify-icon>
                    Status
                </h3>
                <span class="filter-status-badge">
                    <iconify-icon icon="<?php echo $statusFilter ? $statusIcons[$statusFilter] : 'solar:list-bold'; ?>"></iconify-icon>
                    <?php echo $statusFilter ? ($statusLabels[$statusFilter] ?? 'Todos') : 'Todos'; ?>
                </span>
            </div>
            <button type="button" class="filter-toggle-btn" onclick="toggleStatusFilter()" id="statusFilterToggle">
                <iconify-icon icon="solar:alt-arrow-down-bold"></iconify-icon>
            </button>
        </div>
        <div class="filter-body" id="statusFilterBody">
            <div class="filter-scroll">
                <div class="filter-pills">
                    <a href="?<?php echo http_build_query(array_merge($_GET, ['status' => '', 'page' => 1])); ?>" class="filter-pill <?php echo !$statusFilter ? 'active' : ''; ?>">
                        <iconify-icon icon="solar:list-bold"></iconify-icon> Todos <span class="count"><?php echo array_sum($statusCounts); ?></span>
                    </a>
                    <?php foreach (['awaiting_payment' => 'Aguardando', 'paid' => 'Pagos', 'preparing' => 'Preparando', 'shipped' => 'Enviados', 'delivered' => 'Entregues'] as $key => $label): ?>
                    <a href="?<?php echo http_build_query(array_merge($_GET, ['status' => $key, 'page' => 1])); ?>" class="filter-pill <?php echo $statusFilter === $key ? 'active' : ''; ?>">
                        <iconify-icon icon="<?php echo $statusIcons[$key]; ?>"></iconify-icon> <?php echo $label; ?> <span class="count"><?php echo $statusCounts[$key] ?? 0; ?></span>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
    
    <script>
    function toggleStatusFilter() {
        const body = document.getElementById('statusFilterBody');
        const btn = document.getElementById('statusFilterToggle');
        body.classList.toggle('show');
        btn.classList.toggle('active');
        const icon = btn.querySelector('iconify-icon');
        icon.setAttribute('icon', body.classList.contains('show') ? 'solar:alt-arrow-up-bold' : 'solar:alt-arrow-down-bold');
    }
    // Auto-show on desktop
    if (window.innerWidth > 768) {
        document.getElementById('statusFilterBody').classList.add('show');
    }
    </script>

    <!-- Filtros Busca/Data - Design igual Período -->
    <div class="filter-section">
        <div class="filter-header">
            <div style="display:flex;align-items:center;gap:.75rem;flex-wrap:wrap">
                <h3 class="filter-title">
                    <iconify-icon icon="solar:magnifer-bold"></iconify-icon>
                    Buscar
                </h3>
                <?php if ($searchFilter || $dateFilter): ?>
                <span class="filter-status-badge">
                    <iconify-icon icon="solar:filter-bold"></iconify-icon>
                    <?php echo $searchFilter ? htmlspecialchars(substr($searchFilter, 0, 15)) . (strlen($searchFilter) > 15 ? '...' : '') : date('d/m', strtotime($dateFilter)); ?>
                </span>
                <?php endif; ?>
            </div>
            <button type="button" class="filter-toggle-btn" onclick="toggleSearchFilter()" id="searchFilterToggle">
                <iconify-icon icon="solar:alt-arrow-down-bold"></iconify-icon>
            </button>
        </div>
        <div class="filter-body" id="searchFilterBody">
            <form method="GET" class="filter-dates" style="flex:1;width:100%">
                <input type="hidden" name="status" value="<?php echo htmlspecialchars($statusFilter); ?>">
                <input type="text" name="search" class="filter-search-input" placeholder="Nome, telefone ou nº" value="<?php echo htmlspecialchars($searchFilter); ?>">
                <span class="sep">Data:</span>
                <input type="date" name="date" value="<?php echo $dateFilter; ?>" title="Filtrar por data">
                <button type="submit" class="btn-apply" title="Aplicar filtros">
                    <iconify-icon icon="solar:magnifer-bold"></iconify-icon>
                </button>
                <?php if ($searchFilter || $dateFilter): ?>
                <a href="?status=<?php echo htmlspecialchars($statusFilter); ?>" class="btn-clear" title="Limpar filtros">
                    <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
                </a>
                <?php endif; ?>
            </form>
        </div>
    </div>
    
    <script>
    function toggleSearchFilter() {
        const body = document.getElementById('searchFilterBody');
        const btn = document.getElementById('searchFilterToggle');
        body.classList.toggle('show');
        btn.classList.toggle('active');
        const icon = btn.querySelector('iconify-icon');
        icon.setAttribute('icon', body.classList.contains('show') ? 'solar:alt-arrow-up-bold' : 'solar:alt-arrow-down-bold');
    }
    // Auto-show on desktop
    if (window.innerWidth > 768) {
        document.getElementById('searchFilterBody').classList.add('show');
    }
    </script>

    <?php if (empty($orders)): ?>
    <div class="empty-state">
        <iconify-icon icon="solar:clipboard-list-bold"></iconify-icon>
        <h3>Nenhum pedido encontrado</h3>
    </div>
    <?php else: ?>

    <div class="orders-grid">
    <?php foreach ($orders as $order): ?>
    <?php
        $phone = '';
        $whatsappMsg = '';
        if (!empty($order['customer_phone'])) {
            $phone = preg_replace('/\D/', '', $order['customer_phone']);
            if (strlen($phone) === 11) $phone = '55' . $phone;
            $whatsappMsg = urlencode("Olá {$order['customer_name']}! Seu pedido #{$order['id']} está sendo processado.");
        }
        
        $isExpired = false;
        $expiresIn = '';
        if ($order['status'] === 'awaiting_payment' && !empty($order['expires_at'])) {
            $expiresAt = new DateTime($order['expires_at']);
            $now = new DateTime();
            $isExpired = $expiresAt < $now;
            if (!$isExpired) {
                $interval = $now->diff($expiresAt);
                $expiresIn = $interval->h . 'h ' . $interval->i . 'min';
            }
        }
        
        $totalItems = array_sum(array_column($order['items'], 'quantity'));
    ?>
    <div class="order-card" onclick="window.location.href='/pages/pedidos/ver.php?id=<?php echo $order['id']; ?>'" style="cursor:pointer;">
        <div class="order-header">
            <div class="order-id-badge">
                <span class="order-id">#<?php echo $order['id']; ?></span>
                <span class="order-date"><?php echo date('d/m H:i', strtotime($order['created_at'])); ?></span>
            </div>
            <div class="order-status-badge <?php echo $order['status']; ?>">
                <iconify-icon icon="<?php echo $statusIcons[$order['status']] ?? 'solar:question-circle-bold'; ?>"></iconify-icon>
                <?php echo $statusLabels[$order['status']] ?? $order['status']; ?>
            </div>
        </div>

        <div class="order-body">
            <div class="order-client">
                <div class="client-avatar"><?php echo strtoupper(substr($order['customer_name'] ?? 'C', 0, 1)); ?></div>
                <div class="client-info">
                    <div class="client-name"><?php echo htmlspecialchars($order['customer_name'] ?? 'Cliente'); ?></div>
                    <?php if (!empty($order['customer_phone'])): ?>
                    <div class="client-phone"><iconify-icon icon="solar:phone-bold"></iconify-icon> <?php echo htmlspecialchars($order['customer_phone']); ?></div>
                    <?php endif; ?>
                </div>
                <?php if ($phone): ?>
                <a href="https://wa.me/<?php echo $phone; ?>?text=<?php echo $whatsappMsg; ?>" target="_blank" class="whatsapp-mini" title="WhatsApp" onclick="event.stopPropagation();">
                    <iconify-icon icon="ic:baseline-whatsapp"></iconify-icon>
                </a>
                <?php endif; ?>
            </div>

            <div class="order-items-summary">
                <div class="items-count">
                    <iconify-icon icon="solar:box-bold"></iconify-icon>
                    <span><?php echo $totalItems; ?> <?php echo $totalItems === 1 ? 'item' : 'itens'; ?></span>
                </div>
                <div class="items-preview">
                    <?php $count = 0; foreach ($order['items'] as $item): if ($count >= 3) break; ?>
                    <div class="item-thumb" title="<?php echo htmlspecialchars($item['product_name']); ?>">
                        <img src="<?php echo htmlspecialchars($item['image_url'] ?? '/assets/images/placeholder.png'); ?>" alt="" onerror="this.src='/assets/images/placeholder.png'">
                        <?php if ($item['quantity'] > 1): ?><span class="item-qty"><?php echo $item['quantity']; ?></span><?php endif; ?>
                    </div>
                    <?php $count++; endforeach; ?>
                    <?php if (count($order['items']) > 3): ?>
                    <div class="item-thumb more">+<?php echo count($order['items']) - 3; ?></div>
                    <?php endif; ?>
                </div>
            </div>

            <?php if ($expiresIn || $isExpired): ?>
            <div class="order-expire <?php echo $isExpired ? 'expired' : ''; ?>">
                <iconify-icon icon="solar:alarm-bold"></iconify-icon>
                <?php echo $isExpired ? 'Expirado' : 'Expira em ' . $expiresIn; ?>
            </div>
            <?php endif; ?>

            <?php if (!empty($order['notes'])): ?>
            <div class="order-note">
                <iconify-icon icon="solar:chat-round-line-bold"></iconify-icon>
                <?php echo mb_strimwidth(htmlspecialchars($order['notes']), 0, 50, '...'); ?>
            </div>
            <?php endif; ?>
        </div>

        <div class="order-footer">
            <div class="order-total">
                <span class="total-label">Total</span>
                <span class="total-value">R$ <?php echo number_format($order['total_amount'] ?? 0, 2, ',', '.'); ?></span>
            </div>
            <form method="POST" style="margin:0;" onclick="event.stopPropagation();">
                <input type="hidden" name="action" value="update_status">
                <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                <select name="status" class="status-select" onchange="this.form.submit()">
                    <?php foreach ($statusLabels as $k => $v): ?>
                    <option value="<?php echo $k; ?>" <?php echo $order['status'] === $k ? 'selected' : ''; ?>><?php echo $v; ?></option>
                    <?php endforeach; ?>
                </select>
            </form>
        </div>
    </div>
    <?php endforeach; ?>
    </div>

    <?php if ($totalPages > 1): ?>
    <div style="display: flex; justify-content: center; gap: 0.5rem; margin-top: 1.5rem;">
        <?php if ($page > 1): ?>
        <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>" class="btn btn-secondary btn-sm"><iconify-icon icon="solar:arrow-left-bold"></iconify-icon></a>
        <?php endif; ?>
        <span style="padding: 0.5rem 1rem;">Página <?php echo $page; ?> de <?php echo $totalPages; ?></span>
        <?php if ($page < $totalPages): ?>
        <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>" class="btn btn-secondary btn-sm"><iconify-icon icon="solar:arrow-right-bold"></iconify-icon></a>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <?php endif; ?>
</main>

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