<?php
// ============================================================
//  MediCore — Customer Portal: Phone + OTP / Password Login
//  File: shop/login.php
//  Default flow is phone + OTP (also handles first-time
//  registration — see api/customer-auth.php's api_request_otp()).
//  A customer who has set a password from their profile page can
//  switch to a phone + password form instead; OTP always remains
//  available too since it's the built-in recovery path.
// ============================================================
require_once '../includes/customer_auth.php';

if (customer_logged_in()) {
    header('Location: ' . base_url('shop/index.php'));
    exit;
}

$shopPage = 'login';
$title    = 'Login / Register';
require_once '../includes/shop_header.php';
?>
<div style="max-width:380px;margin:40px auto 0">
  <div class="card" style="padding:28px">
    <div style="text-align:center;margin-bottom:20px">
      <div style="font-size:34px">💊</div>
      <div style="font-weight:800;font-size:16px;margin-top:4px">
        <?= htmlspecialchars(portal_shop_name()) ?>
      </div>
      <div style="font-size:11.5px;color:var(--text3);margin-top:4px">
        <?= htmlspecialchars(portal_welcome_text()) ?>
      </div>
    </div>

    <div id="err-box" style="display:none" class="flash-error"></div>
    <div id="notice-box" style="display:none" class="flash-success"></div>

    <!-- ── Step 1: phone entry (OTP flow) ── -->
    <div id="step-phone">
      <div class="fg" style="margin-bottom:12px">
        <label>Phone Number</label>
        <input type="tel" id="in-phone" placeholder="e.g. 01712345678" autofocus
               style="width:100%">
      </div>
      <div class="fg" style="margin-bottom:18px">
        <label>Your Name <span style="color:var(--text3);font-weight:400">(first time only)</span></label>
        <input type="text" id="in-name" placeholder="Full name" style="width:100%">
      </div>
      <button class="btn btn-primary" style="width:100%;padding:9px" onclick="requestOtp()">
        Send Verification Code
      </button>
      <div style="text-align:center;margin-top:14px">
        <a href="#" onclick="showPasswordStep();return false" style="font-size:11.5px;color:var(--text3)">
          Have a password? Login with it instead →
        </a>
      </div>
    </div>

    <!-- ── Step 2: OTP entry ── -->
    <div id="step-otp" style="display:none">
      <div style="font-size:12px;color:var(--text2);margin-bottom:14px">
        Enter the 6-digit code sent to <strong id="otp-phone-label"></strong>
      </div>
      <div class="fg" style="margin-bottom:18px">
        <label>Verification Code</label>
        <input type="text" id="in-otp" inputmode="numeric" maxlength="6"
               placeholder="000000" style="width:100%;letter-spacing:4px;font-size:18px;text-align:center">
      </div>
      <button class="btn btn-primary" style="width:100%;padding:9px" onclick="verifyOtp()">
        Verify & Continue
      </button>
      <div style="text-align:center;margin-top:12px">
        <a href="#" onclick="backToPhone();return false" style="font-size:11.5px;color:var(--text3)">
          ← Use a different number
        </a>
        &nbsp;·&nbsp;
        <a href="#" onclick="requestOtp(true);return false" style="font-size:11.5px;color:var(--brand)">
          Resend Code
        </a>
      </div>
    </div>

    <!-- ── Alt: phone + password login ── -->
    <div id="step-password" style="display:none">
      <div class="fg" style="margin-bottom:12px">
        <label>Phone Number</label>
        <input type="tel" id="in-pw-phone" placeholder="e.g. 01712345678" style="width:100%">
      </div>
      <div class="fg" style="margin-bottom:18px">
        <label>Password</label>
        <input type="password" id="in-pw-password" style="width:100%">
      </div>
      <button class="btn btn-primary" style="width:100%;padding:9px" onclick="loginPassword()">
        Login
      </button>
      <div style="text-align:center;margin-top:14px">
        <a href="#" onclick="showPhoneStep();return false" style="font-size:11.5px;color:var(--text3)">
          ← Login with a verification code instead
        </a>
      </div>
    </div>
  </div>
