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

<?php
$subtotal = $subtotal ?? 0;
$deliveryFee = $deliveryFee ?? 0;
$total = $total ?? ($subtotal + $deliveryFee);
$prefs = $prefs ?? [
    'mode' => 'delivery',
    'name' => '',
    'phone' => '',
    'address' => '',
    'neighborhood' => '',
    'delivery_fee' => 0,
];
$savedCustomer = $savedCustomer ?? null;
?>

<div class="container" style="margin-top: 20px;">
    <div class="layout-with-cart">
        <div class="layout-main">
            <div class="card">
                <h2 style="color: var(--accent);">Finalizar Pedido</h2>
                
                <div class="mobile-only-block" style="margin-bottom: 20px; border: 1px solid #eee; border-radius: 8px; padding: 10px; background: #fafafa;">
                    <h3 style="font-size: 1rem; margin-top: 0; color: #555;">Resumo da Sacola</h3>
                    <?php if (empty($cart)): ?>
                        <p style="color: #999;">Sacola vazia</p>
                    <?php else: ?>
                        <ul style="padding-left: 20px; margin-bottom: 0;">
                            <?php foreach ($cart as $item): ?>
                                <li style="margin-bottom: 5px;">
                                    <strong><?= htmlspecialchars($item['name']) ?></strong> x<?= $item['quantity'] ?>
                                    <br>
                                    <span style="color: #555;">R$ <?= number_format($item['total_price'], 2, ',', '.') ?></span>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                </div>

                <?php if ($savedCustomer): ?>
                    <div style="background: #fff7e6; border: 1px solid #ffe0b2; padding: 10px; border-radius: 8px; margin-bottom: 15px; font-size: 0.9rem;">
                        <strong>Encontramos seus dados salvos:</strong><br>
                        Endereço: <?= htmlspecialchars($savedCustomer['address'] ?? '') ?><br>
                        <span>Esse endereço ainda é o mesmo?</span>
                        <div style="margin-top: 8px; display: flex; gap: 8px;">
                            <button type="button" id="address-ok" class="btn" style="padding: 6px 10px; font-size: 0.8rem;">Sim, pode usar</button>
                            <button type="button" id="address-change" class="btn" style="padding: 6px 10px; font-size: 0.8rem; background: #ccc;">Não, quero alterar</button>
                        </div>
                    </div>
                <?php endif; ?>

                <form action="/checkout/process" method="POST">
                    <input type="hidden" name="delivery_fee" value="<?= htmlspecialchars((string) $deliveryFee) ?>">

                    <div style="margin-bottom: 20px;">
                        <label style="display: block; margin-bottom: 10px; font-weight: 600;">Como você quer receber?</label>
                        <div style="display: flex; gap: 10px;">
                            <label style="flex: 1; cursor: pointer;">
                                <input type="radio" name="mode" value="delivery" <?= ($prefs['mode'] ?? 'delivery') === 'delivery' ? 'checked' : '' ?> style="display: none;" onchange="toggleDeliveryMode(this.value)">
                                <div class="mode-btn" style="text-align: center; padding: 12px; border: 1px solid #ddd; border-radius: 8px; background: #fff; transition: all 0.2s;">
                                    <span style="font-size: 1.2rem;">🛵</span><br>Entrega
                                </div>
                            </label>
                            <label style="flex: 1; cursor: pointer;">
                                <input type="radio" name="mode" value="pickup" <?= ($prefs['mode'] ?? 'delivery') === 'pickup' ? 'checked' : '' ?> style="display: none;" onchange="toggleDeliveryMode(this.value)">
                                <div class="mode-btn" style="text-align: center; padding: 12px; border: 1px solid #ddd; border-radius: 8px; background: #fff; transition: all 0.2s;">
                                    <span style="font-size: 1.2rem;">🏪</span><br>Retirada
                                </div>
                            </label>
                        </div>
                    </div>

                    <div style="margin-bottom: 15px;">
                        <label>Seu Nome:</label>
                        <input type="text" name="name" required style="width: 100%; padding: 10px;" value="<?= htmlspecialchars($prefs['name']) ?>">
                    </div>
                    
                    <div style="margin-bottom: 15px;">
                        <label>WhatsApp:</label>
                        <input type="text" name="phone" required style="width: 100%; padding: 10px;" value="<?= htmlspecialchars($prefs['phone']) ?>">
                    </div>

                    <div id="delivery-fields" style="<?= ($prefs['mode'] ?? 'delivery') === 'delivery' ? '' : 'display:none;' ?>">
                        <div style="margin-bottom: 15px;">
                            <label>Bairro:</label>
                            <select name="neighborhood" id="checkout-neighborhood" style="width: 100%; padding: 10px;">
                                <option value="">Selecione o bairro</option>
                                <?php if (!empty($deliveryZones)): ?>
                                    <?php foreach ($deliveryZones as $zone): ?>
                                        <option value="<?= htmlspecialchars($zone['neighborhood']) ?>" data-fee="<?= $zone['fee'] ?>" <?= ($prefs['neighborhood'] ?? '') === $zone['neighborhood'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($zone['neighborhood']) ?> (+ R$ <?= number_format($zone['fee'], 2, ',', '.') ?>)
                                        </option>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <option value="Centro" data-fee="0" <?= ($prefs['neighborhood'] ?? '') === 'Centro' ? 'selected' : '' ?>>Centro</option>
                                <?php endif; ?>
                            </select>
                        </div>

                        <div style="margin-bottom: 15px;">
                            <label>Endereço de Entrega:</label>
                            <textarea name="address" id="address-field" rows="3" style="width: 100%; padding: 10px;"><?= htmlspecialchars($prefs['mode'] === 'delivery' ? $prefs['address'] : '') ?></textarea>
                        </div>
                    </div>
                    
                    <div id="pickup-info" style="<?= ($prefs['mode'] ?? 'delivery') === 'pickup' ? '' : 'display:none;' ?>; background: #e8f5e9; padding: 15px; border-radius: 8px; margin-bottom: 15px; border: 1px solid #c8e6c9;">
                        <strong>📍 Retirada na loja</strong><br>
                        <small>Endereço: Fenda do Biquíni, 123 (Ao lado do Balde de Lixo)</small><br>
                        <small style="color: green;">Taxa de entrega GRÁTIS</small>
                    </div>

                    <div style="margin-bottom: 15px;">

                    <div style="margin-bottom: 15px;">
                        <label>Forma de Pagamento:</label>
                        <select name="payment" required style="width: 100%; padding: 10px;">
                            <option value="pix">Pix (Aprovação Instantânea)</option>
                            <option value="cartao">Cartão na Entrega/Retirada</option>
                            <option value="dinheiro">Dinheiro (Conchas)</option>
                        </select>
                    </div>

                    <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 15px; border: 1px solid #eee;">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                            <span>Subtotal:</span>
                            <span>R$ <?= number_format($subtotal, 2, ',', '.') ?></span>
                        </div>
                        <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                            <span>Taxa de entrega:</span>
                            <span id="checkout-delivery-fee-display">R$ <?= number_format($deliveryFee, 2, ',', '.') ?></span>
                        </div>
                        <div style="display: flex; justify-content: space-between; font-weight: bold; font-size: 1.1rem; margin-top: 10px; border-top: 1px solid #ddd; padding-top: 10px;">
                            <span>Total:</span>
                            <span id="checkout-total-display">R$ <?= number_format($total, 2, ',', '.') ?></span>
                        </div>
                    </div>

                    <button type="submit" class="btn" style="width: 100%;">Confirmar Pedido</button>
                </form>
            </div>
        </div>

        <aside class="cart-sidebar">
            <div class="card cart-summary-card">
                <div class="cart-summary-body">
                    <h3 style="margin-top: 0; margin-bottom: 10px; font-size: 1rem;">Resumo do pedido</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 $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, ',', '.') ?></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 id="sidebar-delivery-fee">R$ <?= number_format($deliveryFee, 2, ',', '.') ?></span>
                    </div>
                    <div class="cart-totals-row cart-total">
                        <span>Total</span>
                        <span id="sidebar-total">R$ <?= number_format($total, 2, ',', '.') ?></span>
                    </div>
                </div>
            </div>
        </aside>
    </div>
