<?php
// POST (instant-save via fetch) is processed BEFORE any HTML output so the
// JSON response isn't polluted by the page markup.
session_start();
include_once("config/db.php");
$uid = (int)($_SESSION['user_id'] ?? 0);

// notify_* columns come from restaurantadmin/schema_settings_migration.sql.
// Everything here is defensive: if the migration hasn't run, the page falls
// back to "all on, read-only" instead of crashing.
$migrated = false;
$prefs = ['notify_order_updates' => 1, 'notify_promos' => 1, 'notify_wallet' => 1];

$check = $uid ? $conn->prepare("SELECT notify_order_updates, notify_promos, notify_wallet FROM users WHERE id=?") : false;
if ($check) {
    $migrated = true;
    $check->bind_param("i", $uid);
    $check->execute();
    $row = $check->get_result()->fetch_assoc();
    if ($row) $prefs = $row;
}

// Instant-save POST (sent via fetch when a toggle changes)
if ($uid && $migrated && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $prefs['notify_order_updates'] = isset($_POST['notify_order_updates']) ? 1 : 0;
    $prefs['notify_promos']        = isset($_POST['notify_promos']) ? 1 : 0;
    $prefs['notify_wallet']        = isset($_POST['notify_wallet']) ? 1 : 0;

    $upd = $conn->prepare("UPDATE users SET notify_order_updates=?, notify_promos=?, notify_wallet=? WHERE id=?");
    $upd->bind_param("iiii", $prefs['notify_order_updates'], $prefs['notify_promos'], $prefs['notify_wallet'], $uid);
    $upd->execute();

    if (!empty($_POST['ajax'])) { header('Content-Type: application/json'); echo json_encode(['ok' => true]); exit; }
}

$page_title = 'Notifications';
$active_nav = 'profile';
include("includes/header.php");
?>

<style>
.app-topbar { display: none; }
.main-content { padding-top: calc(env(safe-area-inset-top) + 6px); }
.nt-wrap { max-width: 600px; margin: 0 auto; }

.sub-topbar { display: flex; align-items: center; justify-content: space-between; padding: 4px 2px 18px; }
.sub-topbar-left { display: flex; align-items: center; gap: 12px; min-width: 0; }
.sub-topbar .sub-back { width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: var(--primary); background: var(--primary-bg); flex-shrink: 0; }
.sub-topbar .sub-title { font-size: 1.15rem; font-weight: 800; letter-spacing: -.02em; color: var(--text); }

.nt-intro { font-size: .86rem; color: var(--text-muted); line-height: 1.5; margin-bottom: 22px; }
.nt-group-label { font-size: .68rem; font-weight: 800; letter-spacing: .1em; text-transform: uppercase; color: var(--text-light); margin: 22px 4px 10px; }

