<?php
// ============================================================
//  MediCore — Customer Portal: Profile
//  File: shop/profile.php
//  Editable name/address/email/profile picture, read-only phone/
//  due/advance, and an optional password set/change section — OTP
//  login always remains available regardless of whether a
//  password is set (it doubles as the account-recovery path).
//  Email is optional — it lets order/OTP notifications also go out
//  by email if the Email gateway is configured in Settings.
// ============================================================
require_once '../includes/customer_auth.php';
require_customer_login();

$shopPage = 'profile';
$title    = 'My Profile';
require_once '../includes/shop_header.php';

$cur = get_settings()['currency'];
?>
<div style="max-width:560px;margin:0 auto">
  <div id="err-box" style="display:none" class="flash-error"></div>
  <div id="notice-box" style="display:none" class="flash-success"></div>

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

    <div style="display:flex;gap:16px;align-items:center;margin-bottom:18px">
      <div style="position:relative">
        <img id="pic-preview" src="" alt=""
             style="width:72px;height:72px;border-radius:50%;object-fit:cover;
                    background:var(--brand-light);display:none;border:2px solid var(--brand-light)">
        <div id="pic-placeholder"
             style="width:72px;height:72px;border-radius:50%;background:var(--brand-light);
                    display:flex;align-items:center;justify-content:center;font-size:28px">👤</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>
    </div>

    <div class="fg" style="margin-bottom:12px">
      <label>Full Name</label>
      <input type="text" id="in-name" style="width:100%">
    </div>
    <div class="fg" style="margin-bottom:12px">
      <label>Phone Number</label>
      <input type="text" id="in-phone" disabled style="width:100%;background:var(--brand-light)">
    </div>
    <div class="fg" style="margin-bottom:12px">
      <label>Email <span style="color:var(--text3);font-weight:400">(optional — for email notifications)</span></label>
      <input type="email" id="in-email" placeholder="you@example.com" style="width:100%">
    </div>
    <div class="fg" style="margin-bottom:18px">
      <label>Delivery Address</label>
      <textarea id="in-address" rows="2" style="width:100%"></textarea>
    </div>

    <div style="display:flex;gap:20px;margin-bottom:18px;font-size:12.5px">
      <div><span style="color:var(--text3)">Due</span>
        <div class="mono" style="font-weight:800;color:var(--danger)" id="stat-due">—</div></div>
      <div><span style="color:var(--text3)">Advance</span>
        <div class="mono" style="font-weight:800;color:var(--accent)" id="stat-advance">—</div></div>
    </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">🔒 Password</div>
    <div id="pw-status" style="font-size:11.5px;color:var(--text3);margin-bottom:16px"></div>

    <div class="fg" id="cur-pw-wrap" style="display:none;margin-bottom:12px">
      <label>Current Password</label>
      <input type="password" id="in-cur-pw" style="width:100%">
    </div>
    <div class="fg" style="margin-bottom:12px">
      <label>New Password</label>
      <input type="password" id="in-new-pw" placeholder="At least 6 characters" style="width:100%">
    </div>
    <div class="fg" style="margin-bottom:18px">
      <label>Confirm New Password</label>
      <input type="password" id="in-new-pw2" style="width:100%">
    </div>
    <button class="btn" id="save-pw-btn" style="width:100%;padding:9px" onclick="savePassword()">
      Save Password
    </button>
    <div style="font-size:11px;color:var(--text3);margin-top:10px">
      Forgot your password? Just log out and log back in with a verification code — no password is needed for that.
    </div>
  </div>
</div>

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

function showErr(msg) {
  const el = document.getElementById('err-box');
  el.textContent = '⚠ ' + msg;
  el.style.display = 'block';
  document.getElementById('notice-box').style.display = 'none';
  window.scrollTo({top: 0, behavior: 'smooth'});
}
function showNotice(msg) {
  const el = document.getElementById('notice-box');
  el.textContent = msg;
  el.style.display = 'block';
  document.getElementById('err-box').style.display = 'none';
  window.scrollTo({top: 0, behavior: 'smooth'});
}

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/')) { showErr('Please choose an image file.'); return; }
  if (file.size > 4 * 1024 * 1024) { showErr('Image is too large (max 4MB).'); return; }
  const reader = new FileReader();
  reader.onload = () => {
    pendingPic = reader.result;
    renderPic(pendingPic);
  };
  reader.readAsDataURL(file);
}
function removePic() {
  pendingPic = '';
  renderPic(null);
}

async function loadProfile() {
  const r = await apiPost(window.SHOP_API + 'customer-auth.php', { action: 'me' });
  if (!r.success || !r.logged_in) {
    window.location.href = window.SHOP_BASE + 'shop/login.php';
    return;
  }
  const c = r.customer;
  document.getElementById('in-name').value    = c.name || '';
  document.getElementById('in-phone').value   = c.phone || '';
  document.getElementById('in-email').value   = c.email || '';
  document.getElementById('in-address').value = c.address || '';
  document.getElementById('stat-due').textContent      = '<?= addslashes($cur) ?>' + parseFloat(c.due || 0).toFixed(2);
  document.getElementById('stat-advance').textContent  = '<?= addslashes($cur) ?>' + parseFloat(c.advance || 0).toFixed(2);
  renderPic(c.profile_pic || null);

  hasPassword = !!c.has_password;
  document.getElementById('cur-pw-wrap').style.display = hasPassword ? '' : 'none';
  document.getElementById('pw-status').textContent = hasPassword
    ? 'A password is set for phone + password login.'
    : 'No password set yet — you currently log in with a verification code only.';
  document.getElementById('save-pw-btn').textContent = hasPassword ? 'Update Password' : 'Set Password';
}

async function saveProfile() {
  const name    = document.getElementById('in-name').value.trim();
  const email   = document.getElementById('in-email').value.trim();
  const address = document.getElementById('in-address').value.trim();
  if (!name) { showErr('Name is required.'); return; }

  const payload = { action: 'update_profile', name, address, email };
  if (pendingPic !== undefined) payload.profile_pic = pendingPic;

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

  const r = await apiPost(window.SHOP_API + 'customer-auth.php', payload);

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

  if (!r.success) { showErr(r.error || 'Could not save profile.'); return; }
  pendingPic = undefined;
  showNotice('Profile updated.');
}

async function savePassword() {
  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 (pw1.length < 6) { showErr('New password must be at least 6 characters.'); return; }
  if (pw1 !== pw2) { showErr('New passwords do not match.'); return; }
  if (hasPassword && !cur) { showErr('Enter your current password.'); return; }

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

  const r = await apiPost(window.SHOP_API + 'customer-auth.php', {
    action: 'set_password', current_password: cur, new_password: pw1,
  });

  btn.disabled = false;

  if (!r.success) {
    btn.textContent = hasPassword ? 'Update Password' : 'Set Password';
    showErr(r.error || 'Could not save password.');
    return;
  }

  document.getElementById('in-cur-pw').value = '';
  document.getElementById('in-new-pw').value = '';
  document.getElementById('in-new-pw2').value = '';
  hasPassword = true;
  document.getElementById('cur-pw-wrap').style.display = '';
  document.getElementById('pw-status').textContent = 'A password is set for phone + password login.';
  btn.textContent = 'Update Password';
  showNotice('Password saved.');
}

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

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