<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once 'includes/mailer.php';

// ── Public QR code profile view (no login required) ──────────────────────
if (isset($_GET['uid']) && !empty($_GET['uid'])) {

    // ── Add Friend via QR (AJAX, requires login) ──────────────────────
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
        if (!isset($_SESSION['user_id'])) jsonResponse(['success'=>false,'message'=>'Please log in to add friends.']);
        $myId    = (int)$_SESSION['user_id'];
        $action  = $_POST['action'] ?? '';

        if ($action === 'add_friend_qr') {
            $targetId = (int)($_POST['target_id'] ?? 0);
            if (!$targetId || $targetId === $myId) jsonResponse(['success'=>false,'message'=>'Invalid user.']);
            $exists = $pdo->prepare("SELECT id,status FROM friend_requests WHERE (sender_id=? AND receiver_id=?) OR (sender_id=? AND receiver_id=?)");
            $exists->execute([$myId,$targetId,$targetId,$myId]);
            $row = $exists->fetch();
            if ($row) {
                if ($row['status'] === 'accepted') jsonResponse(['success'=>false,'message'=>'Already friends!','already'=>true]);
                jsonResponse(['success'=>false,'message'=>'Friend request already sent.','pending'=>true]);
            }
            $pdo->prepare("INSERT INTO friend_requests (sender_id,receiver_id) VALUES (?,?)")->execute([$myId,$targetId]);
            // Email notification
            $targetUser = $pdo->prepare("SELECT name,email FROM users WHERE id=?");
            $targetUser->execute([$targetId]); $tu = $targetUser->fetch();
            if ($tu && !empty($tu['email'])) {
                $senderName = $_SESSION['user_name'] ?? 'Someone';
                sendFriendRequest($tu['email'], $tu['name'], $senderName, SITE_URL . '/leaderboard');
            }
            jsonResponse(['success'=>true,'message'=>'Friend request sent!']);
        }
        jsonResponse(['success'=>false]);
    }

    $qrToken = trim($_GET['uid']);
    $stmt = $pdo->prepare("SELECT id, name, email, avatar, google_avatar, is_verified, created_at, auth_provider FROM users WHERE qr_token=?");
    $stmt->execute([$qrToken]);
    $pubUser = $stmt->fetch();

    if (!$pubUser) {
        http_response_code(404);
        require_once 'includes/header.php';
        renderHeader('Profile Not Found', '');
        echo '<div style="text-align:center;padding:80px 20px">
          <div style="font-size:64px;margin-bottom:20px">🔍</div>
          <h2 style="color:var(--text-primary);margin-bottom:10px">Profile Not Found</h2>
          <p style="color:var(--text-muted)">This QR code is invalid or has been regenerated.</p>
          <a href="' . SITE_URL . '" class="btn btn-primary" style="margin-top:24px;display:inline-block">Go Home</a>
        </div>';
        require_once 'includes/footer.php';
        renderFooter();
        exit;
    }

    // ── Public stats ───────────────────────────────────────────────────
    $pubId = $pubUser['id'];

    $q = $pdo->prepare("SELECT COALESCE(SUM(duration_minutes),0) FROM study_sessions WHERE user_id=?");
    $q->execute([$pubId]); $pubTotalMins = (int)$q->fetchColumn();

    $q = $pdo->prepare("SELECT COUNT(*) FROM study_sessions WHERE user_id=?");
    $q->execute([$pubId]); $pubSessions = (int)$q->fetchColumn();

    $q = $pdo->prepare("SELECT COUNT(*) FROM user_achievements WHERE user_id=?");
    $q->execute([$pubId]); $pubBadges = (int)$q->fetchColumn();

    // Streak
    $streakQ = $pdo->prepare("SELECT date FROM study_streaks WHERE user_id=? ORDER BY date DESC");
    $streakQ->execute([$pubId]); $streakDates = $streakQ->fetchAll(PDO::FETCH_COLUMN);
    $pubStreak = 0;
    $check = new DateTime('today');
    foreach ($streakDates as $d) {
        if ($d === $check->format('Y-m-d')) { $pubStreak++; $check->modify('-1 day'); }
        elseif ($d < $check->format('Y-m-d')) break;
    }

    // Top subjects
    $subQ = $pdo->prepare("SELECT s.name, s.color, SUM(ss.duration_minutes) as mins FROM study_sessions ss JOIN subjects s ON ss.subject_id=s.id WHERE ss.user_id=? GROUP BY ss.subject_id ORDER BY mins DESC LIMIT 3");
    $subQ->execute([$pubId]); $pubSubjects = $subQ->fetchAll();

    $pubHours = floor($pubTotalMins / 60);
    $pubMins  = $pubTotalMins % 60;

    // ── Friend status (if viewer is logged in) ─────────────────────────
    $viewerId    = $_SESSION['user_id'] ?? null;
    $friendStatus = null; // null=not logged in, 'self', 'accepted', 'pending_sent', 'pending_recv', 'none'
    if ($viewerId) {
        if ((int)$viewerId === $pubId) {
            $friendStatus = 'self';
        } else {
            $fr = $pdo->prepare("SELECT id,status,sender_id FROM friend_requests WHERE (sender_id=? AND receiver_id=?) OR (sender_id=? AND receiver_id=?)");
            $fr->execute([$viewerId,$pubId,$pubId,$viewerId]);
            $frRow = $fr->fetch();
            if ($frRow) {
                if ($frRow['status'] === 'accepted') $friendStatus = 'accepted';
                elseif ($frRow['status'] === 'pending') $friendStatus = ($frRow['sender_id'] == $viewerId) ? 'pending_sent' : 'pending_recv';
                else $friendStatus = 'none';
            } else {
                $friendStatus = 'none';
            }
        }
    }

    // Show public profile
    require_once 'includes/header.php';
    renderHeader(htmlspecialchars($pubUser['name']) . "'s Profile", '');

    $pubJoined  = date('F j, Y', strtotime($pubUser['created_at']));
    $pubInitial = strtoupper($pubUser['name'][0]);
    $pubHasAvatar = !empty($pubUser['avatar']) && file_exists(__DIR__.'/'.$pubUser['avatar']);
    $pubHasGoogle = !$pubHasAvatar && !empty($pubUser['google_avatar']);
    ?>

<style>
.qrp-wrap {
  max-width: 520px;
  margin: 32px auto;
  padding: 0 16px 60px;
  animation: qrpRise .45s cubic-bezier(.34,1.56,.64,1) both;
}
@keyframes qrpRise {
  from { opacity:0; transform:translateY(22px) scale(.97); }
  to   { opacity:1; transform:translateY(0) scale(1); }
}

/* ── Card ── */
.qrp-card {
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: 24px;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0,0,0,.25), 0 0 0 1px rgba(255,255,255,.03);
}

/* ── Banner ── */
.qrp-banner {
  height: 100px;
  background: linear-gradient(135deg,
    rgba(99,102,241,.4) 0%,
    rgba(168,85,247,.3) 50%,
    rgba(6,182,212,.25) 100%);
  position: relative;
}
.qrp-banner-dots {
  position: absolute;
  inset: 0;
  background-image: radial-gradient(circle, rgba(255,255,255,.15) 1px, transparent 1px);
  background-size: 20px 20px;
}

/* ── Avatar ── */
.qrp-avatar-wrap {
  position: absolute;
  bottom: -42px;
  left: 24px;
}
.qrp-avatar {
  width: 84px; height: 84px;
  border-radius: 50%;
  border: 4px solid var(--bg-card);
  object-fit: cover;
  display: block;
}
.qrp-avatar-init {
  width: 84px; height: 84px;
  border-radius: 50%;
  border: 4px solid var(--bg-card);
  background: linear-gradient(135deg,#6366f1,#a855f7);
  display: flex; align-items: center; justify-content: center;
  font-size: 32px; font-weight: 800; color: #fff;
  font-family: 'Sora', 'Outfit', sans-serif;
}

/* ── Body ── */
.qrp-body { padding: 52px 24px 22px; }
.qrp-name {
  font-family: 'Sora', 'Outfit', sans-serif;
  font-size: 22px; font-weight: 800;
  color: var(--text-primary);
  letter-spacing: -.3px;
  margin-bottom: 4px;
}
.qrp-meta { font-size: 12px; color: var(--text-muted); margin-bottom: 14px; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.qrp-verified {
  display: inline-flex; align-items: center; gap: 4px;
  font-size: 11px; font-weight: 700;
  background: rgba(16,185,129,.1); border: 1px solid rgba(16,185,129,.25);
  color: #10b981; border-radius: 99px; padding: 2px 9px;
}

/* ── Stats grid ── */
.qrp-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
  margin-bottom: 18px;
}
.qrp-stat {
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 12px;
  padding: 12px 8px;
  text-align: center;
}
.qrp-stat-val {
  font-size: 18px;
  font-weight: 800;
  color: var(--text-primary);
  font-family: 'Sora', sans-serif;
  line-height: 1;
  margin-bottom: 4px;
}
.qrp-stat-label {
  font-size: 10px;
  font-weight: 600;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing: .4px;
}

/* ── Top subjects ── */
.qrp-subjects {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 18px;
}
.qrp-subj-chip {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  font-weight: 600;
  color: var(--text-secondary);
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 99px;
  padding: 4px 12px;
}
.qrp-subj-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }

