<form method="POST" action="<?= url('settings/update') ?>" enctype="multipart/form-data">
<?= csrf_field() ?>

<div class="page-header">
    <div>
        <h1>Settings</h1>
        <p>Configure restaurant details, fees, and system preferences.</p>
    </div>
    <button type="submit" class="btn btn-accent">
        <i class="bi bi-check-lg me-1"></i> Save Settings
    </button>
</div>

<div class="row g-4">

    <!-- ── Left column ────────────────────────────────────────────────────── -->
    <div class="col-12 col-xl-8">

        <!-- Restaurant Info -->
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-shop text-accent"></i>
                <h6 class="card-title">Restaurant Information</h6>
            </div>
            <div class="card-body">
                <div class="row g-3">

                    <div class="col-12 col-md-6">
                        <label class="form-label">Restaurant Name <span class="text-danger">*</span></label>
                        <input type="text" name="restaurant_name" class="form-control"
                               value="<?= e($settings['restaurant_name'] ?? '') ?>"
                               placeholder="My Restaurant" required>
                    </div>

                    <div class="col-12 col-md-6">
                        <label class="form-label">Phone Number</label>
                        <input type="text" name="restaurant_phone" class="form-control"
                               value="<?= e($settings['restaurant_phone'] ?? '') ?>"
                               placeholder="0300-0000000">
                    </div>

                    <div class="col-12">
                        <label class="form-label">Restaurant Address</label>
                        <textarea name="restaurant_address" class="form-control" rows="2"
                                  placeholder="Full address for customers..."><?= e($settings['restaurant_address'] ?? '') ?></textarea>
                    </div>

                    <!-- Logo -->
                    <div class="col-12">
                        <label class="form-label">Restaurant Logo</label>
                        <div class="d-flex align-items-start gap-3">
                            <?php if (!empty($settings['restaurant_logo'])): ?>
                            <img src="<?= e(upload_url($settings['restaurant_logo'])) ?>"
                                 alt="Logo" style="width:80px;height:80px;border-radius:12px;object-fit:cover;border:2px solid var(--border-color);">
                            <?php else: ?>
                            <div style="width:80px;height:80px;border-radius:12px;background:var(--accent-soft);display:flex;align-items:center;justify-content:center;font-size:2rem;flex-shrink:0;">🍕</div>
                            <?php endif; ?>
                            <div class="flex-grow-1">
                                <input type="file" name="restaurant_logo" class="form-control" accept="image/*">
                                <div class="form-text">PNG or JPG, max 2 MB. Will be resized to 300×300.</div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>

        <!-- Pricing & General Fees -->
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-cash-coin text-accent"></i>
                <h6 class="card-title">Pricing & Fees</h6>
            </div>
            <div class="card-body">
                <div class="row g-3">

                    <div class="col-12 col-md-4">
                        <label class="form-label">Currency Symbol</label>
                        <input type="text" name="currency_symbol" class="form-control"
                               value="<?= e($settings['currency_symbol'] ?? 'Rs.') ?>"
                               placeholder="Rs.">
                    </div>

                    <div class="col-12 col-md-4">
                        <label class="form-label">Tax Rate (%)</label>
                        <div class="input-group">
                            <input type="number" name="tax_rate" class="form-control"
                                   value="<?= e($settings['tax_rate'] ?? '0') ?>"
                                   min="0" max="100" step="0.5" placeholder="0">
                            <span class="input-group-text">%</span>
                        </div>
                        <div class="form-text">Set 0 to disable tax.</div>
                    </div>

                    <div class="col-12 col-md-4">
                        <label class="form-label">Minimum Order Amount</label>
                        <div class="input-group">
                            <span class="input-group-text"><?= e($settings['currency_symbol'] ?? 'Rs.') ?></span>
                            <input type="number" name="min_order_amount" class="form-control"
                                   value="<?= e($settings['min_order_amount'] ?? '0') ?>"
                                   min="0" step="10" placeholder="0">
                        </div>
                        <div class="form-text">Set 0 for no minimum.</div>
                    </div>

                </div>
            </div>
        </div>

        <!-- First Order Discount -->
        <?php
        $foEnabled = ($settings['first_order_discount_enabled'] ?? '0') === '1';
        $foType    = $settings['first_order_discount_type'] ?? 'percentage';
        $curSym    = e($settings['currency_symbol'] ?? 'Rs.');
        ?>
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-gift text-accent"></i>
                <h6 class="card-title">First Order Discount</h6>
            </div>
            <div class="card-body">
                <div class="form-check form-switch mb-3">
                    <input class="form-check-input" type="checkbox" role="switch"
                           id="foEnabled" name="first_order_discount_enabled" value="1"
                           <?= $foEnabled ? 'checked' : '' ?>>
                    <label class="form-check-label" for="foEnabled">
                        Give customers a discount on their first order
                    </label>
                </div>
                <div class="row g-3">
                    <div class="col-12 col-md-3">
                        <label class="form-label">Discount Type</label>
                        <select name="first_order_discount_type" class="form-select">
                            <option value="percentage" <?= $foType === 'percentage' ? 'selected' : '' ?>>Percentage (%)</option>
                            <option value="fixed"      <?= $foType === 'fixed' ? 'selected' : '' ?>>Fixed Amount</option>
                        </select>
                    </div>
                    <div class="col-12 col-md-3">
                        <label class="form-label">Discount Value</label>
                        <input type="number" name="first_order_discount_value" class="form-control"
                               value="<?= e($settings['first_order_discount_value'] ?? '0') ?>"
                               min="0" step="1" placeholder="e.g. 10">
                    </div>
                    <div class="col-12 col-md-3">
                        <label class="form-label">Min. Order Amount</label>
                        <div class="input-group">
                            <span class="input-group-text"><?= $curSym ?></span>
                            <input type="number" name="first_order_min_amount" class="form-control"
                                   value="<?= e($settings['first_order_min_amount'] ?? '0') ?>"
                                   min="0" step="10" placeholder="0">
                        </div>
                    </div>
                    <div class="col-12 col-md-3">
                        <label class="form-label">Max. Discount <span class="text-secondary">(cap)</span></label>
                        <div class="input-group">
                            <span class="input-group-text"><?= $curSym ?></span>
                            <input type="number" name="first_order_max_discount" class="form-control"
                                   value="<?= e($settings['first_order_max_discount'] ?? '0') ?>"
                                   min="0" step="10" placeholder="0 = no cap">
                        </div>
                    </div>
                </div>
                <div class="form-text mt-2">
                    Applied automatically to a customer's very first order. For percentage type,
                    "Max. Discount" caps the amount (0 = no cap). "Min. Order Amount" is the
                    minimum subtotal required (0 = always).
                </div>
            </div>
        </div>

        <!-- Delivery Charges Policy -->
        <?php
        $dct       = $settings['delivery_charge_type'] ?? 'fixed';
        $cur       = e($settings['currency_symbol'] ?? 'Rs.');
        ?>
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-truck text-accent"></i>
                <h6 class="card-title">Delivery Charges Policy</h6>
            </div>
            <div class="card-body">

                <!-- Charge type selector -->
                <div class="mb-4">
                    <label class="form-label fw-600">Charge Type</label>
                    <div class="row g-2">
                        <?php foreach ([
                            'fixed'  => ['bi-tag-fill',     'Fixed Fee',      'Same fee on every delivery order'],
                            'per_km' => ['bi-geo-alt-fill', 'Per Kilometre',  'Fee calculated by distance from restaurant'],
                            'free'   => ['bi-gift-fill',    'Always Free',    'No delivery fee charged'],
                        ] as $val => [$icon, $label, $desc]): ?>
                        <div class="col-12 col-md-4">
                            <label class="d-block border rounded-3 p-3 cursor-pointer delivery-type-card <?= $dct === $val ? 'border-accent bg-accent-soft' : '' ?>"
                                   style="cursor:pointer;" for="dct_<?= $val ?>">
                                <input type="radio" name="delivery_charge_type" value="<?= $val ?>"
                                       id="dct_<?= $val ?>" class="d-none dct-radio"
                                       <?= $dct === $val ? 'checked' : '' ?>>
                                <div class="d-flex align-items-center gap-2 mb-1">
                                    <i class="bi <?= $icon ?> text-accent"></i>
                                    <span class="fw-700" style="font-size:.88rem;"><?= $label ?></span>
                                </div>
                                <div class="text-secondary" style="font-size:.75rem;"><?= $desc ?></div>
                            </label>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Fixed fee fields -->
                <div id="dctFixed" class="row g-3 <?= $dct !== 'fixed' ? 'd-none' : '' ?>">
                    <div class="col-12 col-md-6">
                        <label class="form-label">Fixed Delivery Fee</label>
                        <div class="input-group">
                            <span class="input-group-text"><?= $cur ?></span>
                            <input type="number" name="delivery_fixed_fee" class="form-control"
                                   value="<?= e($settings['delivery_fixed_fee'] ?? $settings['delivery_fee'] ?? '0') ?>"
                                   min="0" step="1" placeholder="0">
                        </div>
                    </div>
                    <div class="col-12 col-md-6">
                        <label class="form-label">Free Delivery Above <span class="text-secondary">(optional)</span></label>
                        <div class="input-group">
                            <span class="input-group-text"><?= $cur ?></span>
                            <input type="number" name="delivery_free_above" class="form-control"
                                   value="<?= e($settings['delivery_free_above'] ?? '0') ?>"
                                   min="0" step="10" placeholder="0 = disabled">
                        </div>
                        <div class="form-text">Set 0 to disable. Orders above this get free delivery.</div>
                    </div>
                </div>

                <!-- Per-km fields -->
                <div id="dctPerKm" class="<?= $dct !== 'per_km' ? 'd-none' : '' ?>">
                    <div class="alert alert-warning py-2" style="font-size:.8rem;">
                        <i class="bi bi-info-circle me-1"></i>
                        Set the restaurant GPS location below so distance can be calculated automatically.
                    </div>
                    <div class="row g-3">
                        <div class="col-12 col-md-4">
                            <label class="form-label">Rate per Kilometre</label>
                            <div class="input-group">
                                <span class="input-group-text"><?= $cur ?></span>
                                <input type="number" name="delivery_per_km_rate" class="form-control"
                                       value="<?= e($settings['delivery_per_km_rate'] ?? '0') ?>"
                                       min="0" step="1" placeholder="0">
                            </div>
                        </div>
                        <div class="col-12 col-md-4">
                            <label class="form-label">Minimum Fee</label>
                            <div class="input-group">
                                <span class="input-group-text"><?= $cur ?></span>
                                <input type="number" name="delivery_min_fee" class="form-control"
                                       value="<?= e($settings['delivery_min_fee'] ?? '0') ?>"
                                       min="0" step="1" placeholder="0">
                            </div>
                            <div class="form-text">Minimum charged even for short distances.</div>
                        </div>
                        <div class="col-12 col-md-4">
                            <label class="form-label">Free Delivery Above <span class="text-secondary">(optional)</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><?= $cur ?></span>
                                <input type="number" name="delivery_free_above" class="form-control"
                                       value="<?= e($settings['delivery_free_above'] ?? '0') ?>"
                                       min="0" step="10" placeholder="0 = disabled">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Restaurant GPS location (needed for per_km) -->
                <div class="row g-3 mt-1" id="restaurantGpsRow">
                    <div class="col-12">
                        <label class="form-label fw-600">
                            Restaurant GPS Location
                            <span class="text-secondary fw-400" style="font-size:.78rem;"> — required for per-km charges and rider map links</span>
                        </label>
                    </div>
                    <div class="col-12 col-md-5">
                        <label class="form-label">Latitude</label>
                        <input type="text" name="restaurant_lat" id="restLat" class="form-control"
                               value="<?= e($settings['restaurant_lat'] ?? '') ?>" placeholder="e.g. 31.5497">
                    </div>
                    <div class="col-12 col-md-5">
                        <label class="form-label">Longitude</label>
                        <input type="text" name="restaurant_lng" id="restLng" class="form-control"
                               value="<?= e($settings['restaurant_lng'] ?? '') ?>" placeholder="e.g. 74.3436">
                    </div>
                    <div class="col-12 col-md-2 d-flex align-items-end">
                        <button type="button" class="btn btn-outline-secondary w-100" onclick="detectRestaurantLocation(this)">
                            <i class="bi bi-geo-alt-fill me-1 text-accent"></i> Detect
                        </button>
                    </div>
                    <div class="col-12" id="restLocStatus"></div>
                </div>

                <!-- Delivery range -->
                <div class="row g-3 mt-1">
                    <div class="col-12 col-md-6">
                        <label class="form-label">Delivery Range (radius)</label>
                        <div class="input-group">
                            <input type="number" name="delivery_radius_km" class="form-control"
                                   value="<?= e($settings['delivery_radius_km'] ?? '0') ?>"
                                   min="0" step="0.5" placeholder="0 = unlimited">
                            <span class="input-group-text">km</span>
                        </div>
                        <div class="form-text">Max distance from the restaurant we deliver to (0 = no limit). Requires the restaurant GPS location.</div>
                    </div>
                </div>

            </div>
        </div>

        <!-- Working Hours -->
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-clock text-accent"></i>
                <h6 class="card-title">Working Hours</h6>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-6 col-md-4">
                        <label class="form-label">Opening Time</label>
                        <input type="time" name="open_time" class="form-control"
                               value="<?= e($settings['open_time'] ?? '') ?>">
                    </div>
                    <div class="col-6 col-md-4">
                        <label class="form-label">Closing Time</label>
                        <input type="time" name="close_time" class="form-control"
                               value="<?= e($settings['close_time'] ?? '') ?>">
                    </div>
                </div>
                <div class="form-text mt-2">
                    The customer app only accepts orders during these hours. Leave both
                    empty for 24/7. If closing time is earlier than opening time, hours
                    are treated as crossing midnight (e.g. 18:00 → 02:00).
                </div>
            </div>
        </div>

    </div><!-- /left column -->

    <!-- ── Right column ───────────────────────────────────────────────────── -->
    <div class="col-12 col-xl-4">

        <!-- System Preferences -->
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-gear-fill text-accent"></i>
                <h6 class="card-title">System Preferences</h6>
            </div>
            <div class="card-body">

                <!-- Order alert sound -->
                <div class="d-flex align-items-center justify-content-between py-3 border-bottom">
                    <div>
                        <div class="fw-600" style="font-size:.875rem;">Order Alert Sound</div>
                        <div class="text-secondary" style="font-size:.75rem;">Beep when a new order arrives</div>
                    </div>
                    <div class="form-check form-switch mb-0">
                        <input class="form-check-input" type="checkbox" name="order_alert_sound" value="1"
                               id="alertSound"
                               <?= ($settings['order_alert_sound'] ?? '1') === '1' ? 'checked' : '' ?>
                               style="width:44px;height:22px;">
                    </div>
                </div>

                <!-- Maintenance mode -->
                <div class="d-flex align-items-center justify-content-between py-3">
                    <div>
                        <div class="fw-600" style="font-size:.875rem;">Maintenance Mode</div>
                        <div class="text-secondary" style="font-size:.75rem;">Hides the customer storefront</div>
                    </div>
                    <div class="form-check form-switch mb-0">
                        <input class="form-check-input" type="checkbox" name="app_maintenance_mode" value="1"
                               id="maintMode"
                               <?= ($settings['app_maintenance_mode'] ?? '0') === '1' ? 'checked' : '' ?>
                               style="width:44px;height:22px;">
                    </div>
                </div>

                <!-- Share rider location -->
                <div class="d-flex align-items-center justify-content-between py-3 border-top">
                    <div>
                        <div class="fw-600" style="font-size:.875rem;">Share Rider Location</div>
                        <div class="text-secondary" style="font-size:.75rem;">Show the rider's live location &amp; ETA to customers while out for delivery</div>
                    </div>
                    <div class="form-check form-switch mb-0">
                        <input class="form-check-input" type="checkbox" name="show_rider_location" value="1"
                               id="showRiderLoc"
                               <?= ($settings['show_rider_location'] ?? '0') === '1' ? 'checked' : '' ?>
                               style="width:44px;height:22px;">
                    </div>
                </div>

            </div>
        </div>

        <!-- Quick info -->
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-info-circle text-accent"></i>
                <h6 class="card-title">System Info</h6>
            </div>
            <div class="card-body p-0">
                <?php
                $info = [
                    'PHP Version'  => PHP_VERSION,
                    'Server'       => $_SERVER['SERVER_SOFTWARE'] ?? 'Apache',
                    'App Version'  => '1.0.0',
                    'Environment'  => defined('APP_ENV') ? APP_ENV : 'production',
                ];
                foreach ($info as $label => $val):
                ?>
                <div class="d-flex justify-content-between px-4 py-2 border-bottom" style="font-size:.82rem;">
                    <span class="text-secondary"><?= e($label) ?></span>
                    <span class="fw-600"><?= e($val) ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Save button -->
        <div class="d-grid gap-2">
            <button type="submit" class="btn btn-accent py-3">
                <i class="bi bi-check-lg me-1"></i> Save All Settings
            </button>
            <a href="<?= url('dashboard') ?>" class="btn btn-outline-secondary">
                Cancel
            </a>
        </div>

    </div><!-- /right column -->

