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

<?php
$cart = $_SESSION['cart'] ?? [];
$subtotal = 0;
foreach ($cart as $item) {
    $subtotal += $item['total_price'];
}
$prefs = $_SESSION['checkout_prefs'] ?? [
    'mode' => 'delivery',
    'name' => '',
    'phone' => '',
    'address' => '',
    'neighborhood' => '',
    'delivery_fee' => 0,
];
$deliveryFee = $prefs['delivery_fee'] ?? 0;
$cartTotal = $subtotal + $deliveryFee;
?>

<div class="container" style="margin-top: 20px;">
    <div class="layout-with-cart">
        <div class="layout-main">
            <?php foreach ($menu as $category => $products): ?>
                <h2 style="color: white; text-shadow: 1px 1px 0 #000; font-family: 'Space Grotesk'; margin-top: 40px;">
                    <?= htmlspecialchars($category) ?>
                </h2>
                <div class="product-grid">
                    <?php foreach ($products as $product): ?>
                        <div class="product-card">
                            <?php 
                                $imgUrl = $product['image_url'];
                                if ($imgUrl && strpos($imgUrl, 'http') !== 0) {
                                    $imgUrl = $baseUrl . '/' . ltrim($imgUrl, '/');
                                }
                                $displayImg = $imgUrl ?: 'https://placehold.co/400x300?text=Siri+Cascudo';
                            ?>
                            <img src="<?= $displayImg ?>" alt="<?= htmlspecialchars($product['name']) ?>" onerror="this.src='https://placehold.co/400x300?text=Imagem+Indispon%C3%ADvel'">
                            <div class="info">
                                <h3><?= htmlspecialchars($product['name']) ?></h3>
                                <p><?= htmlspecialchars($product['description']) ?></p>
                                <span class="price">R$ <?= number_format($product['base_price'], 2, ',', '.') ?></span>
                                <button 
                                    class="btn"
                                    data-open-product
                                    data-id="<?= $product['id'] ?>"
                                    data-name="<?= htmlspecialchars($product['name'], ENT_QUOTES) ?>"
                                    data-description="<?= htmlspecialchars($product['description'], ENT_QUOTES) ?>"
                                    data-price="<?= number_format($product['base_price'], 2, '.', '') ?>"
                                >
                                    Eu quero!
                                </button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endforeach; ?>
        </div>

        <aside class="cart-sidebar">
            <div class="card cart-summary-card" data-cart-subtotal="<?= number_format($subtotal, 2, '.', '') ?>" data-delivery-fee="<?= number_format($deliveryFee, 2, '.', '') ?>">
                <div class="cart-summary-header" data-toggle="delivery-calc">
                    <span>
                        <span class="cart-summary-header-icon">📍</span>
                        <span>Calcular taxa de entrega</span>
                    </span>
                    <span>›</span>
                </div>

                <div class="delivery-panel">
                    <form class="cart-delivery-form" action="/checkout/preferences" method="POST">
                        <input type="hidden" name="mode" value="<?= htmlspecialchars($prefs['mode']) ?>">
                        <input type="hidden" name="delivery_fee" value="<?= number_format($deliveryFee, 2, '.', '') ?>">

                        <div class="delivery-panel-section">
                            <label>Como você quer receber o pedido?</label>
                            <div class="delivery-mode-options">
                                <button type="button" data-mode-select="delivery" class="<?= $prefs['mode'] === 'delivery' ? 'active' : '' ?>">
                                    Delivery<br><small>Receba no seu endereço</small>
                                </button>
                                <button type="button" data-mode-select="pickup" class="<?= $prefs['mode'] === 'pickup' ? 'active' : '' ?>">
                                    Retirada na loja<br><small>Retire no local</small>
                                </button>
                            </div>
                        </div>

                        <div class="delivery-panel-section" data-mode="delivery" style="<?= $prefs['mode'] === 'delivery' ? '' : 'display:none;' ?>">
                            <label>Endereço do cliente</label>
                            <input type="text" name="address" placeholder="Rua, número, complemento" value="<?= htmlspecialchars($prefs['address']) ?>">
                            <div style="margin-top: 8px;">
                                <label>Bairro</label>
                                <select name="neighborhood" id="neighborhood-select">
                                    <option value="">Selecione o bairro</option>
                                    <?php if (!empty($deliveryZones)): ?>
                                        <?php foreach ($deliveryZones as $zone): ?>
                                            <option value="<?= htmlspecialchars($zone['neighborhood']) ?>" data-fee="<?= $zone['fee'] ?>" <?= isset($prefs['neighborhood']) && $prefs['neighborhood'] === $zone['neighborhood'] ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($zone['neighborhood']) ?> (+ R$ <?= number_format($zone['fee'], 2, ',', '.') ?>)
                                            </option>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <option value="Centro" <?= isset($prefs['neighborhood']) && $prefs['neighborhood'] === 'Centro' ? 'selected' : '' ?>>Centro</option>
                                    <?php endif; ?>
                                </select>
                                <small>Taxa configurada por bairro.</small>
                            </div>
                            <div style="margin-top: 8px;">
                                <label>Nome do cliente</label>
                                <input type="text" name="name" value="<?= htmlspecialchars($prefs['name']) ?>" placeholder="Nome completo">
                            </div>
                            <div style="margin-top: 8px;">
                                <label>WhatsApp</label>
                                <input type="text" name="phone" value="<?= htmlspecialchars($prefs['phone']) ?>" placeholder="(00) 00000-0000">
                            </div>
                        </div>

                        <div class="delivery-panel-section" data-mode="pickup" style="<?= $prefs['mode'] === 'pickup' ? '' : 'display:none;' ?>">
                            <label>Dados para retirada na loja</label>
                            <input type="text" name="pickup_name" value="<?= htmlspecialchars($prefs['name']) ?>" placeholder="Nome do cliente">
                            <div style="margin-top: 8px;">
                                <label>WhatsApp</label>
                                <input type="text" name="pickup_phone" value="<?= htmlspecialchars($prefs['phone']) ?>" placeholder="(00) 00000-0000">
                            </div>
                            <small style="display:block; margin-top: 6px;">A taxa de entrega será R$ 0,00 na retirada.</small>
                        </div>

                        <div style="margin-top: 10px; text-align: right;">
                            <button type="submit" class="btn" style="padding: 6px 14px; font-size: 0.8rem;">Salvar forma de recebimento</button>
                        </div>
                    </form>
                </div>

                <div class="cart-summary-body">
                    <h3 style="margin-top: 0; margin-bottom: 10px; font-size: 1rem;">Sua sacola</h3>

                    <?php if (empty($cart)): ?>
                        <div class="cart-empty">
                            <div class="cart-empty-icon">🔒</div>
                            <div>Sacola vazia</div>
                        </div>
                    <?php else: ?>
                        <ul style="list-style: none; padding: 0; margin: 0 0 10px 0; max-height: 200px; overflow-y: auto;">
                            <?php foreach ($cart as $index => $item): ?>
                                <li style="display: flex; justify-content: space-between; margin-bottom: 6px; font-size: 0.85rem;">
                                    <span><?= htmlspecialchars($item['name']) ?> x<?= $item['quantity'] ?></span>
                                    <span>
                                        R$ <?= number_format($item['total_price'], 2, ',', '.') ?>
                                        <a href="/carrinho/remove/<?= $index ?>" style="color: red; margin-left: 5px; text-decoration: none; font-weight: bold;">&times;</a>
                                    </span>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                </div>

                <div class="cart-totals">
                    <div class="cart-totals-row">
                        <span>Subtotal</span>
                        <span>R$ <?= number_format($subtotal, 2, ',', '.') ?></span>
                    </div>
                    <div class="cart-totals-row">
                        <span>Taxa de entrega</span>
                        <span data-cart-delivery-text>R$ <?= number_format($deliveryFee, 2, ',', '.') ?></span>
                    </div>
                    <div class="cart-totals-row cart-total">
                        <span>Total</span>
                        <span data-cart-total-text>R$ <?= number_format($cartTotal, 2, ',', '.') ?></span>
                    </div>
                </div>

                <div class="cart-coupon">
                    <div>Tem um cupom?</div>
                    <a href="javascript:void(0)">Clique e insira o código</a>
                </div>

                <div class="cart-summary-footer">
                    <?php if (empty($cart)): ?>
                        <button class="btn disabled" type="button">Sacola vazia</button>
                    <?php else: ?>
                        <a href="/checkout" class="btn">Ir para pagamento</a>
                    <?php endif; ?>
                </div>
            </div>
        </aside>
    </div>