.nt-card { background: #fff; border-radius: 16px; box-shadow: 0 4px 18px rgba(15,23,42,.06); border: 1px solid var(--border); overflow: hidden; }
.nt-row { display: flex; align-items: center; gap: 14px; padding: 16px; border-bottom: 1px solid var(--border); }
.nt-row:last-child { border-bottom: none; }
.nt-icon { width: 38px; height: 38px; border-radius: 11px; background: var(--primary-bg); color: var(--primary); display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
.nt-icon.amber { background: var(--warning-bg); color: var(--warning); }
.nt-icon.muted { background: var(--bg); color: var(--text-muted); }
.nt-text { flex: 1; min-width: 0; }
.nt-label { font-weight: 700; font-size: .9rem; margin-bottom: 2px; }
.nt-desc { font-size: .76rem; color: var(--text-muted); line-height: 1.4; }

/* square check control */
.nt-check { position: relative; flex-shrink: 0; width: 26px; height: 26px; }
.nt-check input { position: absolute; opacity: 0; inset: 0; margin: 0; cursor: pointer; z-index: 2; }
.nt-box { position: absolute; inset: 0; border: 2px solid var(--border-dark); border-radius: 8px; background: #fff; transition: all .15s; display: flex; align-items: center; justify-content: center; }
.nt-box svg { width: 15px; height: 15px; stroke: #fff; opacity: 0; transition: opacity .15s; }
.nt-check input:checked + .nt-box { background: var(--primary); border-color: var(--primary); }
.nt-check input:checked + .nt-box svg { opacity: 1; }
.nt-check input:disabled { cursor: not-allowed; }
.nt-check input:disabled + .nt-box { opacity: .5; }

.nt-foot { font-size: .76rem; color: var(--text-light); text-align: center; line-height: 1.5; margin: 22px 16px 0; }
</style>

<div class="nt-wrap">

  <div class="sub-topbar">
    <div class="sub-topbar-left">
      <a href="profile.php" class="sub-back" aria-label="Back" onclick="return goBack(event)">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 12H5m0 0l7 7M5 12l7-7"/></svg>
      </a>
      <span class="sub-title">Notifications</span>
    </div>
  </div>

  <p class="nt-intro">Manage how you receive alerts and stay updated with your account activity.</p>

  <?php if (!$migrated): ?>
  <div class="alert alert-info" style="margin-bottom:16px">
    <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>
    <span>Preference toggles aren't saveable yet on this server — everything is on by default until the database is updated.</span>
  </div>
  <?php endif; ?>

  <!-- Push notifications (browser) -->
  <div class="nt-card">
    <div class="nt-row">
      <span class="nt-icon"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8a6 6 0 10-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 01-3.46 0"/></svg></span>
      <span class="nt-text">
        <span class="nt-label">Push Notifications</span>
        <span class="nt-desc" id="pushStatus">Get alerts on this device</span>
      </span>
      <label class="nt-check">
        <input type="checkbox" id="pushToggle">
        <span class="nt-box"><svg viewBox="0 0 24 24" fill="none" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></span>
      </label>
    </div>
  </div>

  <div class="nt-group-label">Alert Channels</div>
  <form id="prefForm" class="nt-card">
    <div class="nt-row">
      <span class="nt-icon"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/><rect x="9" y="3" width="6" height="4" rx="1"/><path d="M9 12h6M9 16h4"/></svg></span>
      <span class="nt-text">
        <span class="nt-label">Order Updates</span>
        <span class="nt-desc">Confirmed, preparing, ready &amp; served — every step of an order.</span>
      </span>
      <label class="nt-check">
        <input type="checkbox" name="notify_order_updates" <?php echo $prefs['notify_order_updates'] ? 'checked' : ''; ?> <?php echo $migrated ? '' : 'disabled'; ?>>
        <span class="nt-box"><svg viewBox="0 0 24 24" fill="none" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></span>
      </label>
    </div>
    <div class="nt-row">
      <span class="nt-icon"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12V7H5a2 2 0 010-4h15a1 1 0 011 1v4"/><path d="M3 5v14a2 2 0 002 2h16v-5"/><path d="M18 12a2 2 0 000 4h4v-4z"/></svg></span>
      <span class="nt-text">
        <span class="nt-label">Wallet Activity</span>
        <span class="nt-desc">Funding confirmations, debits and balance alerts.</span>
      </span>
      <label class="nt-check">
        <input type="checkbox" name="notify_wallet" <?php echo $prefs['notify_wallet'] ? 'checked' : ''; ?> <?php echo $migrated ? '' : 'disabled'; ?>>
        <span class="nt-box"><svg viewBox="0 0 24 24" fill="none" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></span>
      </label>
    </div>
    <div class="nt-row">
      <span class="nt-icon amber"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 11l18-5v12L3 14v-3z"/><path d="M11.6 16.8a3 3 0 11-5.8-1.6"/></svg></span>
      <span class="nt-text">
        <span class="nt-label">Promotions &amp; Offers</span>
        <span class="nt-desc">Exclusive deals and rewards from restaurants you use.</span>
      </span>
      <label class="nt-check">
        <input type="checkbox" name="notify_promos" <?php echo $prefs['notify_promos'] ? 'checked' : ''; ?> <?php echo $migrated ? '' : 'disabled'; ?>>
        <span class="nt-box"><svg viewBox="0 0 24 24" fill="none" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></span>
      </label>
    </div>
  </form>

  <div class="nt-group-label">Push Notifications (this device)</div>
  <div class="nt-card">
    <div class="nt-row">
      <span class="nt-icon"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8a6 6 0 10-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 01-3.46 0"/></svg></span>
      <span class="nt-text">
        <span class="nt-label">Push to this device</span>
        <span class="nt-desc" id="pushDesc">Receive alerts even when Dabil isn't open in your browser.</span>
      </span>
      <label class="nt-check">
        <input type="checkbox" id="pushToggle">
        <span class="nt-box"><svg viewBox="0 0 24 24" fill="none" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></span>
      </label>
    </div>
    <div class="nt-row" id="pushTestRow" style="display:none">
      <span class="nt-text"><a href="#" id="pushTest" style="color:var(--primary);font-weight:700;font-size:.86rem">Send a test notification</a></span>
    </div>
  </div>

  <p class="nt-foot">Channel toggles control your in-app alerts (the bell icon). Push delivers those alerts to your device even when the app is closed — enable it per device.</p>
</div>

<div class="os-toast" id="ntToast" style="position:fixed;bottom:calc(env(safe-area-inset-bottom) + 80px);left:50%;transform:translateX(-50%);background:#0F172A;color:#fff;padding:10px 18px;border-radius:30px;font-size:.8rem;font-weight:600;box-shadow:0 6px 20px rgba(0,0,0,.25);z-index:700;opacity:0;pointer-events:none;transition:opacity .25s"></div>

<script src="assets/js/push.js?v=3"></script>
<script>
(function () {
  const VAPID    = 'BBEgAn0_znukmO8rd6tAHcGJh-AQ2lxXixpzYBOkDW6e_TiFOxMbaboXyHS8OVCaDlJNml8SFjBcCgzypi83MSU';
  const toggle   = document.getElementById('pushToggle');
  const desc     = document.getElementById('pushDesc');
  const testRow  = document.getElementById('pushTestRow');
  const testLink = document.getElementById('pushTest');
  function ptoast(m){ const t=document.getElementById('ntToast'); if(!t)return; t.textContent=m; t.style.opacity='1'; clearTimeout(window._ntp); window._ntp=setTimeout(()=>t.style.opacity='0',2400); }
  if (!toggle) return;

  (async function () {
    if (!window.DabilPush || !DabilPush.supported()) {
      toggle.disabled = true;
      if (desc) desc.textContent = 'Not supported by this browser';
      return;
    }
    try {
      await DabilPush.registerSW();
      const on = await DabilPush.isSubscribed();
      toggle.checked = on;
      if (testRow) testRow.style.display = on ? 'flex' : 'none';
    } catch (e) {}
  })();

  toggle.addEventListener('change', async () => {
    toggle.disabled = true;
    try {
      if (toggle.checked) { await DabilPush.subscribe(VAPID); ptoast('Push notifications enabled'); if (testRow) testRow.style.display = 'flex'; }
      else { await DabilPush.unsubscribe(); ptoast('Push notifications disabled'); if (testRow) testRow.style.display = 'none'; }
    } catch (e) {
      toggle.checked = !toggle.checked;
      ptoast(e.message || 'Could not update push notifications');
    } finally { toggle.disabled = false; }
  });

  if (testLink) testLink.addEventListener('click', async (e) => {
    e.preventDefault();
    try { await fetch('push_test.php', { method: 'POST' }); ptoast('Test sent — check your notifications'); }
    catch (err) { ptoast('Could not send test'); }
  });
})();
</script>
<script>
(function () {
  const migrated = <?php echo $migrated ? 'true' : 'false'; ?>;
  function toast(m){ const t=document.getElementById('ntToast'); t.textContent=m; t.style.opacity='1'; clearTimeout(window._nt); window._nt=setTimeout(()=>t.style.opacity='0',2000); }

  // Instant-save channel toggles
  const form = document.getElementById('prefForm');
  if (migrated) {
    form.querySelectorAll('input[type=checkbox]').forEach(cb => {
      cb.addEventListener('change', () => {
        const fd = new FormData(form);
        fd.append('ajax', '1');
        fetch('notification_preferences.php', { method: 'POST', body: fd })
          .then(r => r.json()).then(() => toast('Preferences saved'))
          .catch(() => toast("Couldn't save — try again"));
      });
    });
  }

  // Real browser push permission
  const push = document.getElementById('pushToggle');
  const status = document.getElementById('pushStatus');
  function reflectPush() {
    if (!('Notification' in window)) { push.disabled = true; status.textContent = 'Not supported on this device'; return; }
    if (Notification.permission === 'granted') { push.checked = true; status.textContent = 'Enabled on this device'; }
    else if (Notification.permission === 'denied') { push.checked = false; status.textContent = 'Blocked — enable in browser settings'; }
    else { push.checked = false; status.textContent = 'Tap to enable on this device'; }
  }
  reflectPush();
  push.addEventListener('change', function () {
    if (!('Notification' in window)) return;
    if (Notification.permission === 'granted') { this.checked = true; status.textContent = 'Enabled on this device'; toast('Already enabled'); return; }
    if (Notification.permission === 'denied') { this.checked = false; status.textContent = 'Blocked — enable in browser settings'; toast('Blocked in your browser settings'); return; }
    Notification.requestPermission().then(p => { reflectPush(); toast(p === 'granted' ? 'Push enabled' : 'Push not enabled'); });
  });
})();
</script>

<?php include("includes/footer.php"); ?>
