<?php
session_start();
$page_title = 'Security & Privacy';
$active_nav = 'profile';
include("includes/header.php");
$uid = (int)$_SESSION['user_id'];

$stmt = $conn->prepare("SELECT email, created_at, updated_at FROM users WHERE id=?");
$stmt->bind_param("i", $uid);
$stmt->execute();
$u = $stmt->get_result()->fetch_assoc();

// 2FA status — defensive (column added by schema_customer_settings.sql)
$twofa_on = false;
if ($c = $conn->prepare("SELECT twofa_enabled FROM users WHERE id=?")) {
    $c->bind_param("i", $uid); $c->execute();
    $twofa_on = (bool)($c->get_result()->fetch_assoc()['twofa_enabled'] ?? 0);
}

// Biometric passkey status — has this user registered a Face ID / fingerprint passkey?
$has_passkey = false;
require_once __DIR__ . '/includes/webauthn.php';
wa_ensure_table($conn);
if ($pk = $conn->prepare("SELECT COUNT(*) FROM webauthn_credentials WHERE user_id=?")) {
    $pk->bind_param("i", $uid); $pk->execute();
    $has_passkey = ((int)($pk->get_result()->fetch_row()[0] ?? 0)) > 0;
}

function rel_time($ts) {
    if (!$ts) return 'Not changed yet';
    $diff = time() - strtotime($ts);
    if ($diff < 3600) return 'Updated recently';
    if ($diff < 86400) return 'Updated today';
    $d = floor($diff / 86400);
    if ($d < 30) return "Updated $d day" . ($d > 1 ? 's' : '') . ' ago';
    $m = floor($d / 30);
    if ($m < 12) return "Updated $m month" . ($m > 1 ? 's' : '') . ' ago';
    return 'Updated ' . date('M Y', strtotime($ts));
}
?>

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

.sub-topbar { display: flex; align-items: center; justify-content: space-between; padding: 4px 2px 14px; }
.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); }
.sub-topbar .icon-btn { color: var(--primary); }