/* ── Add friend button ── */
.qrp-add-btn {
  width: 100%;
  padding: 13px 20px;
  border: none;
  border-radius: 12px;
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
  color: #fff;
  font-size: 15px;
  font-weight: 700;
  font-family: inherit;
  cursor: pointer;
  display: flex; align-items: center; justify-content: center; gap: 9px;
  transition: transform .2s, box-shadow .2s, opacity .2s;
  box-shadow: 0 6px 24px rgba(99,102,241,.35);
  letter-spacing: .2px;
  position: relative;
  overflow: hidden;
  text-decoration: none;
}
.qrp-add-btn::after {
  content: '';
  position: absolute; inset: 0;
  background: linear-gradient(105deg,transparent 30%,rgba(255,255,255,.15),transparent 70%);
  transform: translateX(-100%);
  transition: transform .4s;
}
.qrp-add-btn:hover { transform: translateY(-2px); box-shadow: 0 10px 32px rgba(99,102,241,.5); }
.qrp-add-btn:hover::after { transform: translateX(100%); }
.qrp-add-btn:disabled { opacity: .6; transform: none; cursor: not-allowed; }
.qrp-add-btn.success { background: linear-gradient(135deg,#10b981,#06b6d4); box-shadow: 0 6px 24px rgba(16,185,129,.35); }
.qrp-add-btn.pending { background: rgba(245,158,11,.15); color: #fbbf24; border: 1px solid rgba(245,158,11,.3); box-shadow: none; }
.qrp-add-btn.friends { background: rgba(16,185,129,.12); color: #34d399; border: 1px solid rgba(16,185,129,.3); box-shadow: none; }

/* ── Footer ── */
.qrp-footer {
  padding: 14px 24px;
  border-top: 1px solid var(--border);
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  color: var(--text-muted);
  background: rgba(255,255,255,.02);
}

/* ── Status message ── */
.qrp-msg {
  padding: 10px 14px;
  border-radius: 10px;
  font-size: 13px;
  font-weight: 500;
  display: flex; align-items: center; gap: 8px;
  margin-bottom: 12px;
}
.qrp-msg.ok  { background: rgba(16,185,129,.1); border: 1px solid rgba(16,185,129,.25); color: #6ee7b7; }
.qrp-msg.err { background: rgba(239,68,68,.1);  border: 1px solid rgba(239,68,68,.25);  color: #fca5a5; }

/* spinner */
.qrp-spin {
  display: inline-block; width:14px; height:14px;
  border:2px solid rgba(255,255,255,.3); border-top-color:#fff;
  border-radius:50%; animation:qrpSpin .65s linear infinite;
}
@keyframes qrpSpin { to{transform:rotate(360deg)} }
</style>

<div class="qrp-wrap">
  <div class="qrp-card">

    <!-- Banner -->
    <div class="qrp-banner">
      <div class="qrp-banner-dots"></div>
      <div class="qrp-avatar-wrap">
        <?php if ($pubHasAvatar): ?>
          <img src="<?= SITE_URL ?>/<?= htmlspecialchars($pubUser['avatar']) ?>" class="qrp-avatar" alt="Avatar">
        <?php elseif ($pubHasGoogle): ?>
          <img src="<?= htmlspecialchars($pubUser['google_avatar']) ?>" class="qrp-avatar" alt="Avatar">
        <?php else: ?>
          <div class="qrp-avatar-init"><?= $pubInitial ?></div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Body -->
    <div class="qrp-body">
      <div class="qrp-name"><?= htmlspecialchars($pubUser['name']) ?></div>
      <div class="qrp-meta">
        <span>📅 Joined <?= $pubJoined ?></span>
        <?php if (!empty($pubUser['is_verified'])): ?>
        <span class="qrp-verified">✓ Verified</span>
        <?php endif; ?>
      </div>

      <!-- Stats -->
      <div class="qrp-stats">
        <div class="qrp-stat">
          <div class="qrp-stat-val" style="color:#818cf8"><?= $pubHours ?><span style="font-size:11px;font-weight:600;color:var(--text-muted)">h</span></div>
          <div class="qrp-stat-label">Studied</div>
        </div>
        <div class="qrp-stat">
          <div class="qrp-stat-val" style="color:#34d399"><?= $pubSessions ?></div>
          <div class="qrp-stat-label">Sessions</div>
        </div>
        <div class="qrp-stat">
          <div class="qrp-stat-val" style="color:#fb923c"><?= $pubStreak ?><span style="font-size:13px">🔥</span></div>
          <div class="qrp-stat-label">Streak</div>
        </div>
        <div class="qrp-stat">
          <div class="qrp-stat-val" style="color:#fbbf24"><?= $pubBadges ?></div>
          <div class="qrp-stat-label">Badges</div>
        </div>
      </div>

      <!-- Top subjects -->
      <?php if ($pubSubjects): ?>
      <div class="qrp-subjects">
        <?php foreach ($pubSubjects as $s): ?>
        <span class="qrp-subj-chip">
          <span class="qrp-subj-dot" style="background:<?= htmlspecialchars($s['color']) ?>"></span>
          <?= htmlspecialchars($s['name']) ?>
        </span>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>

      <!-- Add Friend / Status button -->
      <div id="qrpMsgBox" style="display:none"></div>

      <?php if ($friendStatus === 'self'): ?>
        <a href="<?= SITE_URL ?>/profile" class="qrp-add-btn friends">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
          This is your profile
        </a>

      <?php elseif ($friendStatus === 'accepted'): ?>
        <button class="qrp-add-btn friends" disabled>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="20 6 9 17 4 12"/></svg>
          Already Friends
        </button>

      <?php elseif ($friendStatus === 'pending_sent'): ?>
        <button class="qrp-add-btn pending" disabled>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
          Request Sent — Pending
        </button>

      <?php elseif ($friendStatus === 'pending_recv'): ?>
        <button class="qrp-add-btn" style="background:linear-gradient(135deg,#10b981,#6366f1)" onclick="acceptFromQR()">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="20 6 9 17 4 12"/></svg>
          Accept Friend Request
        </button>

      <?php elseif ($friendStatus === 'none'): ?>
        <button class="qrp-add-btn" id="qrpAddBtn" onclick="addFriendQR(<?= $pubId ?>)">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="8.5" cy="7" r="4"/><line x1="20" y1="8" x2="20" y2="14"/><line x1="23" y1="11" x2="17" y2="11"/></svg>
          Add Friend
        </button>

      <?php else: ?>
        <!-- Not logged in -->
        <a href="<?= SITE_URL ?>/login" class="qrp-add-btn">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" y1="12" x2="3" y2="12"/></svg>
          Login to Add Friend
        </a>
      <?php endif; ?>
    </div>

    <!-- Footer -->
    <div class="qrp-footer">
      <span>
        <a href="<?= SITE_URL ?>" style="color:var(--accent);font-weight:700;text-decoration:none">📚 StudyTrack</a>
        &nbsp;·&nbsp; Scanned via QR Code
      </span>
      <span>#<?= $pubId ?></span>
    </div>
  </div>

  <!-- Join prompt for non-users -->
  <?php if (!$viewerId): ?>
  <div style="text-align:center;margin-top:18px">
    <a href="<?= SITE_URL ?>/register" class="btn btn-primary" style="display:inline-flex;align-items:center;gap:8px;padding:12px 28px">
      ✨ Join StudyTrack for free
    </a>
    <div style="font-size:12px;color:var(--text-muted);margin-top:10px">Track your A/L studies · Free forever</div>
  </div>
  <?php endif; ?>
</div>

<script>
var QRP_TARGET_ID = <?= $pubId ?>;
var QRP_URL = '<?= SITE_URL ?>/profile.php?uid=<?= urlencode($qrToken) ?>';

function qrpMsg(msg, type) {
  var el = document.getElementById('qrpMsgBox');
  el.className = 'qrp-msg ' + (type === 'ok' ? 'ok' : 'err');
  el.innerHTML = (type === 'ok' ? '✅ ' : '⚠️ ') + msg;
  el.style.display = 'flex';
}

async function addFriendQR(targetId) {
  var btn = document.getElementById('qrpAddBtn');
  if (!btn) return;
  btn.disabled = true;
  btn.innerHTML = '<span class="qrp-spin"></span> Sending request…';

  var fd = new FormData();
  fd.append('action', 'add_friend_qr');
  fd.append('target_id', targetId);

  try {
    var res  = await fetch(QRP_URL, { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} });
    var data = await res.json();
    if (data.success) {
      btn.className = 'qrp-add-btn success';
      btn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="20 6 9 17 4 12"/></svg> Request Sent!';
      qrpMsg('Friend request sent! They\'ll be notified.', 'ok');
    } else {
      btn.disabled = false;
      btn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="8.5" cy="7" r="4"/><line x1="20" y1="8" x2="20" y2="14"/><line x1="23" y1="11" x2="17" y2="11"/></svg> Add Friend';
      qrpMsg(data.message || 'Something went wrong.', 'err');
    }
  } catch(e) {
    btn.disabled = false;
    btn.innerHTML = 'Add Friend';
    qrpMsg('Connection error. Try again.', 'err');
  }
}
</script>

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

requireLogin();
$uid = $_SESSION['user_id'];
$success = ''; $error = '';

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

    if ($action === 'delete_check_password') {
        $stmt = $pdo->prepare("SELECT password, email, name, auth_provider FROM users WHERE id=?");
        $stmt->execute([$uid]);
        $user = $stmt->fetch();

        if (!empty($user['auth_provider']) && in_array($user['auth_provider'], ['google','facebook']) && empty($_POST['password'])) {
            $otp     = generateOTP();
            $expires = date('Y-m-d H:i:s', time() + 600);
            $pdo->prepare("UPDATE users SET otp_code=?, otp_expires=? WHERE id=?")->execute([$otp, $expires, $uid]);
            $emailBody = '<p style="color:#94a3b8;">Hello <strong style="color:#f8fafc;">' . htmlspecialchars($user['name']) . '</strong>,</p><p style="color:#94a3b8;">We received a request to <strong style="color:#ef4444;">permanently delete</strong> your StudyTrack account.</p><p style="color:#94a3b8;">Your verification code is:</p><div style="text-align:center;margin:30px 0;"><span style="background:linear-gradient(135deg,#ef4444,#dc2626);color:#fff;font-size:36px;font-weight:700;padding:16px 32px;border-radius:12px;letter-spacing:8px;display:inline-block;">' . $otp . '</span></div><p style="color:#94a3b8;">This code expires in <strong style="color:#f8fafc;">10 minutes</strong>.</p><p style="color:#ef4444;font-weight:600;">⚠️ If you did NOT request this, please contact support immediately.</p>';
            $sent = sendEmail($user['email'], $user['name'], '⚠️ Account Deletion Verification - StudyTrack', $emailBody);
            if (!$sent) jsonResponse(['success' => false, 'message' => 'Could not send OTP email. Please try again.']);
            jsonResponse(['success' => true, 'google_user' => true, 'message' => 'OTP sent to ' . $user['email']]);
        }

        $password = $_POST['password'] ?? '';
        if (!$user || !password_verify($password, $user['password'])) {
            jsonResponse(['success' => false, 'message' => 'Incorrect password. Please try again.']);
        }

        $otp     = generateOTP();
        $expires = date('Y-m-d H:i:s', time() + 600);
        $pdo->prepare("UPDATE users SET otp_code=?, otp_expires=? WHERE id=?")->execute([$otp, $expires, $uid]);
        $emailBody = '<p style="color:#94a3b8;">Hello <strong style="color:#f8fafc;">' . htmlspecialchars($user['name']) . '</strong>,</p><p style="color:#94a3b8;">We received a request to <strong style="color:#ef4444;">permanently delete</strong> your StudyTrack account.</p><p style="color:#94a3b8;">Your verification code is:</p><div style="text-align:center;margin:30px 0;"><span style="background:linear-gradient(135deg,#ef4444,#dc2626);color:#fff;font-size:36px;font-weight:700;padding:16px 32px;border-radius:12px;letter-spacing:8px;display:inline-block;">' . $otp . '</span></div><p style="color:#94a3b8;">This code expires in <strong style="color:#f8fafc;">10 minutes</strong>.</p><p style="color:#ef4444;font-weight:600;">⚠️ If you did NOT request this, please change your password immediately.</p>';
        $sent = sendEmail($user['email'], $user['name'], '⚠️ Account Deletion Verification - StudyTrack', $emailBody);
        if (!$sent) jsonResponse(['success' => false, 'message' => 'Could not send OTP email. Please try again.']);
        jsonResponse(['success' => true, 'message' => 'OTP sent to ' . $user['email']]);
    }

    if ($action === 'delete_verify_otp') {
        $otp = trim($_POST['otp'] ?? '');
        $stmt = $pdo->prepare("SELECT otp_code, otp_expires FROM users WHERE id=?");
        $stmt->execute([$uid]);
        $row = $stmt->fetch();
        if (!$row || $row['otp_code'] !== $otp) jsonResponse(['success' => false, 'message' => 'Invalid OTP code. Please try again.']);
        if (strtotime($row['otp_expires']) < time()) jsonResponse(['success' => false, 'message' => 'OTP has expired. Please restart the process.']);
        try {
            $userStmt = $pdo->prepare("SELECT email, name, avatar FROM users WHERE id=?");
            $userStmt->execute([$uid]);
            $userToDelete = $userStmt->fetch();
            if ($userToDelete && $userToDelete['avatar'] && file_exists(__DIR__ . '/' . $userToDelete['avatar'])) @unlink(__DIR__ . '/' . $userToDelete['avatar']);
            $pdo->prepare("DELETE FROM users WHERE id=?")->execute([$uid]);
            if ($userToDelete && !empty($userToDelete['email'])) sendAccountDeleted($userToDelete['email'], $userToDelete['name']);
            session_destroy();
            jsonResponse(['success' => true, 'redirect' => SITE_URL . '/login']);
        } catch (Exception $e) {
            jsonResponse(['success' => false, 'message' => 'Deletion failed. Please contact support.']);
        }
    }

    if ($action === 'upload_avatar') {
        if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] === 0) {
            $allowed = ['image/jpeg','image/png','image/gif','image/webp'];
            $maxSize = 2 * 1024 * 1024;
            $file = $_FILES['avatar'];
            if (!in_array($file['type'], $allowed)) jsonResponse(['success' => false, 'message' => 'Only JPG, PNG, GIF or WebP images allowed.']);
            elseif ($file['size'] > $maxSize) jsonResponse(['success' => false, 'message' => 'Image must be under 2MB.']);
            else {
                $ext  = pathinfo($file['name'], PATHINFO_EXTENSION);
                $name = 'avatar_' . $uid . '_' . time() . '.' . strtolower($ext);
                $dir  = __DIR__ . '/assets/uploads/avatars/';
                if (!is_dir($dir)) mkdir($dir, 0755, true);
                $dest = $dir . $name;
                $oldQ = $pdo->prepare("SELECT avatar FROM users WHERE id=?"); $oldQ->execute([$uid]); $oldAvatar = $oldQ->fetchColumn();
                if ($oldAvatar && file_exists(__DIR__.'/'.$oldAvatar)) @unlink(__DIR__.'/'.$oldAvatar);
                if (move_uploaded_file($file['tmp_name'], $dest)) {
                    $rel = 'assets/uploads/avatars/' . $name;
                    $pdo->prepare("UPDATE users SET avatar=? WHERE id=?")->execute([$rel, $uid]);
                    jsonResponse(['success' => true, 'message' => 'Profile photo updated!', 'avatar_url' => SITE_URL . '/' . $rel . '?v=' . time()]);
                } else jsonResponse(['success' => false, 'message' => 'Upload failed. Check server permissions.']);
            }
        } else jsonResponse(['success' => false, 'message' => 'Please select an image.']);
    }

    if ($action === 'remove_avatar') {
        $oldQ = $pdo->prepare("SELECT avatar FROM users WHERE id=?"); $oldQ->execute([$uid]); $oldAvatar = $oldQ->fetchColumn();
        if ($oldAvatar && file_exists(__DIR__.'/'.$oldAvatar)) @unlink(__DIR__.'/'.$oldAvatar);
        $pdo->prepare("UPDATE users SET avatar=NULL WHERE id=?")->execute([$uid]);
        jsonResponse(['success' => true, 'message' => 'Profile photo removed.']);
    }

    if ($action === 'update_profile') {
        $name = sanitize($_POST['name'] ?? '');
        if ($name) {
            $pdo->prepare("UPDATE users SET name=? WHERE id=?")->execute([$name, $uid]);
            $_SESSION['user_name'] = $name;
            jsonResponse(['success' => true, 'message' => 'Profile updated!']);
        } else jsonResponse(['success' => false, 'message' => 'Name required']);
    }

    if ($action === 'change_password') {
        $cur = $_POST['current_password'] ?? '';
        $new = $_POST['new_password'] ?? '';
        $con = $_POST['confirm_new'] ?? '';
        $stmt = $pdo->prepare("SELECT password FROM users WHERE id=?"); $stmt->execute([$uid]);
        $hash = $stmt->fetchColumn();
        if (!password_verify($cur, $hash)) jsonResponse(['success' => false, 'message' => 'Current password incorrect.']);
        elseif (strlen($new) < 8) jsonResponse(['success' => false, 'message' => 'New password must be 8+ characters.']);
        elseif ($new !== $con) jsonResponse(['success' => false, 'message' => 'Passwords do not match.']);
        else {
            $pdo->prepare("UPDATE users SET password=? WHERE id=?")->execute([password_hash($new, PASSWORD_BCRYPT, ['cost'=>12]), $uid]);
            jsonResponse(['success' => true, 'message' => 'Password changed!']);
        }
    }

    if ($action === 'regenerate_qr') {
        $newToken = bin2hex(random_bytes(32));
        $pdo->prepare("UPDATE users SET qr_token=? WHERE id=?")->execute([$newToken, $uid]);
        $newUrl = SITE_URL . '/profile.php?uid=' . urlencode($newToken);
        jsonResponse(['success' => true, 'new_token' => $newToken, 'new_url' => $newUrl]);
    }

    jsonResponse(['success' => false, 'message' => 'Unknown action.']);
}

// ── Normal POST ────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'upload_avatar') {
        if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] === 0) {
            $allowed = ['image/jpeg','image/png','image/gif','image/webp']; $maxSize = 2 * 1024 * 1024; $file = $_FILES['avatar'];
            if (!in_array($file['type'], $allowed)) $error = 'Only JPG, PNG, GIF or WebP images allowed.';
            elseif ($file['size'] > $maxSize) $error = 'Image must be under 2MB.';
            else {
                $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
                $name = 'avatar_' . $uid . '_' . time() . '.' . strtolower($ext);
                $dir  = __DIR__ . '/assets/uploads/avatars/';
                if (!is_dir($dir)) mkdir($dir, 0755, true);
                $oldQ = $pdo->prepare("SELECT avatar FROM users WHERE id=?"); $oldQ->execute([$uid]); $oldAvatar = $oldQ->fetchColumn();
                if ($oldAvatar && file_exists(__DIR__.'/'.$oldAvatar)) @unlink(__DIR__.'/'.$oldAvatar);
                if (move_uploaded_file($file['tmp_name'], $dir . $name)) {
                    $pdo->prepare("UPDATE users SET avatar=? WHERE id=?")->execute(['assets/uploads/avatars/' . $name, $uid]);
                    $success = 'Profile photo updated!';
                } else $error = 'Upload failed.';
            }
        } else $error = 'Please select an image.';
    }
    if ($action === 'remove_avatar') {
        $oldQ = $pdo->prepare("SELECT avatar FROM users WHERE id=?"); $oldQ->execute([$uid]); $oldAvatar = $oldQ->fetchColumn();
        if ($oldAvatar && file_exists(__DIR__.'/'.$oldAvatar)) @unlink(__DIR__.'/'.$oldAvatar);
        $pdo->prepare("UPDATE users SET avatar=NULL WHERE id=?")->execute([$uid]);
        $success = 'Profile photo removed.';
    }
    if ($action === 'update_profile') {
        $name = sanitize($_POST['name'] ?? '');
        if ($name) { $pdo->prepare("UPDATE users SET name=? WHERE id=?")->execute([$name, $uid]); $_SESSION['user_name'] = $name; $success = 'Profile updated!'; }
        else $error = 'Name required';
    }
    if ($action === 'change_password') {
        $cur = $_POST['current_password'] ?? ''; $new = $_POST['new_password'] ?? ''; $con = $_POST['confirm_new'] ?? '';
        $stmt = $pdo->prepare("SELECT password FROM users WHERE id=?"); $stmt->execute([$uid]); $hash = $stmt->fetchColumn();
        if (!password_verify($cur, $hash)) $error = 'Current password incorrect.';
        elseif (strlen($new) < 8) $error = 'New password must be 8+ characters.';
        elseif ($new !== $con) $error = 'Passwords do not match.';
        else { $pdo->prepare("UPDATE users SET password=? WHERE id=?")->execute([password_hash($new, PASSWORD_BCRYPT, ['cost'=>12]), $uid]); $success = 'Password changed!'; }
    }
}

