<?php
$pf        = $prefill ?? [];
$pfAddress = $pf['address']        ?? '';
$pfLat     = $pf['lat']            ?? '';
$pfLng     = $pf['lng']            ?? '';
$pfNotes   = $pf['notes']          ?? '';
$pfPay     = $pf['payment_method'] ?? 'cash';
$pfType    = $pf['order_type']     ?? 'delivery';
$hasPrefill = !empty($pfAddress);
?>
<div style="padding:14px 14px 100px;">

<?php if ($hasPrefill): ?>
<div style="margin-bottom:10px;padding:10px 14px;background:#f0fdf4;border-radius:10px;
            border:1.5px solid #bbf7d0;font-size:.78rem;color:#15803d;display:flex;align-items:center;gap:8px;">
    <i class="bi bi-magic" style="font-size:1rem;"></i>
    <span>Details filled from your last order. Update if needed.</span>
</div>
<?php endif; ?>

<form method="POST" action="<?= url('shop/place-order') ?>" id="checkoutForm">
<?= csrf_field() ?>
<input type="hidden" name="delivery_lat" id="hidLat" value="<?= e($pfLat) ?>">
<input type="hidden" name="delivery_lng" id="hidLng" value="<?= e($pfLng) ?>">
<input type="hidden" name="order_type"   id="hidOrderType" value="<?= e($pfType) ?>">

<!-- ── Contact Details ── -->
<div class="s-card">
    <div class="s-card-title"><i class="bi bi-person-fill"></i> Your Details</div>

    <?php if (!$isGuest): ?>
    <?php
    $pfName  = $pf['name']  ?? '';
    $pfPhone = $pf['phone'] ?? '';
    ?>
    <!-- Logged-in: show name & phone as editable fields -->
    <div style="margin-bottom:12px;">
        <label class="form-label">Full Name</label>
        <input type="text" name="contact_name" class="form-control"
               value="<?= e($pfName) ?>" placeholder="Your name" autocomplete="name">
    </div>
    <div>
        <label class="form-label">Phone Number</label>
        <input type="tel" name="contact_phone" class="form-control"
               value="<?= e($pfPhone) ?>" placeholder="03xx-xxxxxxx" autocomplete="tel">
    </div>

    <?php else: ?>
    <!-- Guest: full input form -->
    <div style="font-size:.78rem;color:var(--muted);margin-bottom:14px;">
        No account needed.
        <a href="<?= url('shop/login') ?>" style="color:var(--accent);font-weight:600;">Sign in</a> for faster checkout.
    </div>
    <div style="margin-bottom:12px;">
        <label class="form-label">Full Name <span style="color:var(--danger);">*</span></label>
        <input type="text" name="guest_name" id="guestName" class="form-control"
               placeholder="e.g. Ahmed Khan" required autocomplete="name">
    </div>
    <div style="margin-bottom:12px;">
        <label class="form-label">Phone Number <span style="color:var(--danger);">*</span></label>
        <input type="tel" name="guest_phone" id="guestPhone" class="form-control"
               placeholder="03xx-xxxxxxx" required autocomplete="tel">
    </div>
    <div>
        <label class="form-label">Email <span style="color:var(--muted);font-weight:400;">(optional)</span></label>
        <input type="email" name="guest_email" id="guestEmail" class="form-control"
               placeholder="you@example.com" autocomplete="email">
    </div>
    <?php endif; ?>
</div>

