<?php
/**
 * Visualizar Pedido - MontaLoja SaaS
 * Página de detalhes de um pedido específico
 */
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;
}

$orderId = intval($_GET['id'] ?? 0);

if (!$orderId) {
    header('Location: /pages/pedidos.php');
    exit;
}

// Buscar pedido
$orderStmt = $pdo->prepare("SELECT o.* FROM orders o WHERE o.id = ? AND o.store_id = ?");
$orderStmt->execute([$orderId, $storeId]);
$order = $orderStmt->fetch(PDO::FETCH_ASSOC);

if (!$order) {
    $_SESSION['flash_message'] = 'Pedido não encontrado.';
    $_SESSION['flash_type'] = 'error';
    header('Location: /pages/pedidos.php');
    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);

// Buscar dados da loja
$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['status'])) {
        $newStatus = $_POST['status'];
        $validStatuses = ['pending', 'awaiting_payment', 'paid', 'preparing', 'shipped', 'delivered', 'cancelled'];

        if (in_array($newStatus, $validStatuses)) {
            try {
                $pdo->beginTransaction();
                $oldStatus = $order['status'];
                
                if ($newStatus === 'cancelled' && !in_array($oldStatus, ['cancelled', 'expired'])) {
                    // Restaurar estoque
                    foreach ($orderItems 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();
                
                $order['status'] = $newStatus;
                $message = 'Status do pedido atualizado com sucesso!';
                $messageType = 'success';
            } catch (Exception $e) {
                $pdo->rollBack();
                $message = 'Erro ao atualizar status: ' . $e->getMessage();
                $messageType = 'error';
            }
        }
    }
}

// Labels e cores de status
$statusLabels = [
    'pending' => 'Pendente',
    'awaiting_payment' => 'Aguardando Pagamento',
    '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'
];

$statusColors = [
    'pending' => '#F59E0B',
    'awaiting_payment' => '#F59E0B',
    'paid' => '#10B981',
    'preparing' => '#3B82F6',
    'shipped' => '#8B5CF6',
    'delivered' => '#10B981',
    'cancelled' => '#6B7280',
    'expired' => '#6B7280'
];

// WhatsApp
$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']}! Sobre seu pedido #{$order['id']}...");
}

$pageTitle = 'Pedido #' . $order['id'];
include __DIR__ . '/../../includes/dashboard-header.php';
include __DIR__ . '/../../includes/dashboard-styles.php';
?>

<style>
.order-detail-page {
    max-width: 1200px;
    margin: 0 auto;
}

.order-detail-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    flex-wrap: wrap;
    gap: 1rem;
    margin-bottom: 1.5rem;
}

.order-detail-title {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.order-detail-title h1 {
    font-size: 1.75rem;
    font-weight: 700;
    margin: 0;
}

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

.order-detail-actions {
    display: flex;
    gap: 0.75rem;
    flex-wrap: wrap;
}

.back-btn {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.6rem 1rem;
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: 8px;
    color: var(--text-primary);
    text-decoration: none;
    font-size: 0.9rem;
    transition: all 0.2s;
}

.back-btn:hover {
    background: var(--bg-card-hover);
    border-color: var(--primary);
}

.order-status-badge-lg {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.6rem 1.25rem;
    border-radius: 25px;
    font-size: 0.9rem;
    font-weight: 600;
}

.order-detail-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 1.5rem;
}

@media (min-width: 768px) {
    .order-detail-grid {
        grid-template-columns: 2fr 1fr;
    }
}

.detail-card {
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: 16px;
    overflow: hidden;
}

.detail-card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem 1.25rem;
    background: var(--bg-darker);
    border-bottom: 1px solid var(--border);
}

.detail-card-header h3 {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-size: 1rem;
    font-weight: 600;
    margin: 0;
}

.detail-card-body {
    padding: 1.25rem;
}

/* Items */
.order-item {
    display: flex;
    gap: 1rem;
    padding: 1rem 0;
    border-bottom: 1px solid var(--border);
}

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