$userQ = $pdo->prepare("SELECT * FROM users WHERE id=?"); $userQ->execute([$uid]); $user = $userQ->fetch();

// ── QR Token: generate if missing ────────────────────────────────────────
if (empty($user['qr_token'])) {
    $qrToken = bin2hex(random_bytes(32)); // 64-char hex token
    $pdo->prepare("UPDATE users SET qr_token=? WHERE id=?")->execute([$qrToken, $uid]);
    $user['qr_token'] = $qrToken;
}
$qrProfileUrl = SITE_URL . '/profile.php?uid=' . urlencode($user['qr_token']);
require_once 'includes/header.php';
renderHeader('Profile', 'profile');

$showLocalAvatar  = !empty($user['avatar']) && file_exists(__DIR__.'/'.$user['avatar']);
$showGoogleAvatar = !$showLocalAvatar && !empty($user['google_avatar']);
$isSocial         = !empty($user['auth_provider']) && in_array($user['auth_provider'], ['google','facebook']);
$provider         = $user['auth_provider'] ?? '';
$joinedDate       = date('F j, Y', strtotime($user['created_at']));
$initial          = strtoupper($user['name'][0]);
?>

<style>
@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700;800;900&family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap');

/* ── Profile page tokens ── */
:root {
  --pf: 'Outfit', sans-serif;
  --pb: 'Plus Jakarta Sans', sans-serif;
  --pr: 16px;
  --plg: 22px;
  --pg: 18px;
}

