<?php
require_once 'includes/config.php';
requireLogin();
$uid = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $title   = sanitize($_POST['title'] ?? '');
        $message = sanitize($_POST['message'] ?? '');
        $time    = sanitize($_POST['reminder_time'] ?? '');
        $days    = $_POST['days'] ?? [];
        if (!$title || !$time || empty($days)) jsonResponse(['success'=>false,'message'=>'Please fill in all required fields.']);
        $daysJson = json_encode(array_values($days));
        $pdo->prepare("INSERT INTO reminders (user_id,title,message,reminder_time,days) VALUES (?,?,?,?,?)")->execute([$uid,$title,$message,$time,$daysJson]);
        jsonResponse(['success'=>true,'message'=>'Reminder created!']);
    }

    if ($action === 'toggle') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("UPDATE reminders SET is_active=NOT is_active WHERE id=? AND user_id=?")->execute([$id,$uid]);
        jsonResponse(['success'=>true]);
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("DELETE FROM reminders WHERE id=? AND user_id=?")->execute([$id,$uid]);
        jsonResponse(['success'=>true]);
    }
}

$reminders = $pdo->prepare("SELECT * FROM reminders WHERE user_id=? ORDER BY reminder_time ASC");
$reminders->execute([$uid]); $reminders = $reminders->fetchAll();

$daysOfWeek = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];

require_once 'includes/header.php';
renderHeader('Reminders', 'reminders');
?>

<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:22px">
  <div>
    <div style="font-size:22px;font-weight:800;font-family:'Sora',sans-serif">🔔 Study Reminders</div>
    <div style="font-size:13px;color:var(--text-muted);margin-top:3px">Set daily reminders to keep your study habit consistent</div>
  </div>
  <button class="btn btn-primary" onclick="document.getElementById('remModal').classList.add('active')">＋ Add Reminder</button>
</div>

<!-- ── Push Notification Setup Banner ──────────────────────────────── -->
<div id="pushBanner" class="card" style="margin-bottom:20px;border:1.5px solid var(--accent);display:none;">
  <div style="display:flex;align-items:center;gap:14px;flex-wrap:wrap;">
    <div style="font-size:28px;flex-shrink:0">📲</div>
    <div style="flex:1;min-width:200px;">
      <div style="font-size:14px;font-weight:700;color:var(--text-primary);margin-bottom:3px">
        Get Reminders on Your Phone
      </div>
      <div id="pushStatusText" style="font-size:12px;color:var(--text-muted);">
        Enable push notifications to receive reminders even when this tab is closed.
      </div>
    </div>
    <div style="display:flex;gap:8px;flex-shrink:0;">
      <button id="pushEnableBtn"  class="btn btn-primary btn-sm"   onclick="enablePush()">🔔 Enable Push</button>
      <button id="pushTestBtn"    class="btn btn-secondary btn-sm" onclick="testPush()"   style="display:none">🧪 Test</button>
      <button id="pushDisableBtn" class="btn btn-danger btn-sm"    onclick="disablePush()" style="display:none">🔕 Disable</button>
    </div>
  </div>
</div>

<div id="pushUnsupported" class="alert alert-warning" style="margin-bottom:20px;display:none;">
  ⚠️ Your browser doesn't support push notifications. Try Chrome, Edge, or Firefox.
</div>

<?php if ($reminders): ?>
<div style="display:flex;flex-direction:column;gap:12px">
  <?php foreach ($reminders as $r):
    $days = json_decode($r['days'], true) ?: [];
  ?>
  <div class="card" style="border-left:3px solid <?= $r['is_active'] ? 'var(--teal,#38bdf8)' : 'var(--border)' ?>">
    <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;min-width:0;overflow:hidden">
      <div style="min-width:0;flex:1;overflow:hidden">
        <div style="font-size:16px;font-weight:700;color:var(--text-primary);margin-bottom:4px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?= $r['is_active'] ? '🔔' : '🔕' ?> <?= htmlspecialchars($r['title']) ?></div>
        <?php if ($r['message']): ?>
        <div style="font-size:13px;color:var(--text-secondary);margin-bottom:6px"><?= htmlspecialchars($r['message']) ?></div>
        <?php endif; ?>
        <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
          <span style="font-family:'Sora',sans-serif;font-size:18px;font-weight:700;color:var(--teal,#38bdf8)"><?= date('g:i A', strtotime($r['reminder_time'])) ?></span>
          <div style="display:flex;gap:4px">
            <?php foreach ($daysOfWeek as $d): ?>
            <span style="font-size:11px;padding:2px 7px;border-radius:4px;font-weight:600;<?= in_array($d,$days)?'background:var(--teal-dim,rgba(56,189,248,0.12));color:var(--teal,#38bdf8);':'background:var(--bg-secondary);color:var(--text-muted);' ?>"><?= $d ?></span>
            <?php endforeach; ?>
          </div>
        </div>
      </div>
      <div style="display:flex;gap:8px;align-items:center;flex-shrink:0">
        <button onclick="remToggle(<?= $r['id'] ?>)" class="btn btn-secondary btn-sm"><?= $r['is_active'] ? 'Pause' : 'Resume' ?></button>
        <button onclick="remDel(<?= $r['id'] ?>)"    class="btn btn-danger btn-sm">Delete</button>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
