<?php
// ============================================================
//  MediCore — My Profile (staff self-service)
//  File: profile.php
//  Lets the logged-in user manage their own name/username, upload
//  a profile photo, and change their own password. Mirrors
//  shop/profile.php's UX for the customer portal, but scoped to
//  staff accounts and wired through api/profile.php, which only
//  ever touches current_user_id() — never another account.
// ============================================================
$page  = 'profile';
$title = 'My Profile';
require_once 'includes/header.php';
?>

<div style="max-width:600px">

  <!-- ── Profile card ── -->
  <div class="card" style="padding:22px;margin-bottom:16px">
    <div style="font-weight:800;font-size:14px;margin-bottom:16px">👤 Profile Details</div>

    <div style="display:flex;gap:18px;align-items:center;margin-bottom:20px">
      <div style="position:relative;flex-shrink:0">
        <img id="pic-preview" src="" alt=""
             style="width:80px;height:80px;border-radius:50%;object-fit:cover;
                    background:var(--brand-light);display:none;border:2px solid var(--brand-light)">
        <div id="pic-placeholder"
             style="width:80px;height:80px;border-radius:50%;background:var(--brand);color:#fff;
                    display:flex;align-items:center;justify-content:center;font-size:26px;font-weight:700">—</div>
      </div>
      <div>
        <input type="file" id="pic-input" accept="image/*" style="display:none" onchange="onPicSelected(event)">
        <button type="button" class="btn btn-sm" onclick="document.getElementById('pic-input').click()">
          🖼️ Change Photo
        </button>
        <div id="pic-remove-wrap" style="display:none;margin-top:6px">
          <a href="#" onclick="removePic();return false" style="font-size:11px;color:var(--danger)">Remove photo</a>
        </div>
        <div style="font-size:10.5px;color:var(--text3);margin-top:6px">JPG/PNG, up to ~1.5MB</div>
      </div>
    </div>

    <div class="fg2" style="margin-bottom:12px">
      <div class="fg">
        <label>Full Name</label>
        <input type="text" id="in-name">
      </div>
      <div class="fg">
        <label>Username</label>
        <input type="text" id="in-username">
      </div>
    </div>

    <div style="display:flex;gap:20px;margin-bottom:18px;font-size:12.5px">
      <div><span style="color:var(--text3)">Role</span>
        <div style="font-weight:700" id="stat-role">—</div></div>
      <div><span style="color:var(--text3)">Member Since</span>
        <div style="font-weight:700" id="stat-since">—</div></div>
    </div>

    <div id="profile-err" style="color:var(--danger);font-size:11.5px;margin-bottom:10px;display:none"></div>

    <button class="btn btn-primary" id="save-profile-btn" style="width:100%;padding:9px" onclick="saveProfile()">
      Save Profile
    </button>
  </div>

  <!-- ── Password card ── -->
  <div class="card" style="padding:22px">
    <div style="font-weight:800;font-size:14px;margin-bottom:4px">🔒 Reset Password</div>
    <div style="font-size:11.5px;color:var(--text3);margin-bottom:16px">
      Enter your current password to set a new one.
    </div>

    <div class="fg" style="margin-bottom:12px">
      <label>Current Password</label>
      <input type="password" id="in-cur-pw">
    </div>
    <div class="fg2" style="margin-bottom:12px">
      <div class="fg">
        <label>New Password</label>
        <input type="password" id="in-new-pw" placeholder="At least 6 characters">
      </div>
      <div class="fg">
        <label>Confirm New Password</label>
        <input type="password" id="in-new-pw2">
      </div>
    </div>

    <div id="pw-err" style="color:var(--danger);font-size:11.5px;margin-bottom:10px;display:none"></div>

    <button class="btn" id="save-pw-btn" style="width:100%;padding:9px" onclick="savePassword()">
      Update Password
    </button>
  </div>
</div>

<script>
let pendingPic = undefined; // undefined = unchanged, '' = removed, 'data:...' = new image

function showFieldErr(id, msg) {
  const el = document.getElementById(id);
  if (!msg) { el.style.display = 'none'; el.textContent = ''; return; }
  el.textContent = '⚠ ' + msg;
  el.style.display = 'block';
}