.pp { font-family: var(--pb); max-width: 900px; padding-bottom: 48px; }

/* ════════════════════
   PROFILE HERO BANNER
════════════════════ */
.pp-hero {
  position: relative;
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: var(--plg);
  margin-bottom: var(--pg);
  overflow: hidden;
  animation: pp-rise .45s ease both;
}
.pp-hero-bg {
  position: absolute;
  inset: 0;
  background: linear-gradient(135deg, rgba(99,102,241,.12) 0%, rgba(168,85,247,.08) 50%, rgba(6,182,212,.06) 100%);
  pointer-events: none;
}
.pp-hero-bg::after {
  content: '';
  position: absolute;
  top: -80px; right: -80px;
  width: 320px; height: 320px;
  background: radial-gradient(circle, rgba(99,102,241,.14) 0%, transparent 65%);
  border-radius: 50%;
}
.pp-hero-inner {
  position: relative;
  padding: 24px;
  display: grid;
  grid-template-columns: auto 1fr auto;
  grid-template-rows: auto;
  gap: 18px;
  align-items: center;
}
@media(max-width:600px){
  .pp-hero-inner {
    grid-template-columns: auto 1fr;
    grid-template-rows: auto auto;
    padding: 20px;
    gap: 14px;
  }
  .pp-hero-actions {
    grid-column: 1 / -1;
    display: flex !important;
    flex-direction: row !important;
    align-items: center !important;
    justify-content: flex-start !important;
    gap: 8px;
    padding-top: 4px;
    border-top: 1px solid var(--border);
  }
  .pp-hero-actions .pp-av-hint { display: none !important; }
}

