<?php
/**
 * Detalhes do Pedido - MontaLoja
 * Página para visualizar detalhes completos de um pedido
 */

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

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

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

// Pegar ID do pedido da URL
$orderId = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$orderId) {
    header("Location: " . storeUrl('meus-pedidos'));
    exit;
}

// Buscar pedido (verificando se pertence ao cliente)
$orderStmt = $pdo->prepare("
    SELECT * FROM orders 
    WHERE id = ? AND store_id = ? AND (customer_id = ? OR customer_email = ?)
");
$orderStmt->execute([$orderId, $currentStoreId, $customerId, $customerEmail]);
$order = $orderStmt->fetch(PDO::FETCH_ASSOC);

if (!$order) {
    header("Location: " . storeUrl('meus-pedidos'));
    exit;
}

// Buscar itens do pedido
$itemsStmt = $pdo->prepare("
    SELECT oi.*, p.name as product_name, p.image_url, p.sku
    FROM order_items oi
    LEFT JOIN products p ON oi.product_id = p.id
    WHERE oi.order_id = ?
");
$itemsStmt->execute([$orderId]);
$orderItems = $itemsStmt->fetchAll(PDO::FETCH_ASSOC);

// Função para traduzir status
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'];
}

$status = getStatusInfo($order['status']);

// Traduzir método de pagamento
function translatePaymentMethod($method) {
    $methods = [
        'pix' => 'PIX',
        'credit_card' => 'Cartão de Crédito',
        'debit_card' => 'Cartão de Débito',
        'boleto' => 'Boleto Bancário',
        'cash' => 'Dinheiro',
        'transfer' => 'Transferência',
    ];
    return $methods[$method] ?? ucfirst($method);
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pedido #<?php echo str_pad($order['id'], 6, '0', STR_PAD_LEFT); ?> - <?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'); ?>;
}

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

.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.6rem;
    font-weight: 800;
    color: #1F2937;
    display: flex;
    align-items: center;
    gap: 12px;
    margin: 0;
}

.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;
    transform: translateX(-2px);
}

/* Status Banner */
.status-banner {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 24px;
    border-radius: 16px;
    margin-bottom: 24px;
    flex-wrap: wrap;
    gap: 16px;
}

.status-info {
    display: flex;
    align-items: center;
    gap: 14px;
}

.status-icon {
    width: 56px;
    height: 56px;
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(255,255,255,0.5);
}

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

.status-text h2 {
    font-size: 1.2rem;
    font-weight: 700;
    margin: 0 0 4px 0;
}

.status-text p {
    font-size: 0.9rem;
    opacity: 0.8;
    margin: 0;
}

.order-date-badge {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 18px;
    background: rgba(255,255,255,0.6);
    border-radius: 50px;
    font-weight: 600;
    font-size: 0.9rem;
}

/* Cards */
.detail-card {
    background: white;
    border-radius: 16px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
    border: 1px solid #F3F4F6;
    margin-bottom: 20px;
    overflow: hidden;
}

.card-header {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 18px 22px;
    background: linear-gradient(135deg, #F8FAFC 0%, #F1F5F9 100%);
    border-bottom: 1px solid #E5E7EB;
    font-weight: 700;
    font-size: 1rem;
    color: #374151;
}

.card-header iconify-icon {
    font-size: 1.3rem;
    color: #6B7280;
}

.card-body {
    padding: 22px;
}

/* Info Grid */
.info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
}