function renderPic(src) {
  const img = document.getElementById('pic-preview');
  const ph  = document.getElementById('pic-placeholder');
  const rm  = document.getElementById('pic-remove-wrap');
  if (src) {
    img.src = src; img.style.display = '';
    ph.style.display = 'none';
    rm.style.display = '';
  } else {
    img.style.display = 'none';
    ph.style.display = 'flex';
    rm.style.display = 'none';
  }
}

function onPicSelected(ev) {
  const file = ev.target.files[0];
  if (!file) return;
  if (!file.type.startsWith('image/')) { showFieldErr('profile-err', 'Please choose an image file.'); return; }
  if (file.size > 2 * 1024 * 1024) { showFieldErr('profile-err', 'Image is too large (max 2MB).'); return; }
  const reader = new FileReader();
  reader.onload = () => {
    pendingPic = reader.result;
    renderPic(pendingPic);
    showFieldErr('profile-err', '');
  };
  reader.readAsDataURL(file);
}
function removePic() {
  pendingPic = '';
  renderPic(null);
}

async function loadProfile() {
  const r = await apiPost('api/profile.php', { action: 'me' });
  if (!r.success) { showFieldErr('profile-err', r.error || 'Could not load profile.'); return; }
  const u = r.data;
  document.getElementById('in-name').value     = u.name || '';
  document.getElementById('in-username').value = u.username || '';
  document.getElementById('stat-role').textContent  = (u.role || '').replace(/^./, c => c.toUpperCase());
  document.getElementById('stat-since').textContent = u.created_at ? u.created_at.slice(0, 10) : '—';

  if (u.photo) {
    renderPic(u.photo);
  } else {
    document.getElementById('pic-placeholder').textContent = (u.avatar || u.name || '?').slice(0, 2).toUpperCase();
    renderPic(null);
  }
}

async function saveProfile() {
  showFieldErr('profile-err', '');
  const name     = document.getElementById('in-name').value.trim();
  const username = document.getElementById('in-username').value.trim();
  if (!name)     { showFieldErr('profile-err', 'Name is required.'); return; }
  if (!username) { showFieldErr('profile-err', 'Username is required.'); return; }

  const payload = { action: 'update_profile', name, username };
  if (pendingPic !== undefined) payload.photo = pendingPic;

  const btn = document.getElementById('save-profile-btn');
  btn.disabled = true; btn.textContent = 'Saving…';

  const r = await apiPost('api/profile.php', payload);

  btn.disabled = false; btn.textContent = 'Save Profile';

  if (!r.success) { showFieldErr('profile-err', r.error || 'Could not save profile.'); return; }
  MediOffline?.toast?.('✅ Profile updated', 'success');

  // Topbar name/avatar were just updated server-side too — refresh in place
  // rather than waiting for the next full page load.
  const tbName = document.querySelector('.tb-user span');
  if (tbName) tbName.textContent = name;
  const tbAv = document.querySelector('.tb-user .tb-av');
  if (tbAv && payload.photo !== undefined) {
    tbAv.innerHTML = payload.photo
      ? `<img src="${payload.photo}" alt="">`
      : name.split(/\s+/).map(w => w[0]).join('').slice(0, 2).toUpperCase();
  }

  pendingPic = undefined;
}

async function savePassword() {
  showFieldErr('pw-err', '');
  const cur = document.getElementById('in-cur-pw').value;
  const pw1 = document.getElementById('in-new-pw').value;
  const pw2 = document.getElementById('in-new-pw2').value;

  if (!cur) { showFieldErr('pw-err', 'Enter your current password.'); return; }
  if (pw1.length < 6) { showFieldErr('pw-err', 'New password must be at least 6 characters.'); return; }
  if (pw1 !== pw2) { showFieldErr('pw-err', 'New passwords do not match.'); return; }

  const btn = document.getElementById('save-pw-btn');
  btn.disabled = true; btn.textContent = 'Saving…';

  const r = await apiPost('api/profile.php', {
    action: 'change_password', current_password: cur, new_password: pw1,
  });

  btn.disabled = false; btn.textContent = 'Update Password';

  if (!r.success) { showFieldErr('pw-err', r.error || 'Could not update password.'); return; }

  document.getElementById('in-cur-pw').value  = '';
  document.getElementById('in-new-pw').value  = '';
  document.getElementById('in-new-pw2').value = '';
  MediOffline?.toast?.('✅ Password updated', 'success');
}

document.addEventListener('DOMContentLoaded', loadProfile);
</script>

<?php require_once 'includes/footer.php'; ?>