.sc-hero { text-align: center; margin-bottom: 22px; }
.sc-hero-icon { position: relative; width: 70px; height: 70px; border-radius: 20px; background: var(--primary); display: flex; align-items: center; justify-content: center; margin: 6px auto 14px; color: #fff; box-shadow: 0 8px 22px rgba(34,90,227,.3); }
.sc-hero-icon .dot { position: absolute; top: -3px; right: -3px; width: 16px; height: 16px; border-radius: 50%; background: var(--success); border: 3px solid var(--bg); }
.sc-hero h1 { font-size: 1.5rem; font-weight: 800; letter-spacing: -.03em; margin-bottom: 4px; }
.sc-hero p { font-size: .86rem; color: var(--text-muted); }

.sc-group-label { font-size: .68rem; font-weight: 800; letter-spacing: .1em; text-transform: uppercase; color: var(--text-light); margin: 22px 4px 10px; }
.sc-card { background: #fff; border-radius: 16px; box-shadow: 0 4px 18px rgba(15,23,42,.06); border: 1px solid var(--border); overflow: hidden; }
.sc-row { display: flex; align-items: center; gap: 14px; padding: 16px; border-bottom: 1px solid var(--border); text-decoration: none; color: var(--text); }
.sc-row:last-child { border-bottom: none; }
.sc-row.link:active { background: var(--bg); }
.sc-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; }
.sc-text { flex: 1; min-width: 0; }
.sc-label { display: block; font-weight: 700; font-size: .9rem; margin-bottom: 2px; }
.sc-desc { display: block; font-size: .76rem; color: var(--text-muted); line-height: 1.4; word-break: break-word; }
.sc-trail { display: flex; align-items: center; gap: 6px; flex-shrink: 0; font-size: .8rem; font-weight: 700; }
.sc-trail.on { color: var(--success); }
.sc-trail.off { color: var(--text-muted); }
.sc-trail svg { color: var(--border-dark); }
.sc-note { font-size: .76rem; color: var(--text-light); line-height: 1.5; margin: 10px 4px 0; }

.toggle-switch { position: relative; display: inline-block; width: 50px; height: 28px; flex-shrink: 0; }
.toggle-switch input { opacity: 0; width: 0; height: 0; }
.toggle-slider { position: absolute; cursor: pointer; inset: 0; background: var(--border-dark); border-radius: 30px; transition: .2s; }
.toggle-slider:before { content: ''; position: absolute; width: 22px; height: 22px; left: 3px; bottom: 3px; background: #fff; border-radius: 50%; transition: .2s; box-shadow: 0 1px 3px rgba(0,0,0,.2); }
.toggle-switch input:checked + .toggle-slider { background: var(--primary); }
.toggle-switch input:checked + .toggle-slider:before { transform: translateX(22px); }
</style>

<div class="sc-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">Security &amp; Privacy</span>
    </div>
    <a href="help_center.php" class="icon-btn" title="Help">
      <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 115.83 1c0 2-3 2-3 4"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
    </a>
  </div>

  <div class="sc-hero">
    <div class="sc-hero-icon">
      <span class="dot"></span>
      <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><polyline points="9 12 11 14 15 10"/></svg>
    </div>
    <h1>Security &amp; Privacy</h1>
    <p>Manage your account protection</p>
  </div>

  <div class="sc-group-label">Access Control</div>
  <div class="sc-card">
    <div class="sc-row" id="bioRow">
      <span class="sc-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="M12 11a4 4 0 014 4v2M7 16v-1a5 5 0 015-5M5 11a9 9 0 0114 0M8.5 8.5a6 6 0 017 0M12 15v4"/></svg></span>
      <span class="sc-text">
        <span class="sc-label">Biometric sign-in</span>
        <span class="sc-desc" id="bioDesc">Sign in with Face ID or fingerprint on this device</span>
      </span>
      <label class="toggle-switch"><input type="checkbox" id="bioToggle" <?php echo $has_passkey ? 'checked' : ''; ?>><span class="toggle-slider"></span></label>
    </div>
  </div>
  <p class="sc-note" id="bioNote">Uses a secure passkey stored on your device — your password still works as a backup. Available on devices with Face ID, Touch ID or a fingerprint reader.</p>

  <div class="sc-group-label">Advanced Protection</div>
  <div class="sc-card">
    <a href="two_factor.php" class="sc-row link">
      <span class="sc-icon"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="2" width="14" height="20" rx="2"/><line x1="12" y1="18" x2="12.01" y2="18"/></svg></span>
      <span class="sc-text">
        <span class="sc-label">Two-Factor Authentication</span>
        <span class="sc-desc">Verify sign-in with a one-time email code</span>
      </span>
      <span class="sc-trail <?php echo $twofa_on ? 'on' : 'off'; ?>">
        <?php echo $twofa_on ? 'Active' : 'Set up'; ?>
        <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="9 18 15 12 9 6"/></svg>
      </span>
    </a>
    <a href="change_password.php" class="sc-row link">
      <span class="sc-icon"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg></span>
      <span class="sc-text">
        <span class="sc-label">Change Password</span>
        <span class="sc-desc"><?php echo rel_time($u['updated_at']); ?></span>
      </span>
      <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="var(--border-dark)" stroke-width="2.5" stroke-linecap="round"><polyline points="9 18 15 12 9 6"/></svg>
    </a>
  </div>

  <div class="sc-group-label">Account</div>
  <div class="sc-card">
    <div class="sc-row">
      <span class="sc-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="M4 4h16a2 2 0 012 2v12a2 2 0 01-2 2H4a2 2 0 01-2-2V6a2 2 0 012-2z"/><polyline points="22 6 12 13 2 6"/></svg></span>
      <span class="sc-text">
        <span class="sc-label">Sign-in Email</span>
        <span class="sc-desc"><?php echo htmlspecialchars($u['email']); ?></span>
      </span>
    </div>
    <a href="logout.php" class="sc-row link">
      <span class="sc-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 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg></span>
      <span class="sc-text">
        <span class="sc-label">Sign Out</span>
        <span class="sc-desc">End your session on this device</span>
      </span>
      <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="var(--border-dark)" stroke-width="2.5" stroke-linecap="round"><polyline points="9 18 15 12 9 6"/></svg>
    </a>
  </div>
</div>

<div class="os-toast" id="scToast" 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/webauthn.js?v=5"></script>
<script>
(function () {
  function scToast(m){ const t=document.getElementById('scToast'); t.textContent=m; t.style.opacity='1'; clearTimeout(window._sc); window._sc=setTimeout(()=>t.style.opacity='0',2200); }
  const toggle = document.getElementById('bioToggle');
  const desc   = document.getElementById('bioDesc');
  const note   = document.getElementById('bioNote');
  if (!toggle) return;

  // Disable the control on devices/browsers that can't do platform biometrics.
  (async function () {
    if (!window.WA || !WA.supported()) {
      toggle.disabled = true;
      if (!toggle.checked && desc) desc.textContent = 'Not supported by this browser';
      return;
    }
    const avail = await WA.platformAvailable();
    if (!avail && !toggle.checked) {
      toggle.disabled = true;
      if (desc) desc.textContent = 'No Face ID / fingerprint found on this device';
    }
  })();

  toggle.addEventListener('change', async () => {
    if (toggle.checked) {
      toggle.disabled = true;
      try {
        await WA.register();
        scToast('Biometric sign-in enabled');
        if (note) note.textContent = 'Enabled. You can now sign in with Face ID or fingerprint on this device.';
      } catch (e) {
        toggle.checked = false;
        scToast(e.message || 'Could not enable biometric sign-in');
      } finally {
        toggle.disabled = false;
      }
    } else {
      if (!confirm('Turn off biometric sign-in and remove passkeys from your account?')) { toggle.checked = true; return; }
      toggle.disabled = true;
      try {
        const r = await (await fetch('webauthn_remove.php', { method: 'POST' })).json();
        scToast(r.ok ? 'Biometric sign-in disabled' : 'Could not disable right now');
        if (!r.ok) toggle.checked = true;
      } catch (e) {
        toggle.checked = true; scToast('Network error. Please try again.');
      } finally {
        toggle.disabled = false;
      }
    }
  });
})();
</script>

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