<!-- ── Order Type ── -->
<div class="s-card">
    <div class="s-card-title"><i class="bi bi-bag-fill"></i> Order Type</div>

    <div class="order-type-cards">
        <div class="order-type-card selected" id="typeDelivery" onclick="setOrderType('delivery')">
            <i class="bi bi-truck"></i>
            <span>Delivery</span>
        </div>
        <div class="order-type-card" id="typePickup" onclick="setOrderType('pickup')">
            <i class="bi bi-shop"></i>
            <span>Pickup</span>
        </div>
    </div>

    <!-- Delivery address section -->
    <div id="addressWrap" style="margin-top:16px;">
        <label class="form-label">Delivery Address <span style="color:var(--danger);">*</span></label>
        <textarea name="address" id="addressField" class="form-control" rows="3"
                  placeholder="House #, Street, Area, City" required><?= e($pfAddress) ?></textarea>

        <!-- GPS location button -->
        <button type="button" id="locBtn" onclick="useMyLocation()"
                style="width:100%;margin-top:8px;padding:10px 14px;border:2px dashed var(--accent);
                       border-radius:10px;background:var(--accent-soft);color:var(--accent);
                       font-size:.82rem;font-weight:700;cursor:pointer;display:flex;
                       align-items:center;justify-content:center;gap:8px;transition:all .15s;">
            <i class="bi bi-geo-alt-fill" id="locIcon" style="font-size:1rem;"></i>
            <span id="locBtnText">Use My Current Location</span>
        </button>
        <div id="locStatus" style="font-size:.75rem;margin-top:6px;text-align:center;"></div>

        <!-- Map preview (shown after GPS capture) -->
        <div id="mapWrap" style="display:none;margin-top:10px;border-radius:12px;overflow:hidden;border:2px solid var(--accent);position:relative;">
            <div id="deliveryMap" style="height:200px;width:100%;"></div>
            <div style="position:absolute;bottom:0;left:0;right:0;background:rgba(0,0,0,.45);
                        color:#fff;font-size:.72rem;padding:5px 10px;display:flex;align-items:center;gap:6px;z-index:999;">
                <i class="bi bi-geo-alt-fill" style="color:#f97316;"></i>
                <span id="mapCoordLabel"></span>
                <a id="mapExtLink" href="#" target="_blank"
                   style="margin-left:auto;color:#fff;font-size:.7rem;text-decoration:underline;">
                    Open in Google Maps
                </a>
            </div>
        </div>

        <?php if ($chargeType === 'per_km'): ?>
        <div style="font-size:.72rem;color:var(--accent);margin-top:4px;">
            <i class="bi bi-info-circle me-1"></i>
            Fee is <?= money($perKmRate) ?>/km<?= $minFee > 0 ? ', min '.money($minFee) : '' ?>. Share your location to get an exact fee.
        </div>
        <?php elseif ($chargeType === 'free'): ?>
        <div style="font-size:.72rem;color:#16a34a;margin-top:4px;">
            <i class="bi bi-gift-fill me-1"></i> Free delivery!
        </div>
        <?php endif; ?>
    </div>

    <!-- Pickup note -->
    <div id="pickupNote" style="display:none;margin-top:12px;padding:12px;
         background:#f0fdf4;border-radius:10px;border:1.5px solid #bbf7d0;">
        <div style="font-size:.85rem;font-weight:700;color:#15803d;margin-bottom:2px;">
            <i class="bi bi-shop me-1"></i> Self Pickup
        </div>
        <div style="font-size:.78rem;color:#166534;">Come to the restaurant and collect your order.</div>
    </div>

    <!-- Special instructions (always visible) -->
    <div style="margin-top:14px;">
        <label class="form-label">Special Instructions <span style="color:var(--muted);font-weight:400;">(optional)</span></label>
        <input type="text" name="notes" class="form-control" placeholder="e.g. Extra spicy, no onions, ring bell…" value="<?= e($pfNotes) ?>">
    </div>
</div>

<!-- ── Payment Method ── -->
<div class="s-card">
    <div class="s-card-title"><i class="bi bi-credit-card-fill"></i> Payment Method</div>

    <div class="pay-option <?= $pfPay !== 'card' ? 'selected' : '' ?>" id="payCash" onclick="selectPay(this)">
        <input type="radio" name="payment_method" value="cash" <?= $pfPay !== 'card' ? 'checked' : '' ?>>
        <div class="pay-icon" style="background:#f0fdf4;"><i class="bi bi-cash" style="color:#16a34a;"></i></div>
        <div class="pay-info">
            <div class="pi-title">Cash on Delivery</div>
            <div class="pi-sub">Pay when you receive</div>
        </div>
        <div class="pay-check"></div>
    </div>

    <div class="pay-option <?= $pfPay === 'card' ? 'selected' : '' ?>" id="payCard" onclick="selectPay(this)">
        <input type="radio" name="payment_method" value="card" <?= $pfPay === 'card' ? 'checked' : '' ?>>
        <div class="pay-icon" style="background:#eff6ff;"><i class="bi bi-credit-card" style="color:#3b82f6;"></i></div>
        <div class="pay-info">
            <div class="pi-title">Card / Online</div>
            <div class="pi-sub">Pay now securely</div>
        </div>
        <div class="pay-check"></div>
    </div>
</div>

<!-- ── Voucher ── -->
<div class="s-card">
    <div class="s-card-title"><i class="bi bi-ticket-perforated-fill"></i> Voucher Code</div>
    <div class="voucher-row">
        <input type="text" id="voucherInput" name="voucher_code" class="form-control"
               placeholder="Enter promo code" value="<?= e($_SESSION['pending_voucher'] ?? '') ?>">
        <button type="button" class="voucher-btn" onclick="applyVoucher()">Apply</button>
    </div>
    <div id="voucherMsg" style="margin-top:8px;font-size:.78rem;"></div>