</div>

<script>
    (function () {
        var changeBtn = document.getElementById('address-change');
        var okBtn = document.getElementById('address-ok');
        var addressField = document.getElementById('address-field');
        
        // Novos elementos para cálculo de taxa
        var neighborhoodSelect = document.getElementById('checkout-neighborhood');
        var deliveryFeeInput = document.querySelector('input[name="delivery_fee"]');
        var displayFee = document.getElementById('checkout-delivery-fee-display');
        var displayTotal = document.getElementById('checkout-total-display');
        var sidebarFee = document.getElementById('sidebar-delivery-fee');
        var sidebarTotal = document.getElementById('sidebar-total');
        
        var subtotal = <?= json_encode((float)$subtotal) ?>;

        window.toggleDeliveryMode = function(mode) {
            var deliveryFields = document.getElementById('delivery-fields');
            var pickupInfo = document.getElementById('pickup-info');
            
            // Atualizar estilo dos botões
            document.querySelectorAll('input[name="mode"]').forEach(function(input) {
                var btn = input.nextElementSibling;
                if (input.checked) {
                    btn.style.borderColor = 'var(--primary)'; // Assumindo que --primary existe
                    btn.style.background = '#fff7e6';
                } else {
                    btn.style.borderColor = '#ddd';
                    btn.style.background = '#fff';
                }
            });

            if (mode === 'delivery') {
                if (deliveryFields) deliveryFields.style.display = 'block';
                if (pickupInfo) pickupInfo.style.display = 'none';
                updateTotals(); 
            } else {
                if (deliveryFields) deliveryFields.style.display = 'none';
                if (pickupInfo) pickupInfo.style.display = 'block';
                updateTotals(true);
            }
        };

        function updateTotals(forceZeroFee) {
            var fee = 0;
            if (forceZeroFee !== true && neighborhoodSelect) {
                var selectedOption = neighborhoodSelect.options[neighborhoodSelect.selectedIndex];
                if (selectedOption) {
                    fee = parseFloat(selectedOption.getAttribute('data-fee') || 0);
                }
            }
            
            // Atualiza input hidden
            if (deliveryFeeInput) deliveryFeeInput.value = fee.toFixed(2);
            
            var total = subtotal + fee;
            
            var feeFormatted = 'R$ ' + fee.toLocaleString('pt-BR', {minimumFractionDigits: 2, maximumFractionDigits: 2});
            var totalFormatted = 'R$ ' + total.toLocaleString('pt-BR', {minimumFractionDigits: 2, maximumFractionDigits: 2});
            
            if (displayFee) displayFee.textContent = feeFormatted;
            if (displayTotal) displayTotal.textContent = totalFormatted;
            if (sidebarFee) sidebarFee.textContent = feeFormatted;
            if (sidebarTotal) sidebarTotal.textContent = totalFormatted;
        }

        // Inicializar estilos dos botões no carregamento
        document.addEventListener('DOMContentLoaded', function() {
            var checkedMode = document.querySelector('input[name="mode"]:checked');
            if (checkedMode) {
                toggleDeliveryMode(checkedMode.value);
            }
        });

        if (neighborhoodSelect) {
            neighborhoodSelect.addEventListener('change', function() { updateTotals(); });
        }

        if (changeBtn && addressField) {
            changeBtn.addEventListener('click', function () {
                addressField.value = '';
                addressField.focus();
            });
        }
        if (okBtn && addressField) {
            okBtn.addEventListener('click', function () {
                addressField.focus();
            });
        }
    })();
</script>

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