</div><!-- /row -->

</form>

<!-- Payment Modes — must be OUTSIDE the main form to allow its own form submission -->
<div class="row g-4 mt-0">
    <div class="col-12 col-xl-4 offset-xl-8">
        <div class="card mb-4" id="payment-modes">
            <div class="card-header">
                <i class="bi bi-wallet2 text-accent"></i>
                <h6 class="card-title">Payment Modes</h6>
            </div>
            <div class="card-body p-0">
                <ul class="list-group list-group-flush" id="pmList">
                <?php foreach ($paymentModes as $pm): ?>
                <li class="list-group-item d-flex align-items-center gap-2 px-3 py-2" id="pm-<?= $pm['id'] ?>">
                    <span class="flex-grow-1 fw-600" style="font-size:.875rem;"><?= e($pm['name']) ?></span>
                    <span class="badge <?= $pm['is_active'] ? 'bg-success' : 'bg-secondary' ?> pm-badge"
                          style="font-size:.65rem;"><?= $pm['is_active'] ? 'Active' : 'Off' ?></span>
                    <button type="button" class="btn btn-outline-secondary btn-sm"
                            title="Toggle" style="padding:2px 8px;"
                            onclick="pmToggle(<?= $pm['id'] ?>, this)">
                        <i class="bi bi-<?= $pm['is_active'] ? 'eye-slash' : 'eye' ?>"></i>
                    </button>
                    <button type="button" class="btn btn-outline-danger btn-sm"
                            title="Delete" style="padding:2px 8px;"
                            onclick="pmDelete(<?= $pm['id'] ?>, this)">
                        <i class="bi bi-trash"></i>
                    </button>
                </li>
                <?php endforeach; ?>
                </ul>
            </div>
            <div class="card-footer bg-white">
                <form method="POST" action="<?= url('settings/payment-modes/store') ?>" class="d-flex gap-2">
                    <?= csrf_field() ?>
                    <input type="text" name="name" class="form-control form-control-sm"
                           placeholder="New mode name…" required maxlength="60">
                    <button type="submit" class="btn btn-accent btn-sm" style="white-space:nowrap;">
                        <i class="bi bi-plus-lg me-1"></i>Add
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
// ── Delivery type card toggle ────────────────────────────────────────────────
document.querySelectorAll('.dct-radio').forEach(radio => {
    radio.addEventListener('change', applyDeliveryType);
});
function applyDeliveryType() {
    const val = document.querySelector('.dct-radio:checked')?.value || 'fixed';
    document.querySelectorAll('.delivery-type-card').forEach(card => {
        const isActive = card.querySelector('input')?.value === val;
        card.classList.toggle('border-accent',   isActive);
        card.classList.toggle('bg-accent-soft',  isActive);
    });
    document.getElementById('dctFixed').classList.toggle('d-none',  val !== 'fixed');
    document.getElementById('dctPerKm').classList.toggle('d-none',  val !== 'per_km');
}
applyDeliveryType();