</div>
<?php else: ?>
<div class="empty-state"><div class="empty-icon">🔔</div><h3>No reminders set</h3><p>Create a reminder to build a consistent study habit!</p></div>
<?php endif; ?>

<!-- Add Reminder Modal -->
<div class="modal-overlay" id="remModal">
  <div class="modal" style="max-width:460px">
    <div class="modal-header">
      <span class="modal-title">🔔 New Reminder</span>
      <button class="modal-close" onclick="document.getElementById('remModal').classList.remove('active')">✕</button>
    </div>
    <div id="remMsg" class="alert" style="display:none"></div>
    <div class="form-group"><label class="form-label">Reminder Title *</label><input type="text" id="rTitle" class="form-control" placeholder="e.g. Morning Study Session"></div>
    <div class="form-group"><label class="form-label">Message (optional)</label><input type="text" id="rMessage" class="form-control" placeholder="e.g. Time to study Physics!"></div>
    <div class="form-group">
      <label class="form-label">Reminder Time *</label>
      <input type="time" id="rTime" class="form-control" value="08:00">
    </div>
    <div class="form-group">
      <label class="form-label">Days *</label>
      <div style="display:flex;gap:8px;flex-wrap:nowrap;flex-shrink:0;align-items:center">
        <?php foreach ($daysOfWeek as $d): ?>
        <label style="display:flex;align-items:center;gap:5px;cursor:pointer;font-size:13px;background:var(--bg-secondary);border:1px solid var(--border);border-radius:8px;padding:6px 10px">
          <input type="checkbox" name="days[]" value="<?= $d ?>" class="day-check" style="accent-color:var(--teal,#38bdf8)"> <?= $d ?>
        </label>
        <?php endforeach; ?>
      </div>
    </div>
    <button class="btn btn-primary btn-full" onclick="saveReminder()">Save Reminder</button>
  </div>
</div>

<?php require_once 'includes/footer.php'; renderFooter(); ?>

<script>
const SITE_URL   = '<?= SITE_URL ?>';
const VAPID_KEY  = '<?= VAPID_PUBLIC_KEY ?>';
const SW_URL     = '<?= SITE_URL ?>/sw.js';
const SCOPE      = '/studytrack/';

let _sw  = null;
let _sub = null;

// ── Init ──────────────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', async () => {
  const banner      = document.getElementById('pushBanner');
  const unsupported = document.getElementById('pushUnsupported');

  // ── Browser capability detection ──────────────────────────────────
  const hasNotif = 'Notification' in window;
  const hasSW    = 'serviceWorker' in navigator;
  const hasPush  = 'PushManager' in window;

  // Truly unsupported (very old browser)
  if (!hasNotif) {
    unsupported.innerHTML = '⚠️ Your browser doesn\'t support notifications. Try Chrome, Edge, or Firefox.';
    unsupported.style.display = 'block';
    return;
  }

  // iOS Safari browser — Notification API works since iOS 16.4
  // Background push needs home screen PWA, but in-tab reminders work fine
  const isIOS        = /iphone|ipad|ipod/i.test(navigator.userAgent);
  const isStandalone = window.navigator.standalone === true ||
                       window.matchMedia('(display-mode: standalone)').matches;
  const isSafariOnly = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  const isIOSBrowser = isIOS && isSafariOnly && !isStandalone;

  banner.style.display = 'block';

  // Show honest message for iOS Safari browser
  if (isIOSBrowser) {
    document.getElementById('pushStatusText').textContent =
      'Enable to get reminders while this tab is open. Add to Home Screen for background alerts.';
  }

  // Register SW + get existing subscription
  try {
    if (hasSW) {
      try { _sw = await navigator.serviceWorker.register(SW_URL, { scope: SCOPE }); }
      catch(e) { try { _sw = await navigator.serviceWorker.register(SW_URL); } catch(e2) {} }
      if (_sw) {
        await navigator.serviceWorker.ready.catch(() => {});
        _sub = hasPush ? await _sw.pushManager.getSubscription().catch(() => null) : null;
      }
    }
  } catch(e) { console.error('SW init:', e); }

  const perm = Notification.permission;
  if (perm === 'granted' && (_sub || !hasPush)) {
    setPushState('enabled');
    scheduleLocalReminders();
  } else if (perm === 'granted' && !_sub && hasPush) {
    setPushState('default');
    scheduleLocalReminders();
  } else if (perm === 'denied') {
    setPushState('denied');
  } else {
    setPushState('default');
  }
});