/* Avatar wrapper */
.pp-av-wrap {
  position: relative;
  flex-shrink: 0;
  cursor: pointer;
}
.pp-av {
  width: 80px; height: 80px;
  border-radius: 50%;
  border: 3px solid rgba(99,102,241,.5);
  box-shadow: 0 0 0 4px rgba(99,102,241,.12);
  object-fit: cover;
  display: block;
  background: linear-gradient(135deg,#6366f1,#a855f7);
  transition: box-shadow .2s;
}
.pp-av:hover { box-shadow: 0 0 0 5px rgba(99,102,241,.28); }
.pp-av-init {
  width: 80px; height: 80px;
  border-radius: 50%;
  border: 3px solid rgba(99,102,241,.5);
  box-shadow: 0 0 0 4px rgba(99,102,241,.12);
  background: linear-gradient(135deg,#6366f1,#a855f7);
  display: flex; align-items: center; justify-content: center;
  font-family: var(--pf);
  font-size: 30px; font-weight: 800; color: #fff;
  transition: box-shadow .2s;
}
.pp-av-init:hover { box-shadow: 0 0 0 5px rgba(99,102,241,.28); }
.pp-cam {
  position: absolute;
  bottom: 2px; right: 2px;
  width: 24px; height: 24px;
  border-radius: 50%;
  background: var(--accent);
  border: 2px solid var(--bg-card);
  display: flex; align-items: center; justify-content: center;
  cursor: pointer;
  transition: transform .15s, background .15s;
  box-shadow: 0 2px 8px rgba(0,0,0,.3);
}
.pp-cam:hover { transform: scale(1.12); background: #818cf8; }

/* Hero info */
.pp-hero-info { min-width: 0; }
.pp-name {
  font-family: var(--pf);
  font-size: 22px; font-weight: 800;
  color: var(--text-primary);
  letter-spacing: -.3px;
  line-height: 1.15;
  margin-bottom: 3px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.pp-email {
  font-size: 12px; color: var(--text-muted);
  margin-bottom: 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.pp-chips {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}
.pp-chip {
  display: inline-flex; align-items: center; gap: 4px;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 99px;
  padding: 3px 10px;
  font-size: 11px; font-weight: 600;
  color: var(--text-muted);
  white-space: nowrap;
}
.pp-chip.verified { background: rgba(16,185,129,.1); border-color: rgba(16,185,129,.25); color: #10b981; }
.pp-chip.social { background: rgba(99,102,241,.1); border-color: rgba(99,102,241,.25); color: var(--accent); }

/* ════════════════════
   SECTION CARD
════════════════════ */
.pp-card {
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: var(--plg);
  padding: 24px;
  margin-bottom: var(--pg);
  animation: pp-rise .45s ease both;
}
.pp-card-hd {
  display: flex; align-items: center; gap: 10px;
  margin-bottom: 22px;
}
.pp-card-icon {
  width: 36px; height: 36px;
  border-radius: 10px;
  display: flex; align-items: center; justify-content: center;
  font-size: 17px;
  flex-shrink: 0;
}
.pp-card-title {
  font-family: var(--pf);
  font-size: 15px; font-weight: 700;
  color: var(--text-primary);
  letter-spacing: -.2px;
}
.pp-card-sub {
  font-size: 12px; color: var(--text-muted);
  margin-top: 1px;
}

/* 2-col grid */
.pp-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--pg);
}
@media(max-width:720px){ .pp-grid { grid-template-columns:1fr; } }

/* ── Form overrides (inherit from style.css, just tweak labels) ── */
.pp-label {
  display: block;
  font-size: 12px; font-weight: 700;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing: .7px;
  margin-bottom: 7px;
}
.pp-field-locked {
  width: 100%;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: var(--pr);
  padding: 11px 16px;
  font-size: 14px;
  color: var(--text-muted);
  font-family: var(--pb);
  display: flex; align-items: center; gap: 8px;
}
.pp-lock-icon { font-size: 13px; opacity: .6; }

/* ── Submit button (extends .btn .btn-primary) ── */
.pp-save-btn {
  width: 100%;
  margin-top: 4px;
  padding: 13px;
  font-family: var(--pb);
  font-size: 14px; font-weight: 700;
  letter-spacing: .2px;
}

/* ── Password strength bar ── */
.pp-pw-strength {
  height: 4px;
  border-radius: 99px;
  background: var(--bg-secondary);
  margin-top: 8px;
  overflow: hidden;
}
.pp-pw-bar {
  height: 100%;
  border-radius: 99px;
  width: 0;
  transition: width .3s, background .3s;
}
.pp-pw-hint {
  font-size: 11px;
  color: var(--text-muted);
  margin-top: 5px;
  min-height: 16px;
}

/* ── Social provider card ── */
.pp-social-card {
  display: flex;
  align-items: center;
  gap: 16px;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: var(--pr);
  padding: 16px 18px;
  margin-bottom: 16px;
}
.pp-social-logo {
  width: 44px; height: 44px;
  border-radius: 12px;
  display: flex; align-items: center; justify-content: center;
  flex-shrink: 0;
}
.pp-social-title { font-size: 14px; font-weight: 700; color: var(--text-primary); margin-bottom: 2px; }
.pp-social-desc  { font-size: 12px; color: var(--text-muted); line-height: 1.5; }

/* ── Action cards (logout / delete) ── */
.pp-action-card {
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: var(--plg);
  padding: 22px 24px;
  animation: pp-rise .45s .15s ease both;
}
.pp-action-card.danger { border-color: rgba(239,68,68,.25); background: rgba(239,68,68,.02); }
.pp-action-desc { font-size: 13px; color: var(--text-muted); line-height: 1.7; margin-bottom: 16px; }
.pp-danger-info {
  background: rgba(239,68,68,.07);
  border: 1px solid rgba(239,68,68,.18);
  border-radius: 12px;
  padding: 12px 15px;
  margin-bottom: 18px;
  font-size: 12px;
  color: #fca5a5;
  line-height: 1.7;
}
.pp-danger-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 4px 10px;
  margin-top: 6px;
}

/* ── Biometric card ── */
.pp-bio-device {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 12px 14px;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 12px;
  margin-bottom: 8px;
}
.pp-bio-device-info { display: flex; align-items: center; gap: 12px; }
.pp-bio-device-name { font-size: 13px; font-weight: 700; color: var(--text-primary); }
.pp-bio-device-meta { font-size: 11px; color: var(--text-muted); margin-top: 1px; }
.pp-add-device {
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 14px;
  padding: 16px 18px;
  margin-top: 12px;
}
.pp-add-device-title { font-size: 13px; font-weight: 700; color: var(--text-primary); margin-bottom: 12px; }

/* ── Animations ── */
@keyframes pp-rise {
  from { opacity:0; transform:translateY(16px); }
  to   { opacity:1; transform:translateY(0); }
}

/* Stagger cards */
.pp-card:nth-child(2)  { animation-delay:.06s; }
.pp-card:nth-child(3)  { animation-delay:.10s; }
.pp-card:nth-child(4)  { animation-delay:.14s; }
.pp-action-card:nth-child(2) { animation-delay:.18s; }
</style>

<div class="pp">

<?php if ($error): ?>
  <div class="alert alert-error" data-auto-dismiss style="margin-bottom:16px">⚠️ <?= $error ?></div>
<?php endif; ?>
<?php if ($success): ?>
  <div class="alert alert-success" data-auto-dismiss style="margin-bottom:16px">✅ <?= $success ?></div>
<?php endif; ?>

<!-- Hidden avatar upload form -->
<form method="POST" enctype="multipart/form-data" id="avatarForm" style="display:none">
  <input type="hidden" name="action" value="upload_avatar">
  <input type="file" id="avatarInput" name="avatar" accept="image/jpeg,image/png,image/gif,image/webp">
</form>

<!-- ══════════════════════════════════
     PROFILE HERO
══════════════════════════════════ -->
<div class="pp-hero">
  <div class="pp-hero-bg"></div>
  <div class="pp-hero-inner">

    <!-- Avatar -->
    <div class="pp-av-wrap" onclick="document.getElementById('avatarInput').click()" title="Change photo">
      <?php if ($showLocalAvatar): ?>
        <img src="<?= SITE_URL ?>/<?= htmlspecialchars($user['avatar']) ?>?v=<?= filemtime(__DIR__.'/'.$user['avatar']) ?>"
             id="avatarPreview" class="pp-av" alt="Avatar">
      <?php elseif ($showGoogleAvatar): ?>
        <img src="<?= htmlspecialchars($user['google_avatar']) ?>"
             id="avatarPreview" class="pp-av" alt="Avatar">
      <?php else: ?>
        <div id="avatarPreview" class="pp-av-init"><?= $initial ?></div>
      <?php endif; ?>
      <label for="avatarInput" class="pp-cam" title="Change photo" onclick="event.stopPropagation()">
        <svg width="12" height="12" fill="none" stroke="#fff" stroke-width="2.5" viewBox="0 0 24 24">
          <path d="M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z"/>
          <circle cx="12" cy="13" r="4"/>
        </svg>
      </label>
    </div>

    <!-- Info -->
    <div class="pp-hero-info">
      <div class="pp-name"><?= htmlspecialchars($user['name']) ?></div>
      <div class="pp-email"><?= htmlspecialchars($user['email']) ?></div>
      <div class="pp-chips">
        <?php if (!empty($user['is_verified'])): ?>
          <span class="pp-chip verified">✓ Verified</span>
        <?php endif; ?>
        <?php if ($isSocial): ?>
          <span class="pp-chip social"><?= $provider === 'facebook' ? '🔵 Facebook' : '🔴 Google' ?> Sign-in</span>
        <?php endif; ?>
        <span class="pp-chip">📅 <?= $joinedDate ?></span>
      </div>
    </div>

    <!-- Avatar actions — desktop: right column, mobile: bottom row via CSS -->
    <div class="pp-hero-actions" style="display:flex;flex-direction:column;gap:8px;align-items:flex-end">
      <label for="avatarInput" class="btn btn-secondary btn-sm" style="cursor:pointer;white-space:nowrap">
        📷 Change Photo
      </label>
      <?php if (!empty($user['avatar'])): ?>
        <button type="button" class="btn btn-danger btn-sm" style="white-space:nowrap" onclick="removeAvatarAjax(this)">
          🗑 Remove
        </button>
      <?php endif; ?>
      <div class="pp-av-hint" style="font-size:10px;color:var(--text-muted);text-align:right;white-space:nowrap">JPG, PNG, WebP · Max 2MB</div>
    </div>

  </div>
</div>

<!-- ══════════════════════════════════
     2-COL: Edit Profile + Change Password
══════════════════════════════════ -->
<div class="pp-grid">

  <!-- Edit Profile -->
  <div class="pp-card">
    <div class="pp-card-hd">
      <div class="pp-card-icon" style="background:rgba(99,102,241,.12)">👤</div>
      <div>
        <div class="pp-card-title">Edit Profile</div>
        <div class="pp-card-sub">Update your display name</div>
      </div>
    </div>

    <div id="updateProfileMsg" style="display:none" class="alert"></div>
    <form method="POST" id="updateProfileForm">
      <input type="hidden" name="action" value="update_profile">

      <div class="form-group">
        <label class="pp-label">Full Name</label>
        <input type="text" name="name" class="form-control"
               value="<?= htmlspecialchars($user['name']) ?>" required>
      </div>

      <div class="form-group">
        <label class="pp-label">Email Address</label>
        <div class="pp-field-locked">
          <span class="pp-lock-icon">🔒</span>
          <?= htmlspecialchars($user['email']) ?>
        </div>
      </div>

      <button type="submit" class="btn btn-primary pp-save-btn" id="updateProfileBtn">
        Save Changes
      </button>
    </form>
  </div>

  <!-- Change Password -->
  <div class="pp-card">
    <div class="pp-card-hd">
      <div class="pp-card-icon" style="background:rgba(168,85,247,.12)">🔐</div>
      <div>
        <div class="pp-card-title">Change Password</div>
        <div class="pp-card-sub">Keep your account secure</div>
      </div>
    </div>

    <?php if ($isSocial): ?>
    <div class="pp-social-card">
      <div class="pp-social-logo" style="background:<?= $provider==='facebook'?'rgba(24,119,242,.1)':'rgba(234,67,53,.1)' ?>">
        <?php if ($provider === 'facebook'): ?>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="#1877f2"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>
        <?php else: ?>
          <svg width="22" height="22" viewBox="0 0 48 48"><path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"/><path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"/><path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"/><path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.18 1.48-4.97 2.31-8.16 2.31-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"/></svg>
        <?php endif; ?>
      </div>
      <div>
        <div class="pp-social-title">Signed in with <?= $provider === 'facebook' ? 'Facebook' : 'Google' ?></div>
        <div class="pp-social-desc">
          No password to manage here. Visit your
          <a href="<?= $provider==='facebook'?'https://www.facebook.com/settings?tab=security':'https://myaccount.google.com/security' ?>"
             target="_blank" style="color:var(--accent);font-weight:600">
            <?= $provider==='facebook'?'Facebook':'Google' ?> account settings
          </a> to update your password.
        </div>
      </div>
    </div>

    <?php else: ?>
    <div id="changePasswordMsg" style="display:none" class="alert"></div>
    <form method="POST" id="changePasswordForm">
      <input type="hidden" name="action" value="change_password">

      <div class="form-group">
        <label class="pp-label">Current Password</label>
        <div class="input-icon">
          <span class="icon">🔒</span>
          <input type="password" name="current_password" class="form-control" required>
          <button type="button" class="toggle-password">👁️</button>
        </div>
      </div>

      <div class="form-group">
        <label class="pp-label">New Password</label>
        <div class="input-icon">
          <span class="icon">🔑</span>
          <input type="password" name="new_password" id="newPwInput" class="form-control"
                 placeholder="Min. 8 characters" required oninput="checkPwStrength(this.value)">
          <button type="button" class="toggle-password">👁️</button>
        </div>
        <div class="pp-pw-strength"><div class="pp-pw-bar" id="pwBar"></div></div>
        <div class="pp-pw-hint" id="pwHint"></div>
      </div>

      <div class="form-group">
        <label class="pp-label">Confirm New Password</label>
        <div class="input-icon">
          <span class="icon">🔑</span>
          <input type="password" name="confirm_new" class="form-control" required>
          <button type="button" class="toggle-password">👁️</button>
        </div>
      </div>

      <button type="submit" class="btn btn-primary pp-save-btn" id="changePasswordBtn">
        Change Password
      </button>
    </form>
    <?php endif; ?>
  </div>

</div>

<!-- ══════════════════════════════════
     BIOMETRIC / PASSKEY
══════════════════════════════════ -->
<div class="pp-card" id="biometricCard" style="animation-delay:.12s">
  <div class="pp-card-hd" style="margin-bottom:14px">
    <div class="pp-card-icon" style="background:rgba(6,182,212,.12)">🔐</div>
    <div style="flex:1;min-width:0">
      <div class="pp-card-title">Biometric Login (Passkeys)</div>
      <div class="pp-card-sub">Sign in with fingerprint, face ID, or device PIN</div>
    </div>
    <!-- Device count badge (loaded via JS) -->
    <div id="bmProfileBadge" style="display:none;align-items:center;gap:5px;background:rgba(6,182,212,.1);border:1px solid rgba(6,182,212,.25);border-radius:99px;padding:4px 11px;font-size:12px;font-weight:700;color:rgba(6,182,212,1);white-space:nowrap">
      <span id="bmProfileCount">0</span> device<span id="bmProfilePlural">s</span>
    </div>
  </div>

  <!-- Feature chips -->
  <div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:18px">
    <span style="display:inline-flex;align-items:center;gap:4px;background:var(--bg-secondary);border:1px solid var(--border);border-radius:99px;padding:4px 11px;font-size:11px;font-weight:600;color:var(--text-muted)">👆 Fingerprint</span>
    <span style="display:inline-flex;align-items:center;gap:4px;background:var(--bg-secondary);border:1px solid var(--border);border-radius:99px;padding:4px 11px;font-size:11px;font-weight:600;color:var(--text-muted)">👤 Face ID</span>
    <span style="display:inline-flex;align-items:center;gap:4px;background:var(--bg-secondary);border:1px solid var(--border);border-radius:99px;padding:4px 11px;font-size:11px;font-weight:600;color:var(--text-muted)">⚡ Instant Login</span>
  </div>

  <!-- Not supported warning (shown via JS if needed) -->
  <div id="bmProfileUnsupported" style="display:none;background:rgba(245,158,11,.06);border:1px solid rgba(245,158,11,.22);border-radius:12px;padding:12px 15px;font-size:13px;color:#fbbf24;margin-bottom:14px">
    ⚠️ Your browser or device doesn't support biometric login. Try Chrome, Safari, or Edge on a device with a fingerprint/face reader.
  </div>

  <!-- Registered devices preview -->
  <div id="bmProfileDevicePreview" style="margin-bottom:16px"></div>

  <a href="<?= SITE_URL ?>/biometric"
     style="display:flex;align-items:center;justify-content:center;gap:8px;width:100%;padding:13px;background:linear-gradient(135deg,rgba(6,182,212,.12),rgba(6,182,212,.06));border:1.5px solid rgba(6,182,212,.3);border-radius:14px;color:rgba(6,182,212,1);font-size:14px;font-weight:700;text-decoration:none;transition:background .18s,border-color .18s,transform .12s"
     onmouseover="this.style.transform='translateY(-1px)';this.style.borderColor='rgba(6,182,212,.6)'"
     onmouseout="this.style.transform='';this.style.borderColor='rgba(6,182,212,.3)'">
    <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24">
      <rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/>
    </svg>
    Manage Biometric Devices
    <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24" style="margin-left:auto">
      <path d="M9 18l6-6-6-6"/>
    </svg>
  </a>
</div>

<!-- ══════════════════════════════════
     MY QR CODE CARD
══════════════════════════════════ -->
<div class="pp-card" id="qrCodeCard" style="animation-delay:.16s">
  <div class="pp-card-hd" style="margin-bottom:18px">
    <div class="pp-card-icon" style="background:rgba(99,102,241,.12)">📲</div>
    <div style="flex:1;min-width:0">
      <div class="pp-card-title">My QR Code</div>
      <div class="pp-card-sub">Share your StudyTrack profile with your QR code</div>
    </div>
    <button onclick="downloadQR()" class="btn btn-secondary btn-sm" style="white-space:nowrap;gap:6px;display:flex;align-items:center">
      <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
      Download
    </button>
  </div>

  <div style="display:grid;grid-template-columns:auto 1fr;gap:24px;align-items:center">

    <!-- QR Code Display -->
    <div style="position:relative;flex-shrink:0">
      <div id="qrCodeWrapper" style="
        width:180px;height:180px;
        background:#fff;
        border-radius:18px;
        border:3px solid rgba(99,102,241,.25);
        box-shadow:0 0 0 6px rgba(99,102,241,.07),0 8px 32px rgba(0,0,0,.18);
        display:flex;align-items:center;justify-content:center;
        overflow:hidden;
        position:relative;
      ">
        <!-- QR image will be injected here -->
        <div id="qrLoading" style="display:flex;flex-direction:column;align-items:center;gap:8px">
          <span class="spinner" style="width:28px;height:28px;border-width:3px"></span>
          <span style="font-size:11px;color:var(--text-muted)">Generating…</span>
        </div>
        <img id="qrCodeImg" src="" alt="QR Code" style="display:none;width:160px;height:160px;object-fit:contain;border-radius:8px">
      </div>
      <!-- StudyTrack logo overlay on QR -->
      <div id="qrLogo" style="display:none;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:36px;height:36px;background:#fff;border-radius:8px;border:2px solid rgba(99,102,241,.2);display:flex;align-items:center;justify-content:center;font-size:18px">
        📚
      </div>
    </div>

    <!-- Info & Actions -->
    <div style="min-width:0">
      <div style="font-family:var(--pf);font-size:16px;font-weight:800;color:var(--text-primary);margin-bottom:4px">
        <?= htmlspecialchars($user['name']) ?>
      </div>
      <div style="font-size:12px;color:var(--text-muted);margin-bottom:14px;word-break:break-all">
        🆔 User ID: <strong style="color:var(--accent)">STDEDU<?= $uid ?></strong>
      </div>

      <div style="font-size:12px;color:var(--text-muted);margin-bottom:16px;line-height:1.7">
        Scan this QR code to view your StudyTrack profile. Each user has a unique code linked to their account ID.
      </div>

      <div style="display:flex;flex-direction:column;gap:8px">
        <!-- Copy Link -->
        <button onclick="copyQrLink()" class="btn btn-secondary btn-sm" style="display:flex;align-items:center;gap:6px;justify-content:center">
          <svg width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>
          <span id="copyLinkText">Copy Profile Link</span>
        </button>

        <!-- Regenerate -->
        <button onclick="regenerateQR(this)" class="btn btn-secondary btn-sm" style="display:flex;align-items:center;gap:6px;justify-content:center;color:var(--text-muted)">
          <svg width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 102.13-9.36L1 10"/></svg>
          Regenerate QR Code
        </button>
      </div>
    </div>
  </div>

  <!-- QR URL display -->
  <div style="margin-top:18px;padding:10px 14px;background:var(--bg-secondary);border:1px solid var(--border);border-radius:12px;display:flex;align-items:center;gap:10px;overflow:hidden">
    <span style="font-size:13px;flex-shrink:0">🔗</span>
    <span id="qrUrlDisplay" style="font-size:11px;color:var(--text-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1">
      <?= htmlspecialchars($qrProfileUrl) ?>
    </span>
  </div>
</div>

<style>
/* QR card responsive */
@media(max-width:540px){
  #qrCodeCard [style*="grid-template-columns:auto 1fr"]{
    grid-template-columns:1fr !important;
    justify-items:center;
  }
}
</style>

<script>
// ── QR Code generation (using qr-server API — no JS lib needed) ─────────
(function(){
  var qrUrl = <?= json_encode($qrProfileUrl) ?>;
  var encodedUrl = encodeURIComponent(qrUrl);
  var apiUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=320x320&margin=10&color=6366F1&bgcolor=FFFFFF&qzone=2&data=' + encodedUrl;

  var img = document.getElementById('qrCodeImg');
  var loading = document.getElementById('qrLoading');
  var logo = document.getElementById('qrLogo');

  img.onload = function(){
    loading.style.display = 'none';
    img.style.display = 'block';
    logo.style.display = 'flex';
  };
  img.onerror = function(){
    // Fallback: use Google Charts API
    loading.innerHTML = '<span style="font-size:11px;color:var(--text-muted)">Using fallback…</span>';
    img.src = 'https://chart.googleapis.com/chart?cht=qr&chs=320x320&chl=' + encodedUrl + '&chld=M|2';
  };
  img.src = apiUrl;
  img.dataset.url = qrUrl;
})();

// ── Download QR ───────────────────────────────────────────────────────────
function downloadQR() {
  var img = document.getElementById('qrCodeImg');
  if (!img.src || img.style.display === 'none') {
    showToast('⏳ QR code is still loading. Please wait.', 'error');
    return;
  }
  // Create a canvas, draw the QR, then download
  var canvas = document.createElement('canvas');
  canvas.width = 400; canvas.height = 440;
  var ctx = canvas.getContext('2d');

  // White background
  ctx.fillStyle = '#ffffff';
  ctx.roundRect(0, 0, 400, 440, 20);
  ctx.fill();

  var qrImg = new Image();
  qrImg.crossOrigin = 'anonymous';
  qrImg.onload = function(){
    ctx.drawImage(qrImg, 40, 20, 320, 320);
    // Name & ID text
    ctx.fillStyle = '#1e1b4b';
    ctx.font = 'bold 18px Outfit, sans-serif';
    ctx.textAlign = 'center';
    ctx.fillText(<?= json_encode($user['name']) ?>, 200, 368);
    ctx.fillStyle = '#6366f1';
    ctx.font = '14px Plus Jakarta Sans, sans-serif';
    ctx.fillText('StudyTrack · User #<?= $uid ?>', 200, 394);
    ctx.fillStyle = '#94a3b8';
    ctx.font = '11px monospace';
    ctx.fillText('studytrack.edurx.icu', 200, 420);

    var link = document.createElement('a');
    link.download = 'studytrack-qr-<?= $uid ?>.png';
    link.href = canvas.toDataURL('image/png');
    link.click();
    showToast('✅ QR Code downloaded!', 'success');
  };
  qrImg.src = img.src;
}

// ── Copy profile link ─────────────────────────────────────────────────────
async function copyQrLink() {
  var url = <?= json_encode($qrProfileUrl) ?>;
  var btn = document.getElementById('copyLinkText');
  try {
    await navigator.clipboard.writeText(url);
    btn.textContent = '✅ Copied!';
    showToast('✅ Profile link copied!', 'success');
    setTimeout(()=>{ btn.textContent = 'Copy Profile Link'; }, 2500);
  } catch(e) {
    // Fallback
    var ta = document.createElement('textarea');
    ta.value = url; document.body.appendChild(ta);
    ta.select(); document.execCommand('copy'); document.body.removeChild(ta);
    btn.textContent = '✅ Copied!';
    setTimeout(()=>{ btn.textContent = 'Copy Profile Link'; }, 2500);
  }
}

// ── Regenerate QR (creates new token) ────────────────────────────────────
async function regenerateQR(btn) {
  if (!(await stConfirm('Regenerate your QR code? The old QR code will stop working.', {icon:'🔄', okStyle:'primary', okLabel:'Regenerate'}))) return;
  btn.disabled = true;
  var orig = btn.innerHTML;
  btn.innerHTML = '<span class="spinner"></span>&nbsp; Regenerating…';

  try {
    var fd = new FormData();
    fd.append('action', 'regenerate_qr');
    var res = await fetch(window.location.href, {
      method: 'POST', body: fd,
      headers: {'X-Requested-With': 'XMLHttpRequest'}
    });
    var data = await res.json();
    if (data.success) {
      // Update QR display
      var img = document.getElementById('qrCodeImg');
      var loading = document.getElementById('qrLoading');
      var logo = document.getElementById('qrLogo');

      img.style.display = 'none';
      logo.style.display = 'none';
      loading.innerHTML = '<span class="spinner" style="width:28px;height:28px;border-width:3px"></span><span style="font-size:11px;color:var(--text-muted)">Generating…</span>';
      loading.style.display = 'flex';

      var encodedUrl = encodeURIComponent(data.new_url);
      img.src = 'https://api.qrserver.com/v1/create-qr-code/?size=320x320&margin=10&color=6366F1&bgcolor=FFFFFF&qzone=2&data=' + encodedUrl;
      img.onload = function(){
        loading.style.display = 'none';
        img.style.display = 'block';
        logo.style.display = 'flex';
      };
      document.getElementById('qrUrlDisplay').textContent = data.new_url;
      showToast('✅ New QR Code generated!', 'success');
    } else {
      showToast('⚠️ ' + (data.message || 'Failed to regenerate.'), 'error');
    }
  } catch(e) {
    showToast('⚠️ Connection error.', 'error');
  }
  btn.disabled = false;
  btn.innerHTML = orig;
}
</script>

<!-- ══════════════════════════════════
     ACCOUNT ACTIONS — 2-col
══════════════════════════════════ -->
<div class="pp-grid">

  <!-- Log Out -->
  <div class="pp-action-card">
    <div class="pp-card-hd" style="margin-bottom:14px">
      <div class="pp-card-icon" style="background:rgba(100,116,139,.12)">🚪</div>
      <div>
        <div class="pp-card-title">Log Out</div>
        <div class="pp-card-sub">Sign out from this device</div>
      </div>
    </div>
    <p class="pp-action-desc">
      Sign out of your StudyTrack account on this device. Your data will be saved and synced.
    </p>
    <a href="<?= SITE_URL ?>/logout" class="btn btn-secondary"
       style="width:100%;text-align:center;display:block;padding:12px">
      🚪 Log Out
    </a>
  </div>

  <!-- Delete Account -->
  <div class="pp-action-card danger">
    <div class="pp-card-hd" style="margin-bottom:14px">
      <div class="pp-card-icon" style="background:rgba(239,68,68,.12)">⚠️</div>
      <div>
        <div class="pp-card-title" style="color:var(--danger)">Delete Account</div>
        <div class="pp-card-sub">Permanently remove all your data</div>
      </div>
    </div>
    <p class="pp-action-desc">
      This will permanently delete your account and <strong style="color:var(--danger)">all your data</strong>. This action cannot be undone.
    </p>
    <div class="pp-danger-info">
      <div style="font-weight:700;margin-bottom:6px;text-transform:uppercase;font-size:10px;letter-spacing:.5px">⚠️ Permanently deleted</div>
      <div class="pp-danger-grid">
        <?php foreach(['📖 Study sessions','📊 Marks & results','📝 Notes','🎯 Goals','✅ Tasks','🏆 Achievements','🔔 Reminders','📅 Timetable'] as $item): ?>
          <div style="font-size:12px;color:var(--text-muted)"><?= $item ?></div>
        <?php endforeach; ?>
      </div>
    </div>
    <a href="<?= SITE_URL ?>/delete-account" class="btn btn-full"
      style="background:rgba(239,68,68,.1);color:var(--danger);border:1px solid rgba(239,68,68,.3);font-weight:700;padding:12px;text-align:center;display:block;text-decoration:none">
      🗑️ Delete My Account
    </a>
  </div>

</div>

<!-- ══════════════════════════════════
     MODALS
══════════════════════════════════ -->

<!-- Google/Social delete confirm (kept for reference — deletion moved to delete-account.php) -->
<div class="modal-overlay" id="googleDeleteConfirmModal" style="display:none !important">
  <div class="modal" style="max-width:420px">
    <div class="modal-header">
      <div class="modal-title" style="color:var(--danger)">🗑️ Delete Account</div>
      <button class="modal-close" onclick="closeModal('googleDeleteConfirmModal')">✕</button>
    </div>
    <div style="text-align:center;margin-bottom:22px">
      <div style="width:64px;height:64px;border-radius:50%;background:rgba(239,68,68,.1);border:2px solid rgba(239,68,68,.3);display:flex;align-items:center;justify-content:center;margin:0 auto 14px">
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2"/></svg>
      </div>
      <div style="font-size:16px;font-weight:800;color:var(--text-primary);margin-bottom:8px">Delete Your Account?</div>
      <div style="font-size:13px;color:var(--text-muted);line-height:1.7">
        You're signed in via <strong style="color:var(--text-primary)"><?= $provider==='facebook'?'Facebook':'Google' ?></strong>.
        Deleting will permanently remove all your data.
      </div>
    </div>
    <div id="googleConfirmMsgBox" style="display:none" class="alert"></div>
    <button id="googleConfirmBtn" class="btn btn-full" onclick="googleDeleteConfirmed()"
      style="background:rgba(239,68,68,.1);color:var(--danger);border:1.5px solid rgba(239,68,68,.35);font-weight:700;padding:13px;margin-bottom:10px">
      🗑️ Yes, Delete My Account
    </button>
    <button class="btn btn-secondary btn-full" onclick="closeModal('googleDeleteConfirmModal')">
      Cancel — Keep My Account
    </button>
  </div>
</div>

<!-- Delete Step 1: Password -->
<div class="modal-overlay" id="deleteStep1Modal">
  <div class="modal" style="max-width:400px">
    <div class="modal-header">
      <div class="modal-title" style="color:var(--danger)">🗑️ Delete Account</div>
      <button class="modal-close" onclick="closeModal('deleteStep1Modal')">✕</button>
    </div>
    <div style="text-align:center;margin-bottom:20px">
      <div style="width:58px;height:58px;border-radius:50%;background:rgba(239,68,68,.1);border:2px solid rgba(239,68,68,.3);display:flex;align-items:center;justify-content:center;font-size:24px;margin:0 auto 12px">⚠️</div>
      <div style="font-size:15px;font-weight:700;color:var(--text-primary);margin-bottom:6px">Are you sure?</div>
      <div style="font-size:13px;color:var(--text-muted);line-height:1.6">Enter your password to continue with account deletion.</div>
    </div>
    <div id="step1MsgBox" style="display:none" class="alert"></div>
    <div class="form-group">
      <label class="pp-label">Your Password</label>
      <div class="input-icon">
        <span class="icon">🔒</span>
        <input type="password" id="deletePassword" class="form-control"
               placeholder="Enter your password"
               onkeydown="if(event.key==='Enter') deleteStep1Submit()">
        <button type="button" class="toggle-password">👁️</button>
      </div>
    </div>
    <button id="step1Btn" class="btn btn-full" onclick="deleteStep1Submit()"
      style="background:rgba(239,68,68,.1);color:var(--danger);border:1px solid rgba(239,68,68,.3);font-weight:700;margin-top:4px">
      Continue → Send OTP
    </button>
    <button class="btn btn-secondary btn-full" style="margin-top:10px" onclick="closeModal('deleteStep1Modal')">Cancel</button>
  </div>
</div>

<!-- Delete Step 2: OTP -->
<div class="modal-overlay" id="deleteStep2Modal">
  <div class="modal" style="max-width:400px">
    <div class="modal-header">
      <div class="modal-title" style="color:var(--danger)">🔐 Verify Identity</div>
      <button class="modal-close" onclick="closeModal('deleteStep2Modal')">✕</button>
    </div>
    <div style="text-align:center;margin-bottom:20px">
      <div style="width:58px;height:58px;border-radius:50%;background:rgba(239,68,68,.1);border:2px solid rgba(239,68,68,.3);display:flex;align-items:center;justify-content:center;font-size:24px;margin:0 auto 12px">📧</div>
      <div style="font-size:15px;font-weight:700;color:var(--text-primary);margin-bottom:6px">Check Your Email</div>
      <div id="otpSentMsg" style="font-size:13px;color:var(--text-muted);line-height:1.6">
        A 6-digit code has been sent to your email. Enter it below to confirm deletion.
      </div>
    </div>
    <div id="step2MsgBox" style="display:none" class="alert"></div>
    <div style="display:flex;justify-content:center;gap:8px;margin-bottom:20px" id="otpBoxRow">
      <input type="text" maxlength="1" class="otp-box" id="otp0" oninput="otpNext(this,1)" onkeydown="otpKey(event,this,null,document.getElementById('otp1'))">
      <input type="text" maxlength="1" class="otp-box" id="otp1" oninput="otpNext(this,2)" onkeydown="otpKey(event,this,document.getElementById('otp0'),document.getElementById('otp2'))">
      <input type="text" maxlength="1" class="otp-box" id="otp2" oninput="otpNext(this,3)" onkeydown="otpKey(event,this,document.getElementById('otp1'),document.getElementById('otp3'))">
      <input type="text" maxlength="1" class="otp-box" id="otp3" oninput="otpNext(this,4)" onkeydown="otpKey(event,this,document.getElementById('otp2'),document.getElementById('otp4'))">
      <input type="text" maxlength="1" class="otp-box" id="otp4" oninput="otpNext(this,5)" onkeydown="otpKey(event,this,document.getElementById('otp3'),document.getElementById('otp5'))">
      <input type="text" maxlength="1" class="otp-box" id="otp5" oninput="otpDone()"       onkeydown="otpKey(event,this,document.getElementById('otp4'),null)">
    </div>
    <div style="text-align:center;font-size:12px;color:var(--text-muted);margin-bottom:16px">
      Code expires in <span id="otpTimer" style="font-weight:700;color:var(--accent)">10:00</span>
      &nbsp;·&nbsp;
      <button onclick="deleteStep1Resend()" style="background:none;border:none;color:var(--accent);cursor:pointer;font-size:12px;font-weight:600;padding:0" id="resendBtn">Resend</button>
    </div>
    <button id="step2Btn" class="btn btn-full" onclick="deleteStep2Submit()"
      style="background:rgba(239,68,68,.1);color:var(--danger);border:1px solid rgba(239,68,68,.3);font-weight:700">
      🗑️ Permanently Delete Account
    </button>
    <button class="btn btn-secondary btn-full" style="margin-top:10px" onclick="closeModal('deleteStep2Modal')">Cancel</button>
  </div>
</div>

<style>
@keyframes shake {
  0%,100%{ transform:translateX(0) }
  20%{ transform:translateX(-8px) }
  40%{ transform:translateX(8px) }
  60%{ transform:translateX(-6px) }
  80%{ transform:translateX(6px) }
}
</style>

<script>
// ── Avatar upload ───────────────────────────────────────────────
document.getElementById('avatarInput').addEventListener('change', function() {
  if (!this.files || !this.files[0]) return;
  var reader = new FileReader();
  reader.onload = function(e) {
    var prev = document.getElementById('avatarPreview');
    if (prev.tagName === 'IMG') { prev.src = e.target.result; }
    else {
      var img = document.createElement('img');
      img.id = 'avatarPreview'; img.className = 'pp-av'; img.alt = 'Avatar';
      img.src = e.target.result;
      prev.replaceWith(img);
    }
  };
  reader.readAsDataURL(this.files[0]);
  var fd = new FormData(document.getElementById('avatarForm'));
  fetch(window.location.href, { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} })
    .then(r => r.json()).then(data => {
      if (data.success) showToast('✅ ' + data.message, 'success');
    }).catch(e => console.error(e));
});

async function removeAvatarAjax(btn) {
  if (!(await stConfirm('Remove your profile photo?'))) return;
  btn.disabled = true; btn.textContent = 'Removing…';
  var fd = new FormData(); fd.append('action','remove_avatar');
  var res = await fetch(window.location.href, {method:'POST',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}});
  var data = await res.json();
  if (data.success) {
    var prev = document.getElementById('avatarPreview');
    var div = document.createElement('div');
    div.id = 'avatarPreview'; div.className = 'pp-av-init';
    div.textContent = <?= json_encode($initial) ?>;
    prev.replaceWith(div);
    btn.remove();
  } else { btn.disabled = false; btn.textContent = '🗑 Remove'; }
}