</div>

<!-- ── Order Summary ── -->
<div class="order-summary">
    <div style="font-size:.85rem;font-weight:700;margin-bottom:12px;">Order Summary</div>
    <?php foreach ($cart as $item): ?>
    <div class="summary-row">
        <span><?= e($item['name']) ?><?= $item['choices_label'] ? ' ('.$item['choices_label'].')' : '' ?> ×<?= $item['qty'] ?></span>
        <span><?= money($item['unit_price'] * $item['qty']) ?></span>
    </div>
    <?php endforeach; ?>
    <div class="summary-divider"></div>
    <div class="summary-row"><span>Subtotal</span><span><?= money($subtotal) ?></span></div>
    <div class="summary-row" id="delFeeRow" style="<?= $deliveryFee == 0 ? 'display:none;' : '' ?>">
        <span>Delivery Fee</span>
        <span id="delFeeVal"><?= money($deliveryFee) ?></span>
    </div>
    <?php if ($taxAmount > 0): ?>
    <div class="summary-row"><span>Tax</span><span id="taxVal"><?= money($taxAmount) ?></span></div>
    <?php endif; ?>
    <div class="summary-row" id="discRow" style="display:none;">
        <span style="color:var(--success);">Voucher Discount</span>
        <span style="color:var(--success);font-weight:700;" id="discVal">−Rs. 0.00</span>
    </div>
    <div class="summary-divider"></div>
    <div class="summary-total"><span>Total</span><span id="grandTotal"><?= money($total) ?></span></div>
</div>

<button type="submit" class="place-order-btn">
    <i class="bi bi-check-circle-fill"></i> Place Order
</button>

</form>
</div>

<?php ob_start(); ?>
<script>
const _base    = <?= (float)$subtotal ?>;
const _taxRate = <?= (float)$taxRate ?>;
let   _del     = <?= (float)$deliveryFee ?>;
let   _disc    = 0;
let   _curLat  = <?= $pfLat !== '' ? (float)$pfLat : 'null' ?>;
let   _curLng  = <?= $pfLng !== '' ? (float)$pfLng : 'null' ?>;

/* ── Totals ──────────────────────────────────────────────────────────────── */
function recalcTotal() {
    const taxAmt = Math.round(_base * _taxRate / 100 * 100) / 100;
    const total  = Math.max(0, _base + _del + taxAmt - _disc);
    document.getElementById('grandTotal').textContent = 'Rs. ' + total.toFixed(2);
    const taxEl = document.getElementById('taxVal');
    if (taxEl) taxEl.textContent = 'Rs. ' + taxAmt.toFixed(2);
    const delRow = document.getElementById('delFeeRow');
    const delVal = document.getElementById('delFeeVal');
    if (_del > 0) {
        delRow.style.display = '';
        delVal.textContent   = 'Rs. ' + _del.toFixed(2);
    } else {
        delRow.style.display = 'none';
    }
}

/* ── Delivery fee from server ────────────────────────────────────────────── */
async function refreshDeliveryFee(orderType, lat, lng) {
    const fd = new FormData();
    fd.append('order_type', orderType);
    if (lat != null) fd.append('lat', lat);
    if (lng != null) fd.append('lng', lng);
    fd.append('_csrf', _CSRF);
    try {
        const res  = await fetch('<?= url('shop/delivery-fee') ?>', { method: 'POST', body: fd });
        const data = await res.json();
        _del = parseFloat(data.fee) || 0;
        recalcTotal();
    } catch (e) {}
}

/* ── Order type toggle ───────────────────────────────────────────────────── */
function setOrderType(type) {
    const isDel = type === 'delivery';
    document.getElementById('hidOrderType').value          = type;
    document.getElementById('addressWrap').style.display  = isDel ? '' : 'none';
    document.getElementById('pickupNote').style.display   = isDel ? 'none' : '';
    const addrField = document.getElementById('addressField');
    addrField.required = isDel;
    document.getElementById('typeDelivery').classList.toggle('selected', isDel);
    document.getElementById('typePickup').classList.toggle('selected', !isDel);
    refreshDeliveryFee(type, _curLat, _curLng);
}

/* ── Payment toggle ──────────────────────────────────────────────────────── */
function selectPay(el) {
    document.querySelectorAll('.pay-option').forEach(o => o.classList.remove('selected'));
    el.classList.add('selected');
    el.querySelector('input[type="radio"]').checked = true;
}