.order-item:first-child {
    padding-top: 0;
}

.order-item-image {
    width: 70px;
    height: 70px;
    border-radius: 10px;
    overflow: hidden;
    flex-shrink: 0;
    background: var(--bg-darker);
}

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

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

.order-item-name {
    font-weight: 600;
    font-size: 0.95rem;
    margin-bottom: 0.25rem;
}

.order-item-sku {
    font-size: 0.8rem;
    color: var(--text-muted);
    margin-bottom: 0.5rem;
}

.order-item-variations {
    display: flex;
    flex-wrap: wrap;
    gap: 0.35rem;
    margin-top: 0.35rem;
    margin-bottom: 0.5rem;
}

.variation-badge {
    display: inline-block;
    padding: 0.2rem 0.5rem;
    font-size: 0.75rem;
    font-weight: 600;
    background: var(--primary-light);
    color: var(--primary);
    border-radius: 6px;
}

.order-item-details {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.order-item-qty {
    font-size: 0.85rem;
    color: var(--text-secondary);
}

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

/* Customer */
.customer-info-row {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 0.75rem 0;
    border-bottom: 1px solid var(--border);
}

.customer-info-row:last-child {
    border-bottom: none;
}

.customer-info-row iconify-icon {
    font-size: 1.25rem;
    color: var(--text-muted);
    width: 28px;
}

.customer-info-row span {
    flex: 1;
}

.customer-info-row a {
    color: var(--primary);
    text-decoration: none;
}

/* Summary */
.order-summary-row {
    display: flex;
    justify-content: space-between;
    padding: 0.6rem 0;
    font-size: 0.95rem;
}

.order-summary-row.total {
    border-top: 2px solid var(--border);
    margin-top: 0.5rem;
    padding-top: 1rem;
    font-weight: 700;
    font-size: 1.1rem;
}

.order-summary-row.total .value {
    color: var(--success);
}

/* Status Form */
.status-update-form {
    display: flex;
    gap: 0.75rem;
    margin-top: 1rem;
}

.status-update-form select {
    flex: 1;
    padding: 0.6rem 1rem;
    border-radius: 8px;
    border: 1px solid var(--border);
    background: var(--bg-card);
    font-size: 0.9rem;
}

.whatsapp-btn {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.6rem 1.25rem;
    background: linear-gradient(135deg, #25D366);
    color: white;
    border: none;
    border-radius: 8px;
    text-decoration: none;
    font-weight: 600;
    font-size: 0.9rem;
    transition: all 0.2s;
}

.whatsapp-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(37, 211, 102, 0.4);
}

/* Notes */
.order-notes {
    background: rgba(251, 191, 36, 0.1);
    border: 1px solid rgba(251, 191, 36, 0.3);
    border-radius: 10px;
    padding: 1rem;
    color: #92400E;
}

.order-notes-title {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-weight: 600;
    margin-bottom: 0.5rem;
}

/* Address */
.address-text {
    line-height: 1.6;
    color: var(--text-secondary);
}

/* Timeline */
.order-timeline {
    padding: 0;
}

.timeline-item {
    display: flex;
    gap: 1rem;
    padding: 0.75rem 0;
    position: relative;
}

.timeline-item:not(:last-child)::before {
    content: '';
    position: absolute;
    left: 15px;
    top: 40px;
    bottom: 0;
    width: 2px;
    background: var(--border);
}

.timeline-dot {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: var(--bg-darker);
    border: 2px solid var(--border);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    z-index: 1;
}

.timeline-dot.active {
    background: var(--primary);
    border-color: var(--primary);
    color: white;
}

.timeline-content h4 {
    font-size: 0.9rem;
    font-weight: 600;
    margin: 0 0 0.25rem 0;
}

.timeline-content p {
    font-size: 0.8rem;
    color: var(--text-muted);
    margin: 0;
}
</style>

<main class="main-content">
    <div class="order-detail-page">
        
        <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType; ?>" style="margin-bottom: 1rem;">
            <?php echo $message; ?>
        </div>
        <?php endif; ?>

        <div class="order-detail-header">
            <div class="order-detail-title">
                <a href="/pages/pedidos.php" class="back-btn">
                    <iconify-icon icon="solar:arrow-left-bold"></iconify-icon>
                    Voltar
                </a>
                <div>
                    <h1>Pedido #<?php echo $order['id']; ?></h1>
                    <span class="order-date">
                        <iconify-icon icon="solar:calendar-bold"></iconify-icon>
                        <?php echo date('d/m/Y H:i', strtotime($order['created_at'])); ?>
                    </span>
                </div>
            </div>
            <div class="order-detail-actions">
                <span class="order-status-badge-lg" style="background: <?php echo $statusColors[$order['status']] ?? '#6B7280'; ?>20; color: <?php echo $statusColors[$order['status']] ?? '#6B7280'; ?>;">
                    <iconify-icon icon="<?php echo $statusIcons[$order['status']] ?? 'solar:question-circle-bold'; ?>"></iconify-icon>
                    <?php echo $statusLabels[$order['status']] ?? $order['status']; ?>
                </span>
                <?php if ($phone): ?>
                <a href="https://wa.me/<?php echo $phone; ?>?text=<?php echo $whatsappMsg; ?>" target="_blank" class="whatsapp-btn">
                    <iconify-icon icon="ic:baseline-whatsapp"></iconify-icon>
                    WhatsApp
                </a>
                <?php endif; ?>
            </div>
        </div>

        <div class="order-detail-grid">
            <!-- Coluna Principal -->
            <div>
                <!-- Itens do Pedido -->
                <div class="detail-card" style="margin-bottom: 1.5rem;">
                    <div class="detail-card-header">
                        <h3>
                            <iconify-icon icon="solar:box-bold"></iconify-icon>
                            Itens do Pedido
                        </h3>
                        <span style="font-size: 0.85rem; color: var(--text-muted);">
                            <?php echo count($orderItems); ?> <?php echo count($orderItems) === 1 ? 'item' : 'itens'; ?>
                        </span>
                    </div>
                    <div class="detail-card-body">
                        <?php foreach ($orderItems as $item): ?>
                        <div class="order-item">
                            <div class="order-item-image">
                                <img src="<?php echo htmlspecialchars($item['image_url'] ?? '/assets/images/placeholder.png'); ?>" 
                                     alt="<?php echo htmlspecialchars($item['product_name']); ?>"
                                     onerror="this.src='/assets/images/placeholder.png'">
                            </div>
                            <div class="order-item-info">
                                <div class="order-item-name"><?php echo htmlspecialchars($item['product_name'] ?? 'Produto'); ?></div>
                                <?php 
                                // Exibir variações do produto se existirem
                                if (!empty($item['options'])) {
                                    $options = is_string($item['options']) ? json_decode($item['options'], true) : $item['options'];
                                    if (is_array($options) && !empty($options)) {
                                        echo '<div class="order-item-variations">';
                                        foreach ($options as $key => $value) {
                                            if (is_string($value) || is_numeric($value)) {
                                                echo '<span class="variation-badge">';
                                                echo htmlspecialchars(ucfirst($key)) . ': ' . htmlspecialchars($value);
                                                echo '</span> ';
                                            }
                                        }
                                        echo '</div>';
                                    }
                                }
                                ?>
                                <?php if (!empty($item['sku'])): ?>
                                <div class="order-item-sku">SKU: <?php echo htmlspecialchars($item['sku']); ?></div>
                                <?php endif; ?>
                                <div class="order-item-details">
                                    <span class="order-item-qty"><?php echo $item['quantity']; ?>x R$ <?php echo number_format($item['unit_price'], 2, ',', '.'); ?></span>
                                    <span class="order-item-price">R$ <?php echo number_format($item['quantity'] * $item['unit_price'], 2, ',', '.'); ?></span>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <?php if (!empty($order['notes'])): ?>
                <!-- Observações -->
                <div class="detail-card" style="margin-bottom: 1.5rem;">
                    <div class="detail-card-body">
                        <div class="order-notes">
                            <div class="order-notes-title">
                                <iconify-icon icon="solar:chat-round-line-bold"></iconify-icon>
                                Observações do Cliente
                            </div>
                            <?php echo nl2br(htmlspecialchars($order['notes'])); ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <!-- Coluna Lateral -->
            <div>
                <!-- Resumo -->
                <div class="detail-card" style="margin-bottom: 1.5rem;">
                    <div class="detail-card-header">
                        <h3>
                            <iconify-icon icon="solar:wallet-bold"></iconify-icon>
                            Resumo
                        </h3>
                    </div>
                    <div class="detail-card-body">
                        <?php 
                        $subtotal = 0;
                        foreach ($orderItems as $item) {
                            $subtotal += $item['quantity'] * $item['unit_price'];
                        }
                        ?>
                        <div class="order-summary-row">
                            <span>Subtotal</span>
                            <span>R$ <?php echo number_format($subtotal, 2, ',', '.'); ?></span>
                        </div>
                        <div class="order-summary-row">
                            <span>Frete</span>
                            <span>R$ 0,00</span>
                        </div>
                        <div class="order-summary-row total">
                            <span>Total</span>
                            <span class="value">R$ <?php echo number_format($order['total_amount'] ?? $subtotal, 2, ',', '.'); ?></span>
                        </div>

                        <form method="POST" class="status-update-form">
                            <input type="hidden" name="action" value="update_status">
                            <select name="status">
                                <?php foreach ($statusLabels as $k => $v): ?>
                                <option value="<?php echo $k; ?>" <?php echo $order['status'] === $k ? 'selected' : ''; ?>><?php echo $v; ?></option>
                                <?php endforeach; ?>
                            </select>
                            <button type="submit" class="btn btn-primary">Atualizar</button>
                        </form>
                    </div>
                </div>

                <!-- Cliente -->
                <div class="detail-card" style="margin-bottom: 1.5rem;">
                    <div class="detail-card-header">
                        <h3>
                            <iconify-icon icon="solar:user-bold"></iconify-icon>
                            Cliente
                        </h3>
                    </div>
                    <div class="detail-card-body" style="padding: 0.5rem 1.25rem;">
                        <div class="customer-info-row">
                            <iconify-icon icon="solar:user-bold"></iconify-icon>
                            <span><?php echo htmlspecialchars($order['customer_name'] ?? 'Não informado'); ?></span>
                        </div>
                        <?php if (!empty($order['customer_phone'])): ?>
                        <div class="customer-info-row">
                            <iconify-icon icon="solar:phone-bold"></iconify-icon>
                            <span><?php echo htmlspecialchars($order['customer_phone']); ?></span>
                            <a href="tel:<?php echo preg_replace('/\D/', '', $order['customer_phone']); ?>">
                                <iconify-icon icon="solar:phone-calling-bold"></iconify-icon>
                            </a>
                        </div>
                        <?php endif; ?>
                        <?php if (!empty($order['customer_email'])): ?>
                        <div class="customer-info-row">
                            <iconify-icon icon="solar:letter-bold"></iconify-icon>
                            <span><?php echo htmlspecialchars($order['customer_email']); ?></span>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <?php if (!empty($order['delivery_address'])): ?>
                <!-- Endereço -->
                <div class="detail-card">
                    <div class="detail-card-header">
                        <h3>
                            <iconify-icon icon="solar:map-point-bold"></iconify-icon>
                            Endereço de Entrega
                        </h3>
                    </div>
                    <div class="detail-card-body">
                        <p class="address-text"><?php echo nl2br(htmlspecialchars($order['delivery_address'])); ?></p>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</main>

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