</div>

<div class="product-modal-backdrop" id="product-modal">
    <div class="product-modal">
        <button type="button" class="product-modal-close" data-modal-close>&times;</button>
        <div class="product-modal-header">
            <h3 data-modal-name></h3>
            <p style="margin-top: 4px; font-size: 0.85rem; color: #555;" data-modal-description></p>
        </div>
        <form action="/carrinho/add" method="POST">
            <div class="product-modal-body">
                <input type="hidden" name="product_id">
                <input type="hidden" name="name">
                <input type="hidden" name="price">
                <input type="hidden" name="redirect" value="/">

                <div class="product-modal-extras-group">
                    <label>
                        <span>
                            <input type="checkbox" name="options[]" value="extra:bacon:3.00">
                            Bacon extra
                        </span>
                        <span>+ R$ 3,00</span>
                    </label>
                    <label>
                        <span>
                            <input type="checkbox" name="options[]" value="extra:hamburguer:5.00">
                            Hambúrguer extra
                        </span>
                        <span>+ R$ 5,00</span>
                    </label>
                    <label>
                        <span>
                            <input type="checkbox" name="options[]" value="extra:maionese:2.00">
                            Maionese extra
                        </span>
                        <span>+ R$ 2,00</span>
                    </label>
                </div>

                <div style="margin-top: 12px;">
                    <label style="font-weight: bold; font-size: 0.85rem;">Observações</label>
                    <textarea name="notes" rows="3" style="width: 100%; border-radius: 6px; border: 1px solid #ddd; padding: 8px; font-size: 0.85rem;" placeholder="Ex: tirar cebola, caprichar na maionese..."></textarea>
                </div>

                <div class="product-modal-qty">
                    <label>Quantidade:</label>
                    <input type="number" name="quantity" value="1" min="1">
                </div>

                <div class="product-modal-price-row">
                    <span>Valor do pedido</span>
                    <span data-modal-total>R$ 0,00</span>
                </div>
            </div>
            <div class="product-modal-footer">
                <button type="submit" class="btn">Adicionar à sacola</button>
            </div>
        </form>
    </div>
</div>

<?php include __DIR__ . '/home_scripts.php'; ?>
<?php include __DIR__ . '/../layout/footer.php'; ?>