/* ── Voucher ─────────────────────────────────────────────────────────────── */
async function applyVoucher() {
    const code = document.getElementById('voucherInput').value.trim();
    const msg  = document.getElementById('voucherMsg');
    if (!code) return;
    const fd = new FormData();
    fd.append('code', code);
    fd.append('total', _base);
    fd.append('_csrf', _CSRF);
    const res  = await fetch('<?= url('shop/voucher/validate') ?>', { method: 'POST', body: fd });
    const data = await res.json();
    if (data.valid) {
        _disc = data.discount;
        msg.innerHTML = `<span style="color:var(--success);font-weight:700;"><i class="bi bi-check-circle me-1"></i>Saved Rs. ${data.discount.toFixed(2)}!</span>`;
        document.getElementById('discRow').style.display = '';
        document.getElementById('discVal').textContent   = '−Rs. ' + data.discount.toFixed(2);
        recalcTotal();
    } else {
        msg.innerHTML = `<span style="color:var(--danger);"><i class="bi bi-x-circle me-1"></i>${data.message}</span>`;
    }
}

/* ── Leaflet map ─────────────────────────────────────────────────────────── */
let _map    = null;
let _marker = null;

function showMap(lat, lng) {
    const wrap = document.getElementById('mapWrap');
    wrap.style.display = '';

    if (!_map) {
        _map = L.map('deliveryMap', { zoomControl: true, attributionControl: false });
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(_map);

        // Custom orange pin icon
        const pinIcon = L.divIcon({
            className: '',
            html: `<div style="width:32px;height:32px;background:#f97316;border-radius:50% 50% 50% 0;
                         transform:rotate(-45deg);border:3px solid #fff;
                         box-shadow:0 2px 8px rgba(0,0,0,.35);"></div>`,
            iconSize:   [32, 32],
            iconAnchor: [16, 32],
        });
        _marker = L.marker([lat, lng], { icon: pinIcon, draggable: true }).addTo(_map);

        // Allow dragging the pin to fine-tune location
        _marker.on('dragend', async () => {
            const pos = _marker.getLatLng();
            _curLat = pos.lat;
            _curLng = pos.lng;
            document.getElementById('hidLat').value = _curLat;
            document.getElementById('hidLng').value = _curLng;
            updateMapMeta(_curLat, _curLng);
            // Reverse geocode the dragged position
            try {
                const resp = await fetch(
                    `https://nominatim.openstreetmap.org/reverse?lat=${_curLat}&lon=${_curLng}&format=json&addressdetails=1`,
                    { headers: { 'Accept-Language': 'en' } }
                );
                const data = await resp.json();
                const a    = data.address || {};
                const parts = [
                    a.house_number,
                    a.road || a.pedestrian || a.footway,
                    a.suburb || a.neighbourhood || a.quarter,
                    a.city || a.town || a.village || a.county,
                    a.state, a.postcode,
                ].filter(Boolean);
                document.getElementById('addressField').value = parts.length ? parts.join(', ') : data.display_name;
            } catch {}
            const orderType = document.getElementById('hidOrderType').value;
            await refreshDeliveryFee(orderType, _curLat, _curLng);
        });
    } else {
        _marker.setLatLng([lat, lng]);
    }

    _map.setView([lat, lng], 16);
    updateMapMeta(lat, lng);

    // Leaflet needs a size recalc after display:none → visible
    setTimeout(() => _map.invalidateSize(), 50);
}

function updateMapMeta(lat, lng) {
    document.getElementById('mapCoordLabel').textContent =
        lat.toFixed(5) + ', ' + lng.toFixed(5);
    document.getElementById('mapExtLink').href =
        `https://www.google.com/maps?q=${lat},${lng}`;
}