// ── Update Profile ──────────────────────────────────────────────
document.getElementById('updateProfileForm')?.addEventListener('submit', async function(e) {
  e.preventDefault();
  var btn = document.getElementById('updateProfileBtn');
  var orig = btn.innerHTML; btn.disabled = true; btn.innerHTML = '<span class="spinner"></span>';
  var msgBox = document.getElementById('updateProfileMsg'); msgBox.style.display = 'none';
  try {
    var res = await fetch(window.location.href, {method:'POST',body:new FormData(this),headers:{'X-Requested-With':'XMLHttpRequest'}});
    var data = await res.json();
    msgBox.className = 'alert alert-' + (data.success?'success':'error');
    msgBox.innerHTML = (data.success?'✅ ':'⚠️ ') + data.message;
    msgBox.style.display = 'flex';
    if (data.success) {
      // Update hero name
      var n = this.querySelector('[name="name"]').value.trim();
      document.querySelector('.pp-name').textContent = n;
    }
    setTimeout(()=>{ msgBox.style.display='none'; }, 4000);
  } catch(e) {
    msgBox.className='alert alert-error'; msgBox.innerHTML='⚠️ Connection error.'; msgBox.style.display='flex';
  }
  btn.disabled = false; btn.innerHTML = orig;
});

// ── Change Password ─────────────────────────────────────────────
document.getElementById('changePasswordForm')?.addEventListener('submit', async function(e) {
  e.preventDefault();
  var btn = document.getElementById('changePasswordBtn');
  var orig = btn.innerHTML; btn.disabled = true; btn.innerHTML = '<span class="spinner"></span>';
  var msgBox = document.getElementById('changePasswordMsg'); msgBox.style.display = 'none';
  try {
    var res = await fetch(window.location.href, {method:'POST',body:new FormData(this),headers:{'X-Requested-With':'XMLHttpRequest'}});
    var data = await res.json();
    msgBox.className = 'alert alert-' + (data.success?'success':'error');
    msgBox.innerHTML = (data.success?'✅ ':'⚠️ ') + data.message;
    msgBox.style.display = 'flex';
    if (data.success) this.reset();
    setTimeout(()=>{ msgBox.style.display='none'; }, 4000);
  } catch(e) {
    msgBox.className='alert alert-error'; msgBox.innerHTML='⚠️ Connection error.'; msgBox.style.display='flex';
  }
  btn.disabled = false; btn.innerHTML = orig;
});

