<?php
/**
 * Página de Consulta de Pedido (Acesso via Link Único)
 * URL: /meu-pedido/{token}
 */

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

// Obter token da URL
$token = $token ?? $_GET['token'] ?? null;

if (!$token || strlen($token) !== 32) {
    http_response_code(404);
    echo "<h1>Pedido não encontrado</h1><p>O link de consulta é inválido.</p>";
    exit;
}

try {
    $pdo = getDB();
    
    // Buscar pedido pelo token
    // Atualizado para buscar também o slug da loja, necessário para o header
    $stmt = $pdo->prepare("
        SELECT o.*, s.name as store_name, s.slug as store_slug, s.subdomain, s.logo_url as logo, s.primary_color, s.template_settings
        FROM orders o
        JOIN stores s ON o.store_id = s.id
        WHERE o.tracking_token = ?
    ");
    $stmt->execute([$token]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$order) {
        http_response_code(404);
        echo "<h1>Pedido não encontrado</h1><p>Este link de consulta não é válido ou expirou.</p>";
        exit;
    }

    // Configurações do Template
    $customSettings = [];
    if (!empty($order['template_settings'])) {
        $customSettings = json_decode($order['template_settings'], true) ?? [];
    }
    
    // Configurar variáveis para o header/footer
    $store = [
        'id' => $order['store_id'],
        'name' => $order['store_name'],
        'slug' => $order['store_slug'],
        'subdomain' => $order['subdomain'],
        'logo_url' => $order['logo'],
        'primary_color' => $order['primary_color'],
        'template_settings' => $order['template_settings']
    ];
    $currentStoreId = $order['store_id'];
    $storeName = $order['store_name'];
    $logo = $order['logo'];
    $storeSlug = $order['store_slug'];

    // Forçar exibição do logo se existir nas configurações (Dashboard)
    // A coluna logo_url pode estar vazia, mas o settings ter o logo
    $headerSettings = $customSettings['header'] ?? [];
    
    // Se não tiver logo nas configurações mas tiver na coluna (caso legado), usar da coluna
    if (empty($headerSettings['logo_image']) && !empty($logo)) {
        $headerSettings['logo_type'] = 'image';
        $headerSettings['logo_image'] = $logo;
    }
    
    // Garantir que o texto do logo esteja definido
    if (empty($headerSettings['logo_text'])) {
        $headerSettings['logo_text'] = $storeName;
    }

    // Atualizar o array store com o logo correto para o header usar se precisar
    if (!empty($headerSettings['logo_image'])) {
        $store['logo_url'] = $headerSettings['logo_image'];
        $logo = $headerSettings['logo_image'];
    }
    
    // URL Base - dinâmica, sem domínio hardcoded
    $currentHost = $_SERVER['HTTP_HOST'] ?? '';
    $isLojaPathAccess = strpos($_SERVER['REQUEST_URI'] ?? '', '/loja/') !== false;
    if (function_exists('get_store_url') && !empty($store)) {
        $baseUrl = get_store_url($store);
    } elseif ($isLojaPathAccess) {
        $baseUrl = '/loja/' . ($store['slug'] ?? '');
    } else {
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
        $baseUrl = $protocol . $currentHost;
    }

    // MENU DINÂMICO
    // Itens fixos que SEMPRE aparecem no menu (Início e Produtos)
    $fixedMenuItems = [
        ['id' => 1, 'name' => 'Início', 'link' => $baseUrl, 'icon' => 'solar:home-2-bold'],
        ['id' => 2, 'name' => 'Produtos', 'link' => $baseUrl . '/produtos', 'icon' => 'solar:bag-3-bold'],
    ];

    // Itens customizáveis do usuário
    $savedMenuItems = $customSettings['menu'] ?? [];
    $customMenuItems = [];

    // Se há itens salvos, filtrar os que não são fixos
    if (!empty($savedMenuItems)) {
        foreach ($savedMenuItems as $item) {
            $itemName = strtolower(trim($item['name'] ?? ''));
            if (!in_array($itemName, ['início', 'inicio', 'produtos', 'home', 'products'])) {
                $customMenuItems[] = $item;
            }
        }
    }

    // Se não há itens customizados, usar padrões
    if (empty($customMenuItems)) {
        $customMenuItems = [
            ['id' => 3, 'name' => 'Categorias', 'link' => $baseUrl . '#categorias', 'icon' => 'solar:widget-4-bold'],
            ['id' => 4, 'name' => 'Contato', 'link' => $baseUrl . '#contato', 'icon' => 'solar:phone-bold']
        ];
    }

    // Combinar itens
    $menuItems = array_merge($fixedMenuItems, $customMenuItems);
    
    // Corrigir links relativos
    foreach ($menuItems as &$menuItem) {
        $link = $menuItem['link'] ?? '';
        if (strpos($link, '#') === 0) {
            $menuItem['link'] = $baseUrl . $link;
        }
        if ($link === '#') {
            $menuItem['link'] = $baseUrl;
        }
    }
    unset($menuItem);
    
    // Extrair variáveis para o header.php
    $logoType = $headerSettings['logo_type'];
    $logoImage = $headerSettings['logo_image'] ?? $logo;
    $logoText = $headerSettings['logo_text'];
    
    // Configurações do footer
    $footerSettings = $customSettings['footer'] ?? [];
    
    
    // Buscar itens do pedido
    $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']]);
    $items = $itemsStmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Traduzir status
    $statusLabels = [
        'pending' => ['Pendente', '#f59e0b'],
        'awaiting_payment' => ['Aguardando Pagamento', '#f59e0b'],
        'sent_whatsapp' => ['Enviado via WhatsApp', '#3b82f6'],
        'confirmed' => ['Confirmado', '#10b981'],
        'paid' => ['Pago', '#10b981'],
        'preparing' => ['Em Preparação', '#8b5cf6'],
        'shipped' => ['Enviado', '#3b82f6'],
        'delivered' => ['Entregue', '#10b981'],
        'cancelled' => ['Cancelado', '#ef4444'],
        'canceled' => ['Cancelado', '#ef4444'],
        'expired' => ['Expirado', '#6b7280']
    ];
    
    $statusInfo = $statusLabels[$order['status']] ?? ['Desconhecido', '#6b7280'];
    $primaryColor = $order['primary_color'] ?? '#3b82f6';
    
} catch (Exception $e) {
    http_response_code(500);
    echo "<h1>Erro</h1><p>Não foi possível carregar o pedido.</p>";
    exit;
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Meu Pedido - <?= htmlspecialchars($order['store_name']) ?></title>
    
    <!-- Scripts e Estilos Padrão -->
    <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.9">
    <?php include __DIR__ . "/includes/dynamic-styles.php"; ?>
    
    <style>
        :root {
            --primary: <?= $primaryColor ?>;
        }
        /* Estilos específicos desta página que não conflitam com o global */
        .order-tracking-container { max-width: 800px; margin: 2rem auto; padding: 0 1rem; }
        .tracking-header { text-align: center; margin-bottom: 2rem; }
        .tracking-header h1 { font-size: 1.75rem; color: var(--text); margin-bottom: 0.5rem; }
        
        .tracking-card { background: var(--surface); border: 1px solid var(--border); border-radius: 16px; margin-bottom: 1.5rem; overflow: hidden; }
        .tracking-card-header { background: linear-gradient(135deg, var(--primary), color-mix(in srgb, var(--primary) 80%, #000)); color: #fff; padding: 1.5rem; display: flex; justify-content: space-between; align-items: center; }
        .tracking-card-header h2 { font-size: 1.1rem; display: flex; align-items: center; gap: 0.5rem; margin: 0; color: #fff; }
        
        .status-badge { background: rgba(255,255,255,0.2); color: #fff; padding: 0.5rem 1rem; border-radius: 20px; font-size: 0.85rem; font-weight: 600; backdrop-filter: blur(4px); }
        .tracking-card-body { padding: 1.5rem; }
        
        .info-row { display: flex; justify-content: space-between; padding: 0.75rem 0; border-bottom: 1px solid var(--border-light); }
        .info-row:last-child { border-bottom: none; }
        .info-label { color: var(--text-muted); font-size: 0.9rem; }
        .info-value { font-weight: 500; text-align: right; color: var(--text); }
        
        .items-list { list-style: none; }
        .item { display: flex; gap: 1rem; padding: 1rem 0; border-bottom: 1px solid var(--border-light); }
        .item:last-child { border-bottom: none; }
        .item-image { width: 60px; height: 60px; border-radius: 8px; object-fit: cover; background: var(--surface-hover); }
        .item-details { flex: 1; }
        .item-name { font-weight: 500; margin-bottom: 0.25rem; color: var(--text); }
        .item-qty { color: var(--text-muted); font-size: 0.85rem; }
        .item-price { font-weight: 600; color: var(--primary); }
        
        .total-section { background: var(--surface-hover); padding: 1.5rem; border-top: 2px dashed var(--border); }
        .total-row { display: flex; justify-content: space-between; padding: 0.5rem 0; color: var(--text); }
        .total-row.final { font-size: 1.25rem; font-weight: 700; color: var(--primary); padding-top: 1rem; border-top: 1px solid var(--border); margin-top: 0.5rem; }
        
        .address-box { background: var(--surface-hover); padding: 1rem; border-radius: 8px; font-size: 0.9rem; color: var(--text); }
        
        .tracking-code-box { background: #eff6ff; border: 1px solid #bfdbfe; border-radius: 8px; padding: 1rem; margin-top: 1rem; color: #1e3a8a; }
        .tracking-code-box strong { color: #1d4ed8; display: block; margin-bottom: 0.25rem; }
        
        .page-footer-note { text-align: center; color: var(--text-muted); font-size: 0.85rem; margin-top: 2rem; }
    </style>
</head>
<body class="bg-gray-50">

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

    <main class="order-tracking-container">
        <div class="tracking-header">
            <h1>Acompanhe seu Pedido</h1>
            <p style="color: var(--text-muted);">Visualize o status e detalhes da sua compra</p>
        </div>
        
        <div class="tracking-card">
            <div class="tracking-card-header">
                <h2><iconify-icon icon="solar:bag-check-bold"></iconify-icon> Pedido #<?= htmlspecialchars($order['id']) ?></h2>
                <span class="status-badge" style="background: <?= $statusInfo[1] ?>;"><?= $statusInfo[0] ?></span>
            </div>
            <div class="tracking-card-body">
                <div class="info-row">
                    <span class="info-label">Data do Pedido</span>
                    <span class="info-value"><?= date('d/m/Y H:i', strtotime($order['created_at'])) ?></span>
                </div>
                <div class="info-row">
                    <span class="info-label">Cliente</span>
                    <span class="info-value"><?= htmlspecialchars($order['customer_name']) ?></span>
                </div>
                <?php if ($order['customer_phone']): ?>
                <div class="info-row">
                    <span class="info-label">Telefone</span>
                    <span class="info-value"><?= htmlspecialchars($order['customer_phone']) ?></span>
                </div>
                <?php endif; ?>
                <?php if ($order['payment_method']): ?>
                <div class="info-row">
                    <span class="info-label">Pagamento</span>
                    <span class="info-value"><?= $order['payment_method'] === 'whatsapp' ? 'Via WhatsApp' : 'Online' ?></span>
                </div>
                <?php endif; ?>
                
                <?php if ($order['tracking_code']): ?>
                <div class="tracking-code-box">
                    <strong><iconify-icon icon="solar:delivery-bold"></iconify-icon> Código de Rastreio:</strong>
                    <div style="font-family: monospace; font-size: 1.1rem; letter-spacing: 1px;"><?= htmlspecialchars($order['tracking_code']) ?></div>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="tracking-card">
            <div class="tracking-card-body">
                <h3 style="margin-bottom: 1rem; font-size: 1rem; color: var(--text); display:flex; align-items:center; gap:0.5rem;"><iconify-icon icon="solar:box-bold"></iconify-icon> Itens do Pedido</h3>
                <ul class="items-list">
                    <?php foreach ($items as $item): ?>
                    <li class="item">
                        <?php if ($item['image_url']): ?>
                        <img src="<?= htmlspecialchars($item['image_url']) ?>" alt="" class="item-image">
                        <?php else: ?>
                        <div class="item-image" style="display:flex;align-items:center;justify-content:center;"><iconify-icon icon="solar:box-bold" style="font-size:1.5rem;color:var(--text-muted);"></iconify-icon></div>
                        <?php endif; ?>
                        <div class="item-details">
                            <div class="item-name"><?= htmlspecialchars($item['product_name'] ?? $item['name'] ?? 'Produto') ?></div>
                            <div class="item-qty">Qtd: <?= $item['quantity'] ?></div>
                        </div>
                        <div class="item-price">R$ <?= number_format($item['unit_price'] * $item['quantity'], 2, ',', '.') ?></div>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <div class="total-section">
                <div class="total-row">
                    <span>Subtotal</span>
                    <span>R$ <?= number_format($order['subtotal'] ?? $order['total_amount'], 2, ',', '.') ?></span>
                </div>
                <?php if ($order['shipping_cost'] > 0): ?>
                <div class="total-row">
                    <span>Frete (<?= htmlspecialchars($order['shipping_method'] ?? 'Padrão') ?>)</span>
                    <span>R$ <?= number_format($order['shipping_cost'], 2, ',', '.') ?></span>
                </div>
                <?php elseif ($order['shipping_method']): ?>
                <div class="total-row">
                    <span>Frete</span>
                    <span style="color:#10b981;">Grátis</span>
                </div>
                <?php endif; ?>
                <div class="total-row final">
                    <span>Total</span>
                    <span>R$ <?= number_format($order['total_amount'], 2, ',', '.') ?></span>
                </div>
            </div>
        </div>
        
        <?php if ($order['delivery_address']): ?>
        <div class="tracking-card">
            <div class="tracking-card-body">
                <h3 style="margin-bottom: 1rem; font-size: 1rem; color: var(--text); display:flex; align-items:center; gap:0.5rem;"><iconify-icon icon="solar:map-point-bold"></iconify-icon> Endereço de Entrega</h3>
                <div class="address-box"><?= nl2br(htmlspecialchars($order['delivery_address'])) ?></div>
            </div>
        </div>
        <?php endif; ?>
        
        <?php if (!$isCustomerLoggedIn): 
            // Verificar se o email do pedido já tem cadastro na loja
            $accountExists = false;
            if (!empty($order['customer_email'])) {
                $checkStmt = $pdo->prepare("SELECT id FROM customers WHERE email = ? AND store_id = ?");
                $checkStmt->execute([$order['customer_email'], $order['store_id']]);
                if ($checkStmt->fetch()) {
                    $accountExists = true;
                }
            }
        ?>
        <div class="tracking-card" style="border: 2px dashed var(--primary); background: rgba(37, 99, 235, 0.03);">
            <div class="tracking-card-body" style="text-align: center; padding: 2rem;">
                <iconify-icon icon="solar:user-circle-bold" style="font-size: 3rem; color: var(--primary); margin-bottom: 1rem;"></iconify-icon>
                
                <?php if ($accountExists): ?>
                    <!-- Caso tenha conta: Pedir Login -->
                    <h3 style="margin-bottom: 0.5rem; color: var(--text);">Você já tem cadastro!</h3>
                    <p style="color: var(--text-muted); margin-bottom: 1.5rem; max-width: 500px; margin-left: auto; margin-right: auto;">
                        Identificamos que o e-mail <strong><?= htmlspecialchars($order['customer_email']) ?></strong> já possui uma conta em nossa loja.
                        <br>Faça login para vincular este pedido ao seu histórico.
                    </p>
                    <div style="display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap;">
                        <a href="<?= htmlspecialchars($baseUrl) ?>/entrar?email=<?= urlencode($order['customer_email']) ?>" class="btn-primary" style="background: var(--primary); color: #fff; padding: 0.75rem 1.5rem; border-radius: 8px; text-decoration: none; font-weight: 600; transition: opacity 0.2s;">
                            Entrar na minha conta
                        </a>
                    </div>
                <?php else: ?>
                    <!-- Caso NÃO tenha conta: Incentivar Cadastro -->
                    <h3 style="margin-bottom: 0.5rem; color: var(--text);">Você está visitando como convidado</h3>
                    <p style="color: var(--text-muted); margin-bottom: 1.5rem; max-width: 500px; margin-left: auto; margin-right: auto;">
                        Crie sua conta agora para salvar este pedido no seu histórico, agilizar suas próximas compras e receber ofertas exclusivas!
                    </p>
                    <div style="display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap;">
                        <a href="<?= htmlspecialchars($baseUrl) ?>/registrar" class="btn-primary" style="background: var(--primary); color: #fff; padding: 0.75rem 1.5rem; border-radius: 8px; text-decoration: none; font-weight: 600; transition: opacity 0.2s;">
                            Criar minha conta
                        </a>
                        <a href="<?= htmlspecialchars($baseUrl) ?>/entrar" class="btn-outline" style="border: 1px solid var(--border); color: var(--text); padding: 0.75rem 1.5rem; border-radius: 8px; text-decoration: none; font-weight: 600; background: #fff; transition: background 0.2s;">
                            Já tenho conta
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <div class="page-footer-note">
            <p>Pedido realizado em <strong><?= htmlspecialchars($order['store_name']) ?></strong></p>
            <p style="margin-top: 0.5rem;">Guarde este link para acompanhar seu pedido</p>
        </div>
    </main>

    <?php include __DIR__ . '/includes/footer.php'; ?>
    
    <!-- Toast Notification -->
    <div class="toast" id="toast"></div>

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

</body>
</html>
