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

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

$avatar_path = $u['avatar'] ? 'uploads/avatars/' . $u['avatar'] : '';
$has_avatar  = $avatar_path && file_exists(__DIR__ . '/' . $avatar_path);
?>

<style>
/* ============================================================
   Settings page — SELF-CONTAINED styling.
   These rules are duplicated locally (also live in header.php) on
   purpose: the settings screen must always render correctly even if
   a stale/cached shared stylesheet is served. Scoped to .pf-* and the
   shared settings/sub-topbar classes used only on menu screens.
   ============================================================ */

/* Settings is reached from its own bottom-nav tab, not a focused task
   flow — so the tab bar stays visible (Settings highlighted). */
.app-topbar { display: none; }
.main-content { padding-top: calc(env(safe-area-inset-top) + 6px); }

.pf-wrap { max-width: 600px; margin: 0 auto; }

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

/* --- Profile card --- */
.profile-card {
  background: #fff; border-radius: 20px; padding: 30px 24px 26px; text-align: center;
  margin-bottom: 26px; box-shadow: 0 4px 18px rgba(15,23,42,.06); border: 1px solid var(--border);
}
.profile-avatar-wrap { position: relative; width: 92px; height: 92px; margin: 0 auto 16px; }
.profile-avatar {
  width: 92px; height: 92px; border-radius: 50%; overflow: hidden; background: var(--primary);
  display: flex; align-items: center; justify-content: center; box-shadow: 0 0 0 4px var(--primary-bg);
}
.profile-avatar img { width: 100%; height: 100%; object-fit: cover; display: block; }
.profile-avatar .pa-initials { color: #fff; font-size: 1.7rem; font-weight: 800; }
.profile-edit-btn {
  position: absolute; right: -2px; bottom: -2px; width: 32px; height: 32px; border-radius: 50%;
  background: var(--primary); color: #fff; border: 3px solid #fff; display: flex; align-items: center; justify-content: center;
  cursor: pointer; touch-action: manipulation; padding: 0;
}
.profile-edit-btn:active { background: var(--primary-dark); }
.profile-card h2 { font-size: 1.2rem; font-weight: 800; margin-bottom: 3px; letter-spacing: -.02em; color: var(--text); }
.profile-card p { font-size: .86rem; color: var(--text-muted); word-break: break-word; }

/* --- Settings groups & rows --- */
.settings-group-title { font-size: 1.02rem; font-weight: 800; letter-spacing: -.02em; margin: 24px 0 12px; color: var(--text); }
.settings-card { background: #fff; border-radius: 16px; box-shadow: 0 4px 18px rgba(15,23,42,.06); border: 1px solid var(--border); overflow: hidden; margin-bottom: 4px; }
.settings-row {
  display: flex; align-items: center; gap: 14px; padding: 15px 16px; text-decoration: none; color: var(--text);
  border-bottom: 1px solid var(--border); touch-action: manipulation; background: none;
  width: 100%; text-align: left; font-family: var(--font); cursor: pointer; font-size: .92rem;
}
.settings-row:last-child { border-bottom: none; }
.settings-row:active { background: var(--bg); }
.settings-row .sr-icon { width: 36px; height: 36px; border-radius: 10px; background: var(--primary-bg); color: var(--primary); display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
.settings-row .sr-icon svg { stroke: currentColor; fill: none; }
.settings-row .sr-label { flex: 1; font-weight: 600; }
.settings-row .sr-chevron { color: var(--border-dark); flex-shrink: 0; }
.settings-row.danger { color: var(--error); justify-content: center; }
.settings-row.danger .sr-label { flex: none; font-weight: 700; }

/* --- Crop / zoom modal --- */
.crop-overlay {
  position: fixed; inset: 0; z-index: 900; background: rgba(15,23,42,.72);
  display: none; align-items: flex-end; justify-content: center;
  -webkit-backdrop-filter: blur(2px); backdrop-filter: blur(2px);
}
.crop-overlay.open { display: flex; animation: cropFade .2s ease; }
@keyframes cropFade { from { opacity: 0; } to { opacity: 1; } }
.crop-sheet {
  width: 100%; max-width: 480px; background: #fff; border-radius: 22px 22px 0 0;
  padding: 18px 18px calc(18px + env(safe-area-inset-bottom)); animation: cropUp .26s ease;
}
@keyframes cropUp { from { transform: translateY(100%); } to { transform: translateY(0); } }
.crop-sheet h3 { font-size: 1.05rem; font-weight: 800; text-align: center; margin-bottom: 4px; color: var(--text); }
.crop-sheet .crop-sub { font-size: .8rem; color: var(--text-muted); text-align: center; margin-bottom: 16px; }
.crop-stage {
  position: relative; width: min(76vw, 290px); aspect-ratio: 1 / 1; margin: 0 auto 18px;
  border-radius: 50%; overflow: hidden; background: #0F172A; touch-action: none; cursor: grab;
  box-shadow: 0 0 0 3px #fff, 0 0 0 5px var(--primary-bg);
}
.crop-stage:active { cursor: grabbing; }
.crop-stage img { position: absolute; top: 0; left: 0; will-change: transform; user-select: none; -webkit-user-drag: none; pointer-events: none; max-width: none; }
.crop-zoom-row { display: flex; align-items: center; gap: 12px; margin: 0 6px 18px; color: var(--text-muted); }
.crop-zoom-row svg { width: 18px; height: 18px; stroke: currentColor; fill: none; flex-shrink: 0; }
.crop-zoom-row input[type=range] {
  flex: 1; -webkit-appearance: none; appearance: none; height: 5px; border-radius: 5px;
  background: var(--border); outline: none;
}
.crop-zoom-row input[type=range]::-webkit-slider-thumb {
  -webkit-appearance: none; appearance: none; width: 22px; height: 22px; border-radius: 50%;
  background: var(--primary); cursor: pointer; box-shadow: 0 2px 6px rgba(34,90,227,.4);
}
.crop-zoom-row input[type=range]::-moz-range-thumb {
  width: 22px; height: 22px; border: none; border-radius: 50%; background: var(--primary); cursor: pointer;
}
.crop-actions { display: flex; gap: 12px; }
.crop-btn {
  flex: 1; padding: 14px; border-radius: 13px; font-family: var(--font); font-weight: 700; font-size: .92rem;
  cursor: pointer; border: none; touch-action: manipulation; min-height: 50px;
}
.crop-btn-cancel { background: var(--bg); color: var(--text); border: 1.5px solid var(--border); }
.crop-btn-cancel:active { background: var(--border); }
.crop-btn-save { background: var(--primary); color: #fff; box-shadow: 0 6px 18px rgba(34,90,227,.3); }
.crop-btn-save:active { background: var(--primary-dark); }
.crop-btn:disabled { opacity: .6; cursor: default; }
</style>

<div class="pf-wrap">

  <!-- Topbar -->
  <div class="sub-topbar">
    <div class="sub-topbar-left">
      <a href="dashboard.php" class="sub-back" aria-label="Back">
        <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">Your Profile</span>
    </div>
    <div class="sub-topbar-right">
      <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>

  <!-- Avatar card -->
  <div class="profile-card">
    <div class="profile-avatar-wrap">
      <div class="profile-avatar" id="avatarPreview">
        <?php if ($has_avatar): ?>
          <img src="<?php echo htmlspecialchars($avatar_path); ?>" alt="">
        <?php else: ?>
          <span class="pa-initials"><?php echo $__initials; ?></span>
        <?php endif; ?>
      </div>
      <button type="button" class="profile-edit-btn" onclick="document.getElementById('avatarInput').click()" aria-label="Change photo">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M17 3a2.85 2.83 0 114 4L7.5 20.5 2 22l1.5-5.5z"/></svg>
      </button>
      <input type="file" id="avatarInput" accept="image/*" style="display:none">
    </div>
    <h2><?php echo htmlspecialchars($u['name']); ?></h2>
    <p><?php echo htmlspecialchars($u['email']); ?></p>
  </div>

  <!-- Account -->
  <h2 class="settings-group-title">Account</h2>
  <div class="settings-card">
    <a href="personal_info.php" class="settings-row">
      <span class="sr-icon"><svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/></svg></span>
      <span class="sr-label">Personal Info</span>
      <svg class="sr-chevron" 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>
    </a>
    <a href="change_password.php" class="settings-row">
      <span class="sr-icon"><svg width="17" height="17" 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="sr-label">Change Password</span>
      <svg class="sr-chevron" 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>
    </a>
  </div>

  <!-- Activity -->
  <h2 class="settings-group-title">Activity</h2>
  <div class="settings-card">
    <a href="orders.php" class="settings-row">
      <span class="sr-icon"><svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/><rect x="9" y="3" width="6" height="4" rx="1"/><path d="M9 12h6M9 16h4"/></svg></span>
      <span class="sr-label">Order History</span>
      <svg class="sr-chevron" 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>
    </a>
    <a href="wallet.php" class="settings-row">
      <span class="sr-icon"><svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><polyline points="12 7 12 12 16 14"/></svg></span>
      <span class="sr-label">Transaction History</span>
      <svg class="sr-chevron" 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>
    </a>
  </div>

  <!-- Preferences -->
  <h2 class="settings-group-title">Preferences</h2>
  <div class="settings-card">
    <a href="notification_preferences.php" class="settings-row">
      <span class="sr-icon"><svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8a6 6 0 10-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 01-3.46 0"/></svg></span>
      <span class="sr-label">Notifications</span>
      <svg class="sr-chevron" 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>
    </a>
    <a href="security.php" class="settings-row">
      <span class="sr-icon"><svg width="17" height="17" 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"/></svg></span>
      <span class="sr-label">Security</span>
      <svg class="sr-chevron" 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>
    </a>
  </div>

  <!-- Support -->
  <h2 class="settings-group-title">Support</h2>
  <div class="settings-card">
    <a href="help_center.php" class="settings-row">
      <span class="sr-icon"><svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" 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></span>
      <span class="sr-label">Help Center</span>
      <svg class="sr-chevron" 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>
    </a>
    <a href="contact_admin.php" class="settings-row">
      <span class="sr-icon"><svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 16.92z"/></svg></span>
      <span class="sr-label">Contact Admin</span>
      <svg class="sr-chevron" 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>
    </a>
  </div>

  <!-- Sign out -->
  <div class="settings-card" style="margin-top:22px">
    <a href="logout.php" class="settings-row danger">
      <svg width="17" height="17" 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 class="sr-label">Sign Out</span>
    </a>
  </div>

  <p style="text-align:center;font-size:.74rem;color:var(--text-light);margin:18px 0 8px">Version 1.0</p>

</div>

<!-- ===== Crop / zoom modal ===== -->
<div class="crop-overlay" id="cropOverlay" aria-hidden="true">
  <div class="crop-sheet" role="dialog" aria-modal="true" aria-label="Adjust photo">
    <h3>Adjust your photo</h3>
    <p class="crop-sub">Drag to reposition · pinch or slide to zoom</p>
    <div class="crop-stage" id="cropStage">
      <img id="cropImg" alt="">
    </div>
    <div class="crop-zoom-row">
      <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="7"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/></svg>
      <input type="range" id="cropZoom" min="1" max="4" step="0.01" value="1">
      <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="7"/><line x1="8" y1="11" x2="14" y2="11"/></svg>
    </div>
    <div class="crop-actions">
      <button type="button" class="crop-btn crop-btn-cancel" id="cropCancel">Cancel</button>
      <button type="button" class="crop-btn crop-btn-save" id="cropSave">Set Photo</button>
    </div>
  </div>
</div>

<div class="os-toast" id="profileToast" style="position:fixed;bottom:calc(env(safe-area-inset-bottom) + 24px);left:50%;transform:translateX(-50%);background:#0F172A;color:#fff;padding:11px 20px;border-radius:30px;font-size:.82rem;font-weight:600;box-shadow:0 6px 20px rgba(0,0,0,.25);z-index:950;opacity:0;pointer-events:none;transition:opacity .25s;max-width:86%;text-align:center"></div>

<script>
(function () {
  function showProfileToast(msg) {
    const t = document.getElementById('profileToast');
    t.textContent = msg;
    t.style.opacity = '1';
    clearTimeout(window._pToastTimer);
    window._pToastTimer = setTimeout(() => { t.style.opacity = '0'; }, 3000);
  }

  const input    = document.getElementById('avatarInput');
  const overlay  = document.getElementById('cropOverlay');
  const stage    = document.getElementById('cropStage');
  const img      = document.getElementById('cropImg');
  const zoomEl   = document.getElementById('cropZoom');
  const btnCancel= document.getElementById('cropCancel');
  const btnSave  = document.getElementById('cropSave');
  const preview  = document.getElementById('avatarPreview');
  const OUT = 600; // output size in px (square)

  // Crop state
  let natW = 0, natH = 0;     // natural image size
  let baseScale = 1;          // scale to "cover" the stage at zoom = 1
  let zoom = 1;               // user zoom (>= 1)
  let panX = 0, panY = 0;     // pan offset from center, in screen px
  let stageSize = 0;          // square stage size in px
  const MAX_ZOOM = 4;

  function render() {
    const scale = baseScale * zoom;
    const dw = natW * scale, dh = natH * scale;
    // clamp pan so the image always covers the circular stage
    const maxX = Math.max(0, (dw - stageSize) / 2);
    const maxY = Math.max(0, (dh - stageSize) / 2);
    panX = Math.min(maxX, Math.max(-maxX, panX));
    panY = Math.min(maxY, Math.max(-maxY, panY));
    const left = (stageSize - dw) / 2 + panX;
    const top  = (stageSize - dh) / 2 + panY;
    img.style.width  = dw + 'px';
    img.style.height = dh + 'px';
    img.style.transform = 'translate(' + left + 'px,' + top + 'px)';
  }

  function openCropper(file) {
    const reader = new FileReader();
    reader.onload = function (ev) {
      const tmp = new Image();
      tmp.onload = function () {
        natW = tmp.naturalWidth;
        natH = tmp.naturalHeight;
        img.src = tmp.src;
        overlay.classList.add('open');
        overlay.setAttribute('aria-hidden', 'false');
        document.body.style.overflow = 'hidden';
        // measure stage after it's visible
        requestAnimationFrame(() => {
          stageSize = stage.getBoundingClientRect().width;
          baseScale = Math.max(stageSize / natW, stageSize / natH);
          zoom = 1; panX = 0; panY = 0;
          zoomEl.value = 1;
          render();
        });
      };
      tmp.onerror = function () { showProfileToast("Couldn't read that image."); };
      tmp.src = ev.target.result;
    };
    reader.readAsDataURL(file);
  }

  function closeCropper() {
    overlay.classList.remove('open');
    overlay.setAttribute('aria-hidden', 'true');
    document.body.style.overflow = '';
    img.src = '';
    input.value = '';
  }

  // ---- File chosen ----
  input.addEventListener('change', function (e) {
    const file = e.target.files[0];
    if (!file) return;
    if (!file.type.startsWith('image/')) { showProfileToast('Please choose an image file.'); input.value = ''; return; }
    if (file.size > 12 * 1024 * 1024) { showProfileToast('Image is too large (max 12MB).'); input.value = ''; return; }
    openCropper(file);
  });

  // ---- Zoom slider ----
  zoomEl.addEventListener('input', function () {
    zoom = parseFloat(this.value);
    render();
  });

  // ---- Pointer drag + pinch ----
  const pointers = new Map();
  let pinchStartDist = 0, pinchStartZoom = 1;

  function dist(a, b) { return Math.hypot(a.x - b.x, a.y - b.y); }

  stage.addEventListener('pointerdown', function (e) {
    stage.setPointerCapture(e.pointerId);
    pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
    if (pointers.size === 2) {
      const [p1, p2] = [...pointers.values()];
      pinchStartDist = dist(p1, p2);
      pinchStartZoom = zoom;
    }
  });

  stage.addEventListener('pointermove', function (e) {
    if (!pointers.has(e.pointerId)) return;
    const prev = pointers.get(e.pointerId);
    const cur = { x: e.clientX, y: e.clientY };
    pointers.set(e.pointerId, cur);

    if (pointers.size === 1) {
      panX += cur.x - prev.x;
      panY += cur.y - prev.y;
      render();
    } else if (pointers.size === 2) {
      const [p1, p2] = [...pointers.values()];
      const d = dist(p1, p2);
      if (pinchStartDist > 0) {
        zoom = Math.min(MAX_ZOOM, Math.max(1, pinchStartZoom * (d / pinchStartDist)));
        zoomEl.value = zoom;
        render();
      }
    }
  });

  function endPointer(e) {
    if (pointers.has(e.pointerId)) pointers.delete(e.pointerId);
    if (pointers.size < 2) pinchStartDist = 0;
  }
  stage.addEventListener('pointerup', endPointer);
  stage.addEventListener('pointercancel', endPointer);
  stage.addEventListener('pointerleave', endPointer);

  // Desktop wheel zoom (nice-to-have)
  stage.addEventListener('wheel', function (e) {
    e.preventDefault();
    zoom = Math.min(MAX_ZOOM, Math.max(1, zoom - e.deltaY * 0.0015));
    zoomEl.value = zoom;
    render();
  }, { passive: false });

  btnCancel.addEventListener('click', closeCropper);
  overlay.addEventListener('click', function (e) { if (e.target === overlay) closeCropper(); });

  // ---- Confirm: render crop to canvas & upload ----
  btnSave.addEventListener('click', function () {
    const scale = baseScale * zoom;
    // source square (in natural px) currently inside the stage
    const srcSize = stageSize / scale;
    const left = (stageSize - natW * scale) / 2 + panX;
    const top  = (stageSize - natH * scale) / 2 + panY;
    const sx = (-left) / scale;
    const sy = (-top) / scale;

    const canvas = document.createElement('canvas');
    canvas.width = OUT; canvas.height = OUT;
    const ctx = canvas.getContext('2d');
    ctx.imageSmoothingQuality = 'high';
    ctx.drawImage(img, sx, sy, srcSize, srcSize, 0, 0, OUT, OUT);

    btnSave.disabled = true; btnCancel.disabled = true;
    btnSave.textContent = 'Saving…';

    canvas.toBlob(function (blob) {
      if (!blob) {
        showProfileToast("Couldn't process the image.");
        btnSave.disabled = false; btnCancel.disabled = false; btnSave.textContent = 'Set Photo';
        return;
      }
      const fd = new FormData();
      fd.append('avatar', blob, 'avatar.jpg');
      const prevHtml = preview.innerHTML;
      preview.innerHTML = '<span class="pa-initials" style="font-size:.8rem">…</span>';

      fetch('upload_avatar.php', { method: 'POST', body: fd })
        .then(r => r.json())
        .then(d => {
          if (d.ok && d.url) {
            preview.innerHTML = '<img src="' + d.url + '?t=' + Date.now() + '" alt="">';
            showProfileToast('Profile photo updated!');
            closeCropper();
          } else {
            preview.innerHTML = prevHtml;
            showProfileToast(d.error || "Couldn't update your photo.");
          }
        })
        .catch(() => {
          preview.innerHTML = prevHtml;
          showProfileToast('Upload failed. Check your connection.');
        })
        .finally(() => {
          btnSave.disabled = false; btnCancel.disabled = false; btnSave.textContent = 'Set Photo';
        });
    }, 'image/jpeg', 0.9);
  });
})();
</script>

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