// ── Password strength ───────────────────────────────────────────
function checkPwStrength(val) {
  var bar = document.getElementById('pwBar');
  var hint = document.getElementById('pwHint');
  if (!bar) return;
  var score = 0;
  if (val.length >= 8)  score++;
  if (/[A-Z]/.test(val)) score++;
  if (/[0-9]/.test(val)) score++;
  if (/[^A-Za-z0-9]/.test(val)) score++;
  var colors = ['#ef4444','#f59e0b','#10b981','#6366f1'];
  var labels = ['Too short','Could be stronger','Good password','Strong password'];
  var widths = ['25%','50%','75%','100%'];
  if (!val) { bar.style.width='0'; hint.textContent=''; return; }
  var i = Math.min(score-1, 3);
  if (i < 0) i = 0;
  bar.style.width = widths[i];
  bar.style.background = colors[i];
  hint.textContent = labels[i];
  hint.style.color = colors[i];
}

// ── Toast helper ────────────────────────────────────────────────
function showToast(msg, type) {
  var t = document.createElement('div');
  t.className = 'alert alert-' + type;
  t.style.cssText = 'position:fixed;top:20px;right:20px;z-index:9999;max-width:300px;animation:pp-rise .3s ease both';
  t.textContent = msg;
  document.body.appendChild(t);
  setTimeout(()=>t.remove(), 3500);
}