</div>

<script>
let currentPhone = '';

function showErr(msg) {
  const el = document.getElementById('err-box');
  el.textContent = '⚠ ' + msg;
  el.style.display = 'block';
  document.getElementById('notice-box').style.display = 'none';
}
function showNotice(msg) {
  const el = document.getElementById('notice-box');
  el.textContent = msg;
  el.style.display = 'block';
  document.getElementById('err-box').style.display = 'none';
}
function clearMsgs() {
  document.getElementById('err-box').style.display = 'none';
  document.getElementById('notice-box').style.display = 'none';
}

function goToRedirect() {
  const params = new URLSearchParams(window.location.search);
  window.location.href = params.get('redirect') || '<?= base_url("shop/index.php") ?>';
}

// ── OTP flow ──────────────────────────────────────────────────
function showPasswordStep() {
  clearMsgs();
  document.getElementById('step-phone').style.display = 'none';
  document.getElementById('step-otp').style.display = 'none';
  document.getElementById('step-password').style.display = '';
  document.getElementById('in-pw-phone').focus();
}
function showPhoneStep() {
  clearMsgs();
  document.getElementById('step-password').style.display = 'none';
  document.getElementById('step-otp').style.display = 'none';
  document.getElementById('step-phone').style.display = '';
}

async function requestOtp(isResend) {
  const phone = document.getElementById('in-phone').value.trim();
  const name  = document.getElementById('in-name').value.trim();
  if (!phone) { showErr('Enter your phone number.'); return; }

  clearMsgs();
  const r = await apiPost('<?= base_url("api/customer-auth.php") ?>', {
    action: 'request_otp', phone, name,
  });

  if (!r.success) { showErr(r.error || 'Could not send code.'); return; }

  currentPhone = phone;
  document.getElementById('otp-phone-label').textContent = phone;
  document.getElementById('step-phone').style.display = 'none';
  document.getElementById('step-otp').style.display = '';
  document.getElementById('in-otp').focus();

  if (r.debug_otp) {
    showNotice(`📱 Demo mode — no gateway configured yet. Your code is: ${r.debug_otp}`);
  } else {
    showNotice(r.msg || 'Code sent.');
  }
}

async function verifyOtp() {
  const otp = document.getElementById('in-otp').value.trim();
  if (!otp) { showErr('Enter the verification code.'); return; }

  clearMsgs();
  const r = await apiPost('<?= base_url("api/customer-auth.php") ?>', {
    action: 'verify_otp', phone: currentPhone, otp,
  });

  if (!r.success) { showErr(r.error || 'Verification failed.'); return; }
  goToRedirect();
}

function backToPhone() {
  clearMsgs();
  document.getElementById('step-otp').style.display = 'none';
  document.getElementById('step-phone').style.display = '';
}

// ── Password flow ────────────────────────────────────────────
async function loginPassword() {
  const phone    = document.getElementById('in-pw-phone').value.trim();
  const password = document.getElementById('in-pw-password').value;
  if (!phone || !password) { showErr('Enter your phone number and password.'); return; }

  clearMsgs();
  const r = await apiPost('<?= base_url("api/customer-auth.php") ?>', {
    action: 'login_password', phone, password,
  });

  if (!r.success) { showErr(r.error || 'Login failed.'); return; }
  goToRedirect();
}

document.getElementById('in-otp')?.addEventListener('keydown', e => {
  if (e.key === 'Enter') verifyOtp();
});
document.getElementById('in-phone')?.addEventListener('keydown', e => {
  if (e.key === 'Enter') requestOtp();
});
document.getElementById('in-pw-password')?.addEventListener('keydown', e => {
  if (e.key === 'Enter') loginPassword();
});
</script>

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