// ── Push state UI ─────────────────────────────────────────────────────
function setPushState(state) {
  const enBtn  = document.getElementById('pushEnableBtn');
  const testBtn= document.getElementById('pushTestBtn');
  const disBtn = document.getElementById('pushDisableBtn');
  const txt    = document.getElementById('pushStatusText');

  enBtn.style.display  = state === 'default'  ? 'inline-flex' : 'none';
  testBtn.style.display= state === 'enabled'  ? 'inline-flex' : 'none';
  disBtn.style.display = state === 'enabled'  ? 'inline-flex' : 'none';

  if (state === 'enabled') {
    txt.textContent = '✅ Push notifications enabled! You\'ll get reminders even when this tab is closed.';
    txt.style.color = 'var(--success,#22c55e)';
    enBtn.style.display = 'none';
  } else if (state === 'denied') {
    enBtn.disabled    = true;
    enBtn.textContent = '🚫 Blocked';
    enBtn.style.display = 'inline-flex';
    txt.textContent = 'Notifications blocked. Please enable them in your browser/phone settings.';
    txt.style.color = 'var(--danger,#ef4444)';
  } else {
    txt.textContent = 'Enable push notifications to receive reminders even when this tab is closed.';
    txt.style.color = 'var(--text-muted)';
  }
}

// ── Enable Push ───────────────────────────────────────────────────────
async function enablePush() {
  const btn = document.getElementById('pushEnableBtn');
  btn.disabled  = true;
  btn.innerHTML = '⏳ Enabling...';

  try {
    const perm = await Notification.requestPermission();
    if (perm !== 'granted') {
      setPushState('denied');
      btn.disabled  = false;
      btn.innerHTML = '🔔 Enable Push';
      return;
    }

    // Register SW if not already done
    const hasSWnow = 'serviceWorker' in navigator;
    const hasPushNow = 'PushManager' in window;
    if (hasSWnow && !_sw) {
      try { _sw = await navigator.serviceWorker.register(SW_URL, { scope: SCOPE }); }
      catch(e) { try { _sw = await navigator.serviceWorker.register(SW_URL); } catch(e2) {} }
      if (_sw) await navigator.serviceWorker.ready.catch(() => {});
    }

    // Subscribe to push if PushManager available (Chrome/Edge/Firefox/iOS PWA)
    // Safari browser without PushManager — in-tab reminders only, no subscribe needed
    if (_sw && hasPushNow && VAPID_KEY) {
      try {
        _sub = await _sw.pushManager.subscribe({
          userVisibleOnly:      true,
          applicationServerKey: urlB64ToUint8Array(VAPID_KEY),
        });
        const keys = {
          p256dh: btoa(String.fromCharCode(...new Uint8Array(_sub.getKey('p256dh')))),
          auth:   btoa(String.fromCharCode(...new Uint8Array(_sub.getKey('auth')))),
        };
        await fetch(SITE_URL + '/api/push-subscribe.php', {
          method:  'POST',
          headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
          body:    JSON.stringify({ action: 'subscribe', endpoint: _sub.endpoint, ...keys }),
        });
      } catch(subErr) {
        console.warn('Push subscribe (non-fatal):', subErr);
      }
    }

    // Confirmation notification
    try {
      if (_sw && _sw.showNotification) {
        await _sw.showNotification('✅ StudyTrack Notifications Active!', {
          body:    'You\'ll receive study reminders even when this tab is closed 📚',
          icon:    SITE_URL + '/images/studytrack.png',
          badge:   SITE_URL + '/images/studytrack.png',
          vibrate: [200, 100, 200],
        });
      } else {
        new Notification('✅ StudyTrack Notifications Active!', {
          body: 'You\'ll receive study reminders 📚',
          icon: SITE_URL + '/images/studytrack.png',
        });
      }
    } catch(e) {}

    setPushState('enabled');
    scheduleLocalReminders();

  } catch(e) {
    console.error('Enable push error:', e);
    btn.disabled  = false;
    btn.innerHTML = '🔔 Enable Push';
  }
}