/* ── Live GPS location ───────────────────────────────────────────────────── */
function useMyLocation() {
    const btn     = document.getElementById('locBtn');
    const icon    = document.getElementById('locIcon');
    const btnText = document.getElementById('locBtnText');
    const status  = document.getElementById('locStatus');
    const field   = document.getElementById('addressField');

    if (!navigator.geolocation) {
        status.innerHTML = '<span style="color:var(--danger);">Geolocation not supported by your browser.</span>';
        return;
    }

    // Loading state
    icon.className      = 'bi bi-arrow-repeat';
    icon.style.cssText  = 'font-size:1rem;animation:spin 1s linear infinite;';
    btnText.textContent = 'Detecting location…';
    btn.style.opacity   = '.7';
    btn.disabled        = true;
    status.innerHTML    = '';

    navigator.geolocation.getCurrentPosition(
        async (pos) => {
            _curLat = pos.coords.latitude;
            _curLng = pos.coords.longitude;
            document.getElementById('hidLat').value = _curLat;
            document.getElementById('hidLng').value = _curLng;

            btnText.textContent = 'Fetching address…';
            try {
                const resp = await fetch(
                    `https://nominatim.openstreetmap.org/reverse?lat=${_curLat}&lon=${_curLng}&format=json&addressdetails=1`,
                    { headers: { 'Accept-Language': 'en' } }
                );
                const data = await resp.json();
                const a    = data.address || {};
                const parts = [
                    a.house_number,
                    a.road || a.pedestrian || a.footway,
                    a.suburb || a.neighbourhood || a.quarter,
                    a.city || a.town || a.village || a.county,
                    a.state, a.postcode,
                ].filter(Boolean);
                field.value = parts.length ? parts.join(', ') : data.display_name;
            } catch {
                field.value = `${_curLat.toFixed(6)}, ${_curLng.toFixed(6)}`;
            }

            // Show map
            showMap(_curLat, _curLng);

            // Success state on button
            icon.className      = 'bi bi-geo-alt-fill';
            icon.style.cssText  = 'font-size:1rem;';
            btnText.textContent = 'Location Set — Tap to update';
            btn.style.background = '#f0fdf4';
            btn.style.borderColor = '#16a34a';
            btn.style.color       = '#16a34a';
            btn.style.opacity     = '1';
            btn.disabled          = false;
            status.innerHTML = '<i class="bi bi-check-circle-fill" style="color:#16a34a;"></i>'
                             + ' <span style="color:#16a34a;">Location captured. Drag the pin to fine-tune.</span>';

            // Recalculate delivery fee with precise coordinates
            const orderType = document.getElementById('hidOrderType').value;
            await refreshDeliveryFee(orderType, _curLat, _curLng);
        },
        (err) => {
            const msgs = {
                1: 'Location permission denied. Please allow location access in your browser.',
                2: 'Location unavailable. Please enter your address manually.',
                3: 'Request timed out. Please try again.',
            };
            icon.className      = 'bi bi-geo-alt-fill';
            icon.style.cssText  = 'font-size:1rem;';
            btnText.textContent = 'Use My Current Location';
            btn.style.opacity   = '1';
            btn.disabled        = false;
            status.innerHTML    = `<span style="color:var(--danger);"><i class="bi bi-x-circle-fill me-1"></i>${msgs[err.code] || 'Could not get location.'}</span>`;
        },
        { timeout: 12000, maximumAge: 60000 }
    );
}

// ── Restore prefilled state on page load ────────────────────────────────────
(function initPrefill() {
    const pfType = '<?= e($pfType) ?>';
    // Restore order type (pickup or delivery)
    if (pfType === 'pickup') setOrderType('pickup');

    // If we have saved coordinates, show the map and recalculate fee
    if (_curLat !== null && _curLng !== null) {
        showMap(_curLat, _curLng);
        refreshDeliveryFee(pfType, _curLat, _curLng);
    }

    // ── Guest: restore last-used details from localStorage ──────────────────
    const nameEl  = document.getElementById('guestName');
    const phoneEl = document.getElementById('guestPhone');
    const emailEl = document.getElementById('guestEmail');
    if (nameEl) {
        const saved = JSON.parse(localStorage.getItem('_guestInfo') || '{}');
        if (saved.name)  nameEl.value  = saved.name;
        if (saved.phone) phoneEl.value = saved.phone;
        if (saved.email && emailEl) emailEl.value = saved.email;
        // Show hint if we restored something
        if (saved.name || saved.phone) {
            const hint = document.createElement('div');
            hint.style.cssText = 'font-size:.72rem;color:#15803d;margin-top:8px;';
            hint.innerHTML = '<i class="bi bi-magic me-1"></i>Filled from your last visit. Update if needed.';
            nameEl.closest('.s-card').appendChild(hint);
        }
    }

    // Save guest info when form submits
    const form = document.getElementById('checkoutForm');
    form.addEventListener('submit', () => {
        if (nameEl) {
            localStorage.setItem('_guestInfo', JSON.stringify({
                name:  nameEl.value.trim(),
                phone: phoneEl ? phoneEl.value.trim() : '',
                email: emailEl ? emailEl.value.trim() : '',
            }));
        }
    });
})();
</script>
<style>
@keyframes spin { to { transform: rotate(360deg); } }
</style>
<?php $extraJs = ob_get_clean(); ?>