// ── Detect restaurant GPS ────────────────────────────────────────────────────
function detectRestaurantLocation(btn) {
    if (!navigator.geolocation) { alert('Geolocation not supported.'); return; }
    const status = document.getElementById('restLocStatus');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Detecting…';
    status.textContent = '';
    navigator.geolocation.getCurrentPosition(pos => {
        document.getElementById('restLat').value = pos.coords.latitude.toFixed(7);
        document.getElementById('restLng').value = pos.coords.longitude.toFixed(7);
        status.innerHTML = '<span class="text-success"><i class="bi bi-check-circle me-1"></i>Location detected! Save settings to apply.</span>';
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-geo-alt-fill me-1 text-accent"></i> Detect';
    }, err => {
        status.innerHTML = '<span class="text-danger"><i class="bi bi-x-circle me-1"></i>Could not detect location.</span>';
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-geo-alt-fill me-1 text-accent"></i> Detect';
    }, { timeout: 10000 });
}

// ── Payment modes ────────────────────────────────────────────────────────────
const PM_CSRF = '<?= csrf_token() ?>';
const PM_BASE = '<?= url('settings/payment-modes/') ?>';

async function pmToggle(id, btn) {
    btn.disabled = true;
    const res  = await fetch(PM_BASE + id + '/toggle', {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: (() => { const f = new FormData(); f.append('_csrf', PM_CSRF); return f; })(),
    });
    const data = await res.json();
    if (data.ok) {
        const li    = document.getElementById('pm-' + id);
        const badge = li.querySelector('.pm-badge');
        const icon  = btn.querySelector('i');
        badge.className = 'badge ' + (data.active ? 'bg-success' : 'bg-secondary') + ' pm-badge';
        badge.textContent = data.active ? 'Active' : 'Off';
        icon.className = 'bi bi-' + (data.active ? 'eye-slash' : 'eye');
    }
    btn.disabled = false;
}

async function pmDelete(id, btn) {
    if (!confirm('Delete this payment mode?')) return;
    btn.disabled = true;
    const res  = await fetch(PM_BASE + id + '/delete', {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: (() => { const f = new FormData(); f.append('_csrf', PM_CSRF); return f; })(),
    });
    const data = await res.json();
    if (data.ok) {
        document.getElementById('pm-' + id)?.remove();
    } else {
        btn.disabled = false;
    }
}
</script>