// ── Disable Push ──────────────────────────────────────────────────────
async function disablePush() {
  if (_sub) {
    try {
      await fetch(SITE_URL + '/api/push-subscribe.php', {
        method:  'POST',
        headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
        body:    JSON.stringify({ action: 'unsubscribe', endpoint: _sub.endpoint }),
      });
      await _sub.unsubscribe();
      _sub = null;
    } catch(e) {}
  }
  setPushState('default');
}

// ── Test Push ─────────────────────────────────────────────────────────
async function testPush() {
  const btn = document.getElementById('pushTestBtn');
  btn.disabled  = true;
  btn.innerHTML = '⏳';
  try {
    const res  = await fetch(SITE_URL + '/api/push-send.php', {
      method:  'POST',
      headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
      body:    JSON.stringify({ action: 'send_test' }),
    });
    const data = await res.json();

    if (data.sent > 0) {
      btn.innerHTML = '✅ Sent!';
    } else {
      // Fallback local notification
      if (Notification.permission === 'granted') {
        new Notification('🧪 StudyTrack Test', {
          body: 'Push notifications are working! 🎉',
          icon: SITE_URL + '/images/studytrack.png',
        });
      }
      btn.innerHTML = '✅ Sent!';
    }
    setTimeout(() => { btn.disabled = false; btn.innerHTML = '🧪 Test'; }, 2500);
  } catch(e) {
    btn.disabled  = false;
    btn.innerHTML = '🧪 Test';
  }
}

// ── In-tab reminder fallback (runs while tab is open) ─────────────────
function scheduleLocalReminders() {
  <?php foreach ($reminders as $r): if (!$r['is_active']) continue;
    $days    = json_decode($r['days'], true) ?: [];
    $timeStr = date('H:i', strtotime($r['reminder_time']));
  ?>
  _scheduleCheck(
    '<?= addslashes(htmlspecialchars($r['title'])) ?>',
    '<?= $timeStr ?>',
    <?= json_encode($days) ?>,
    '<?= addslashes(htmlspecialchars($r['message'])) ?>'
  );
  <?php endforeach; ?>
}

const _fired = {};
function _scheduleCheck(title, time, days, message) {
  const dayMap = {Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};
  setInterval(() => {
    const now     = new Date();
    const hhmm    = now.getHours().toString().padStart(2,'0') + ':' + now.getMinutes().toString().padStart(2,'0');
    const dayName = Object.keys(dayMap).find(k => dayMap[k] === now.getDay());
    const key     = title + hhmm;
    if (hhmm === time && days.includes(dayName) && !_fired[key] && Notification.permission === 'granted') {
      _fired[key] = true;
      new Notification('📚 ' + title, {
        body: message || 'Time to study!',
        icon: SITE_URL + '/images/studytrack.png',
      });
      setTimeout(() => delete _fired[key], 70000); // reset after ~1min
    }
  }, 15000); // check every 15s for accuracy
}

// ── Reminder CRUD ─────────────────────────────────────────────────────
async function post(data) {
  const fd = new FormData();
  Object.entries(data).forEach(([k,v]) => fd.append(k, v));
  const r = await fetch(location.href, { method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body:fd });
  return r.json();
}

async function saveReminder() {
  const fd = new FormData();
  fd.append('action', 'add');
  fd.append('title',        document.getElementById('rTitle').value);
  fd.append('message',      document.getElementById('rMessage').value);
  fd.append('reminder_time',document.getElementById('rTime').value);
  document.querySelectorAll('.day-check:checked').forEach(cb => fd.append('days[]', cb.value));
  const res  = await fetch(location.href, { method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body:fd });
  const data = await res.json();
  const msg  = document.getElementById('remMsg');
  msg.style.display = 'flex';
  msg.className     = 'alert ' + (data.success ? 'alert-success' : 'alert-error');
  msg.textContent   = data.message;
  if (data.success) setTimeout(() => location.reload(), 700);
}

async function remToggle(id) { await post({action:'toggle', id}); location.reload(); }
async function remDel(id)    { if (!(await stConfirm('Delete reminder?'))) return; await post({action:'delete', id}); location.reload(); }

// ── Util ──────────────────────────────────────────────────────────────
function urlB64ToUint8Array(b64) {
  const pad  = '='.repeat((4 - b64.length % 4) % 4);
  const raw  = atob((b64 + pad).replace(/-/g,'+').replace(/_/g,'/'));
  return Uint8Array.from([...raw].map(c => c.charCodeAt(0)));
}
</script>