// ── Social/Google delete ────────────────────────────────────────
function openGoogleDeleteModal() { openSocialDeleteModal(); }
function openSocialDeleteModal() { openModal('googleDeleteConfirmModal'); }

async function googleDeleteConfirmed() {
  var btn = document.getElementById('googleConfirmBtn');
  btn.disabled = true; btn.innerHTML = '<span class="spinner"></span>&nbsp; Sending OTP…';
  var fd = new FormData(); fd.append('action','delete_check_password');
  try {
    var res = await fetch(window.location.href, {method:'POST',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}});
    var data = await res.json();
    if (data.success) {
      closeModal('googleDeleteConfirmModal');
      openModal('deleteStep2Modal');
      startOtpTimer();
      document.getElementById('otp0').focus();
    } else {
      document.getElementById('googleConfirmMsgBox').className='alert alert-error';
      document.getElementById('googleConfirmMsgBox').innerHTML='⚠️ '+(data.message||'Something went wrong.');
      document.getElementById('googleConfirmMsgBox').style.display='flex';
      btn.disabled = false; btn.innerHTML = 'Yes, Delete My Account';
    }
  } catch(e) {
    document.getElementById('googleConfirmMsgBox').className='alert alert-error';
    document.getElementById('googleConfirmMsgBox').innerHTML='⚠️ Connection error.';
    document.getElementById('googleConfirmMsgBox').style.display='flex';
    btn.disabled = false; btn.innerHTML = 'Yes, Delete My Account';
  }
}

function showMsg(boxId, msg, type) {
  var el = document.getElementById(boxId);
  el.className = 'alert alert-' + type;
  el.innerHTML = (type==='error'?'⚠️ ':'✅ ') + msg;
  el.style.display = 'flex';
}

async function deleteStep1Submit() {
  var pw = document.getElementById('deletePassword').value.trim();
  if (!pw) { showMsg('step1MsgBox','Please enter your password.','error'); return; }
  var btn = document.getElementById('step1Btn');
  btn.disabled = true; btn.innerHTML = '<span class="spinner"></span>&nbsp; Verifying…';
  try {
    var fd = new FormData(); fd.append('action','delete_check_password'); fd.append('password',pw);
    var res = await fetch(window.location.href, {method:'POST',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}});
    var data = await res.json();
    if (data.success) {
      closeModal('deleteStep1Modal');
      document.getElementById('deletePassword').value='';
      document.getElementById('step1MsgBox').style.display='none';
      openModal('deleteStep2Modal'); startOtpTimer();
      document.getElementById('otp0').focus();
    } else showMsg('step1MsgBox', data.message, 'error');
  } catch(e) { showMsg('step1MsgBox','Connection error.','error'); }
  btn.disabled=false; btn.innerHTML='Continue → Send OTP';
}

async function deleteStep1Resend() {
  var btn = document.getElementById('resendBtn');
  btn.textContent = 'Sending…'; btn.disabled = true;
  closeModal('deleteStep2Modal'); clearOtpBoxes();
  document.getElementById('step1MsgBox').style.display='none';
  openModal('deleteStep1Modal');
  btn.textContent='Resend'; btn.disabled=false;
}

async function deleteStep2Submit() {
  var otp = ''; for (var i=0;i<6;i++) otp += (document.getElementById('otp'+i).value||'');
  if (otp.length<6) { showMsg('step2MsgBox','Please enter the full 6-digit code.','error'); return; }
  var btn = document.getElementById('step2Btn');
  btn.disabled=true; btn.innerHTML='<span class="spinner"></span>&nbsp; Deleting account…';
  try {
    var fd = new FormData(); fd.append('action','delete_verify_otp'); fd.append('otp',otp);
    var res = await fetch(window.location.href, {method:'POST',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}});
    var data = await res.json();
    if (data.success) {
      document.querySelector('#deleteStep2Modal .modal').innerHTML = '<div style="text-align:center;padding:40px 20px"><div style="font-size:48px;margin-bottom:16px">👋</div><div style="font-size:18px;font-weight:700;color:var(--text-primary);margin-bottom:10px">Account Deleted</div><div style="font-size:13px;color:var(--text-muted)">Redirecting…</div></div>';
      setTimeout(()=>{ window.location.href = data.redirect; }, 2500);
    } else {
      showMsg('step2MsgBox', data.message, 'error');
      btn.disabled=false; btn.innerHTML='🗑️ Permanently Delete Account';
      document.getElementById('otpBoxRow').style.animation='none';
      setTimeout(()=>{ document.getElementById('otpBoxRow').style.animation='shake .4s ease'; }, 10);
      clearOtpBoxes(); document.getElementById('otp0').focus();
    }
  } catch(e) { showMsg('step2MsgBox','Connection error.','error'); btn.disabled=false; btn.innerHTML='🗑️ Permanently Delete Account'; }
}

function otpNext(el,nextIdx){ el.value=el.value.replace(/\D/g,''); if(el.value&&nextIdx<6) document.getElementById('otp'+nextIdx).focus(); }
function otpDone(){ document.getElementById('otp5').value=document.getElementById('otp5').value.replace(/\D/g,''); }
function otpKey(e,el,prev,next){ if(e.key==='Backspace'&&!el.value&&prev) prev.focus(); if(e.key==='ArrowLeft'&&prev){e.preventDefault();prev.focus();} if(e.key==='ArrowRight'&&next){e.preventDefault();next.focus();} if(e.key==='Enter') deleteStep2Submit(); }
function clearOtpBoxes(){ for(var i=0;i<6;i++){var b=document.getElementById('otp'+i);if(b)b.value='';} }

document.addEventListener('DOMContentLoaded',function(){
  var b = document.getElementById('otp0');
  if (b) b.addEventListener('paste',function(e){
    e.preventDefault();
    var text=(e.clipboardData||window.clipboardData).getData('text').replace(/\D/g,'').slice(0,6);
    for(var i=0;i<text.length;i++){var box=document.getElementById('otp'+i);if(box)box.value=text[i];}
    var last=Math.min(text.length,5); document.getElementById('otp'+last).focus();
  });
});

var _otpTimerInterval=null;
function startOtpTimer(){
  clearInterval(_otpTimerInterval);
  var seconds=600;
  function tick(){
    var m=Math.floor(seconds/60),s=seconds%60;
    var el=document.getElementById('otpTimer');
    if(el) el.textContent=String(m).padStart(2,'0')+':'+String(s).padStart(2,'0');
    if(seconds<=0){clearInterval(_otpTimerInterval);if(el){el.textContent='Expired';el.style.color='var(--danger)';}}
    seconds--;
  }
  tick(); _otpTimerInterval=setInterval(tick,1000);
}

// ── Biometric preview on profile page ──────────────────────────
(function(){
  'use strict';
  const WEBAUTHN_URL = '<?= SITE_URL ?>/webauthn';

  function deviceEmoji(name){
    const n=(name||''). toLowerCase();
    if(n.includes('iphone'))  return '📱';
    if(n.includes('ipad'))    return '📟';
    if(n.includes('android')) return '📱';
    if(n.includes('mac'))     return '💻';
    if(n.includes('windows')||n.includes('pc')||n.includes('laptop')) return '💻';
    if(n.includes('tablet'))  return '📟';
    return '🔐';
  }
  function htmlEsc(s){ return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }

  async function init(){
    if(!window.PublicKeyCredential){
      document.getElementById('bmProfileUnsupported').style.display='block';
      return;
    }
    try{
      const avail = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
      if(!avail){ document.getElementById('bmProfileUnsupported').style.display='block'; return; }
    }catch(e){ document.getElementById('bmProfileUnsupported').style.display='block'; return; }

    try{
      const res  = await fetch(WEBAUTHN_URL + '?action=list-credentials');
      const data = await res.json();
      const preview = document.getElementById('bmProfileDevicePreview');
      const badge   = document.getElementById('bmProfileBadge');
      const countEl = document.getElementById('bmProfileCount');
      const plural  = document.getElementById('bmProfilePlural');

      if(data.credentials && data.credentials.length > 0){
        const n = data.credentials.length;
        countEl.textContent = n;
        plural.textContent = n === 1 ? '' : 's';
        badge.style.display = 'flex';
        const shown = data.credentials.slice(0,2);
        let html = '<div style="display:flex;flex-direction:column;gap:7px">';
        shown.forEach(cr=>{
          const used = cr.last_used_at
            ? new Date(cr.last_used_at).toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})
            : 'Never used';
          html += `<div style="display:flex;align-items:center;gap:10px;padding:10px 13px;background:var(--bg-secondary);border:1px solid var(--border);border-radius:11px">
            <span style="font-size:20px">${deviceEmoji(cr.device_name)}</span>
            <div>
              <div style="font-size:13px;font-weight:700;color:var(--text-primary)">${htmlEsc(cr.device_name)}</div>
              <div style="font-size:11px;color:var(--text-muted)">Last used: ${used}</div>
            </div>
          </div>`;
        });
        if(n > 2) html += `<div style="font-size:12px;color:var(--text-muted);padding:4px 4px 0;text-align:center">+${n-2} more device${n-2>1?'s':''} → <a href="<?= SITE_URL ?>/biometric" style="color:var(--accent)">Manage all</a></div>`;
        html += '</div>';
        preview.innerHTML = html;
      } else {
        preview.innerHTML = '<div style="font-size:13px;color:var(--text-muted);padding:6px 0 10px">No biometric devices registered yet.</div>';
      }
    }catch(e){ console.error('Biometric preview error:', e); }
  }
  init();
})();
</script>

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