.info-item {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

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

.info-value {
    font-size: 1rem;
    color: #1F2937;
    font-weight: 500;
}

/* Products List */
.product-item {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 16px 0;
    border-bottom: 1px solid #F3F4F6;
}

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

.product-image {
    width: 72px;
    height: 72px;
    border-radius: 12px;
    background: #F3F4F6;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    flex-shrink: 0;
}

.product-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.product-image iconify-icon {
    font-size: 2rem;
    color: #D1D5DB;
}

.product-info {
    flex: 1;
    min-width: 0;
}

.product-name {
    font-weight: 600;
    color: #1F2937;
    margin-bottom: 4px;
    font-size: 1rem;
}

.product-meta {
    font-size: 0.85rem;
    color: #6B7280;
}

.product-price {
    text-align: right;
}

.product-unit-price {
    font-size: 0.85rem;
    color: #6B7280;
    margin-bottom: 4px;
}

.product-total {
    font-size: 1.1rem;
    font-weight: 700;
    color: #059669;
}

/* Order Summary */
.order-summary {
    background: linear-gradient(135deg, #F8FAFC 0%, #F1F5F9 100%);
    border-radius: 12px;
    padding: 20px;
    margin-top: 16px;
}

.summary-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    font-size: 0.95rem;
    color: #6B7280;
}

.summary-row.total {
    border-top: 2px solid #E5E7EB;
    margin-top: 12px;
    padding-top: 16px;
    font-size: 1.25rem;
    font-weight: 800;
    color: #1F2937;
}

.summary-row.total .value {
    color: #059669;
}

/* Timeline */
.timeline {
    position: relative;
    padding-left: 32px;
}

.timeline::before {
    content: '';
    position: absolute;
    left: 10px;
    top: 8px;
    bottom: 8px;
    width: 2px;
    background: #E5E7EB;
    border-radius: 2px;
}

.timeline-item {
    position: relative;
    padding-bottom: 20px;
}

.timeline-item:last-child {
    padding-bottom: 0;
}

.timeline-dot {
    position: absolute;
    left: -26px;
    top: 4px;
    width: 14px;
    height: 14px;
    border-radius: 50%;
    background: #E5E7EB;
    border: 3px solid white;
    box-shadow: 0 0 0 2px #E5E7EB;
}

.timeline-item.active .timeline-dot {
    background: #10B981;
    box-shadow: 0 0 0 2px #10B981;
}

.timeline-content {
    background: #F9FAFB;
    border-radius: 10px;
    padding: 12px 16px;
}

.timeline-title {
    font-weight: 600;
    color: #1F2937;
    margin-bottom: 4px;
}

.timeline-date {
    font-size: 0.85rem;
    color: #6B7280;
}

/* Responsive */
@media (max-width: 640px) {
    .page-header {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .btn-back {
        order: -1;
    }
    
    .status-banner {
        flex-direction: column;
        text-align: center;
    }
    
    .status-info {
        flex-direction: column;
    }
    
    .product-item {
        flex-direction: column;
        text-align: center;
    }
    
    .product-price {
        text-align: center;
        margin-top: 8px;
    }
    
    .info-grid {
        grid-template-columns: 1fr;
    }
}
</style>
</head>
<body>

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

<div class="order-detail-page">
    <div class="page-header">
        <h1>
            <iconify-icon icon="solar:document-text-bold"></iconify-icon>
            Pedido #<?php echo str_pad($order['id'], 6, '0', STR_PAD_LEFT); ?>
        </h1>
        <a href="<?php echo storeUrl('meus-pedidos'); ?>" class="btn-back">
            <iconify-icon icon="solar:arrow-left-linear"></iconify-icon>
            Voltar aos Pedidos
        </a>
    </div>

    <!-- Status Banner -->
    <div class="status-banner" style="background: <?php echo $status['bg']; ?>; color: <?php echo $status['color']; ?>">
        <div class="status-info">
            <div class="status-icon">
                <iconify-icon icon="<?php echo $status['icon']; ?>"></iconify-icon>
            </div>
            <div class="status-text">
                <h2><?php echo $status['label']; ?></h2>
                <p>Status atual do seu pedido</p>
            </div>
        </div>
        <div class="order-date-badge">
            <iconify-icon icon="solar:calendar-bold"></iconify-icon>
            <?php echo date('d/m/Y \à\s H:i', strtotime($order['created_at'])); ?>
        </div>
    </div>

    <!-- Customer Info -->
    <div class="detail-card">
        <div class="card-header">
            <iconify-icon icon="solar:user-bold"></iconify-icon>
            Dados do Cliente
        </div>
        <div class="card-body">
            <div class="info-grid">
                <div class="info-item">
                    <span class="info-label">Nome</span>
                    <span class="info-value"><?php echo htmlspecialchars($order['customer_name']); ?></span>
                </div>
                <?php if (!empty($order['customer_email'])): ?>
                <div class="info-item">
                    <span class="info-label">E-mail</span>
                    <span class="info-value"><?php echo htmlspecialchars($order['customer_email']); ?></span>
                </div>
                <?php endif; ?>
                <?php if (!empty($order['customer_phone'])): ?>
                <div class="info-item">
                    <span class="info-label">Telefone</span>
                    <span class="info-value"><?php echo htmlspecialchars($order['customer_phone']); ?></span>
                </div>
                <?php endif; ?>
                <?php if (!empty($order['payment_method'])): ?>
                <div class="info-item">
                    <span class="info-label">Pagamento</span>
                    <span class="info-value"><?php echo translatePaymentMethod($order['payment_method']); ?></span>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Delivery Address -->
    <?php if (!empty($order['delivery_address'])): ?>
    <div class="detail-card">
        <div class="card-header">
            <iconify-icon icon="solar:map-point-bold"></iconify-icon>
            Endereço de Entrega
        </div>
        <div class="card-body">
            <div class="info-value" style="font-size: 1.05rem; line-height: 1.6;">
                <?php echo nl2br(htmlspecialchars($order['delivery_address'])); ?>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Order Items -->
    <div class="detail-card">
        <div class="card-header">
            <iconify-icon icon="solar:bag-4-bold"></iconify-icon>
            Itens do Pedido (<?php echo count($orderItems); ?>)
        </div>
        <div class="card-body">
            <?php foreach ($orderItems as $item): ?>
            <div class="product-item">
                <div class="product-image">
                    <?php if (!empty($item['image_url'])): ?>
                    <img src="<?php echo htmlspecialchars($item['image_url']); ?>" alt="<?php echo htmlspecialchars($item['product_name'] ?? $item['name'] ?? 'Produto'); ?>">
                    <?php else: ?>
                    <iconify-icon icon="solar:box-bold"></iconify-icon>
                    <?php endif; ?>
                </div>
                <div class="product-info">
                    <div class="product-name"><?php echo htmlspecialchars($item['product_name'] ?? $item['name'] ?? 'Produto'); ?></div>
                    <div class="product-meta">
                        Quantidade: <?php echo $item['quantity']; ?>
                        <?php if (!empty($item['sku'])): ?>
                        · SKU: <?php echo htmlspecialchars($item['sku']); ?>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="product-price">
                    <div class="product-unit-price">R$ <?php echo number_format($item['price'], 2, ',', '.'); ?> cada</div>
                    <div class="product-total">R$ <?php echo number_format($item['price'] * $item['quantity'], 2, ',', '.'); ?></div>
                </div>
            </div>
            <?php endforeach; ?>

            <!-- Order Summary -->
            <div class="order-summary">
                <div class="summary-row">
                    <span>Subtotal (<?php echo count($orderItems); ?> <?php echo count($orderItems) == 1 ? 'item' : 'itens'; ?>)</span>
                    <span>R$ <?php echo number_format($order['subtotal'] ?? $order['total_amount'], 2, ',', '.'); ?></span>
                </div>
                <?php if (!empty($order['shipping_cost']) && $order['shipping_cost'] > 0): ?>
                <div class="summary-row">
                    <span>Frete</span>
                    <span>R$ <?php echo number_format($order['shipping_cost'], 2, ',', '.'); ?></span>
                </div>
                <?php endif; ?>
                <?php if (!empty($order['discount']) && $order['discount'] > 0): ?>
                <div class="summary-row" style="color: #059669;">
                    <span>Desconto</span>
                    <span>- R$ <?php echo number_format($order['discount'], 2, ',', '.'); ?></span>
                </div>
                <?php endif; ?>
                <div class="summary-row total">
                    <span>Total</span>
                    <span class="value">R$ <?php echo number_format($order['total_amount'], 2, ',', '.'); ?></span>
                </div>
            </div>
        </div>
    </div>

    <!-- Notes -->
    <?php if (!empty($order['notes'])): ?>
    <div class="detail-card">
        <div class="card-header">
            <iconify-icon icon="solar:notes-bold"></iconify-icon>
            Observações
        </div>
        <div class="card-body">
            <div class="info-value" style="line-height: 1.6;">
                <?php echo nl2br(htmlspecialchars($order['notes'])); ?>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

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

</body>
</html>
