<?php
require_once "db.php";
session_start();

if (!isset($_SESSION['user'])) { header("Location: index.php"); exit; }

/* ===== CSRF ===== */
if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(16)); }
$CSRF = $_SESSION['csrf_token'];

$user = $_SESSION['user'];
$staff_number = $user['staff_number'] ?? '';

/** ===== Helpers: schema introspection ===== */
function column_exists(mysqli $conn, string $table, string $column): bool {
    $sql = "SELECT COUNT(*) AS c
              FROM INFORMATION_SCHEMA.COLUMNS
             WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ss', $table, $column);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return ((int)($res['c'] ?? 0)) > 0;
}
function table_exists(mysqli $conn, string $table): bool {
    $sql = "SELECT COUNT(*) AS c
              FROM INFORMATION_SCHEMA.TABLES
             WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $table);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return ((int)($res['c'] ?? 0)) > 0;
}
/* Active column helper */
function active_col(mysqli $conn, string $table): ?string {
    if (!table_exists($conn,$table)) return null;
    if (column_exists($conn,$table,'is_active')) return 'is_active';
    if (column_exists($conn,$table,'active'))    return 'active';
    return null;
}

/** ===== Tarik ciri skema (dinamik) ===== */
$has_app_date    = column_exists($conn, 'members', 'application_date');
$has_exco_at     = column_exists($conn, 'members', 'exco_approved_at');
$has_ajk_at      = column_exists($conn, 'members', 'ajk_approved_at');
$has_admin_at    = column_exists($conn, 'members', 'admin_approved_at');
$has_official    = column_exists($conn, 'members', 'official_member_since');
$has_created_at  = column_exists($conn, 'members', 'created_at');

$has_waris_name  = column_exists($conn, 'members', 'waris_name');
$has_waris_ph    = column_exists($conn, 'members', 'waris_phone');
$has_home_phone  = column_exists($conn, 'members', 'home_phone');
$has_address     = column_exists($conn, 'members', 'address');
$has_postcode    = column_exists($conn, 'members', 'postcode');
$has_job_title   = column_exists($conn, 'members', 'job_title');

$has_location_str   = column_exists($conn, 'members', 'location'); // legacy
$has_district_id    = column_exists($conn, 'members', 'district_id');
$has_workloc_id     = column_exists($conn, 'members', 'work_location_id');
$has_tbl_districts  = table_exists($conn, 'districts');
$has_tbl_worklocs   = table_exists($conn, 'work_locations');

/** ===== Fetch profil ahli (JOIN districts/work_locations jika ada) ===== */
$cols = [
  "m.id","m.full_name","m.staff_number","m.ic_number","m.email","m.phone","m.race","m.ack_form"
];
$cols[] = $has_home_phone ? "m.home_phone" : "NULL AS home_phone";
$cols[] = $has_address    ? "m.address"    : "NULL AS address";
$cols[] = $has_postcode   ? "m.postcode"   : "NULL AS postcode";
$cols[] = $has_job_title  ? "m.job_title"  : "NULL AS job_title";

$cols[] = $has_app_date   ? "m.application_date"       : "NULL AS application_date";
$cols[] = $has_exco_at    ? "m.exco_approved_at"       : "NULL AS exco_approved_at";
$cols[] = $has_ajk_at     ? "m.ajk_approved_at"        : "NULL AS ajk_approved_at";
$cols[] = $has_admin_at   ? "m.admin_approved_at"      : "NULL AS admin_approved_at";
$cols[] = $has_official   ? "m.official_member_since"  : "NULL AS official_member_since";
$cols[] = $has_created_at ? "m.created_at"             : "NULL AS created_at";

/* Legacy string location for backward compat (papar sahaja) */
$cols[] = $has_location_str ? "m.location" : "NULL AS location";
/* New FK fields */
$cols[] = $has_district_id  ? "m.district_id"      : "NULL AS district_id";
$cols[] = $has_workloc_id   ? "m.work_location_id" : "NULL AS work_location_id";

/* JOINs names */
$joins = [];
if ($has_tbl_districts && $has_district_id) { $joins[] = "LEFT JOIN districts d ON d.id = m.district_id"; $cols[] = "d.name AS district_name"; }
else { $cols[]  = "NULL AS district_name"; }
if ($has_tbl_worklocs && $has_workloc_id)   { $joins[] = "LEFT JOIN work_locations wl ON wl.id = m.work_location_id"; $cols[] = "wl.name AS work_location_name"; }
else { $cols[]  = "NULL AS work_location_name"; }

$sql = "SELECT ".implode(",\n       ", $cols)."
          FROM members m
          ".implode("\n          ", $joins)."
         WHERE m.staff_number = ?
         LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $staff_number);
$stmt->execute();
$res = $stmt->get_result();
$member = $res ? $res->fetch_assoc() : null;
$stmt->close();

/** ===== Jika tiada rekod dalam members, fallback nilai asas dari sesi ===== */
if (!$member) {
    $member = [
        'id' => 0,
        'full_name' => $user['name'] ?? '',
        'staff_number' => $staff_number,
        'ic_number' => '',
        'email' => $user['email'] ?? '',
        'phone' => '',
        'race' => '',
        'location' => '',
        'ack_form' => 0,
        'home_phone' => '',
        'address'    => '',
        'postcode'   => '',
        'job_title'  => '',
        'application_date' => null,
        'exco_approved_at' => null,
        'ajk_approved_at' => null,
        'admin_approved_at' => null,
        'official_member_since' => null,
        'waris_name' => '',
        'waris_phone' => '',
        'created_at' => null,
        'district_id' => null,
        'work_location_id' => null,
        'district_name' => null,
        'work_location_name' => null,
    ];
}

/** ===== Helper: format tarikh selamat ===== */
function fmtDT($v, $fmt) {
    if ($v === null) return '-';
    $s = trim((string)$v);
    if ($s === '' || $s === '0000-00-00' || $s === '0000-00-00 00:00:00') return '-';
    $ts = strtotime($s);
    if ($ts === false || $ts <= 0) return '-';
    return date($fmt, $ts);
}

/** ===== Helper: ambil cap waktu kelulusan pertama ikut ROLE dari approval_logs ===== */
function get_first_approval_time(mysqli $conn, int $memberId, string $role) {
    if ($memberId <= 0 || !table_exists($conn,'approval_logs')) return null;
    $sql = "SELECT `timestamp`
              FROM `approval_logs`
             WHERE `member_id` = ? AND `role` = ? AND `action` = 'approved'
             ORDER BY `timestamp` ASC
             LIMIT 1";
    $stmt = $conn->prepare($sql);
    if (!$stmt) { error_log('get_first_approval_time prepare failed: '.$conn->error); return null; }
    $stmt->bind_param('is', $memberId, $role);
    if (!$stmt->execute()) { error_log('get_first_approval_time exec failed: '.$stmt->error); $stmt->close(); return null; }
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $row['timestamp'] ?? null;
}

/** ===== Derive/Fix tarikh yang hilang ===== */
if (table_exists($conn,'approval_logs')) {
    if (empty($member['application_date']) && !empty($member['created_at'])) {
        $member['application_date'] = $member['created_at'];
    }
    if (empty($member['exco_approved_at']))  $member['exco_approved_at']  = get_first_approval_time($conn, (int)$member['id'], 'exco');
    if (empty($member['ajk_approved_at']))   $member['ajk_approved_at']   = get_first_approval_time($conn, (int)$member['id'], 'ajk');
    if (empty($member['admin_approved_at'])) $member['admin_approved_at'] = get_first_approval_time($conn, (int)$member['id'], 'admin');
    if (empty($member['official_member_since'])) {
        $first = !empty($member['ajk_approved_at']) ? $member['ajk_approved_at'] : ($member['admin_approved_at'] ?? null);
        if ($first) $member['official_member_since'] = date('Y-m-d', strtotime($first));
    }
}

/** ===== Job titles (user masih boleh update) ===== */
$jobTitles = [];
if (table_exists($conn,'job_titles')) {
  $jtCol = active_col($conn,'job_titles');
  $qJT = "SELECT name FROM job_titles";
  if ($jtCol) $qJT .= " WHERE COALESCE($jtCol,1)=1";
  $qJT .= " ORDER BY name ASC";
  if ($qTr = $conn->query($qJT)) while ($r = $qTr->fetch_assoc()) $jobTitles[] = $r['name'];
}

/** ===== Flash ===== */
$flash_success = isset($_GET['success']) ? trim($_GET['success']) : '';
$flash_error   = isset($_GET['error'])   ? trim($_GET['error'])   : '';
$pass_success  = isset($_GET['pass_success']) ? trim($_GET['pass_success']) : '';
$pass_error    = isset($_GET['pass_error'])   ? trim($_GET['pass_error'])   : '';

/** ===== UI ===== */
ob_start();
?>
<style>
  :root{
    --pri:#2563eb; --pri-ink:#1e40af;
    --bd:#e5e7eb; --ink:#0f172a; --muted:#64748b; --bg:#f6f7fb;
    --ok:#10b981; --danger:#ef4444; --warn:#f59e0b;
  }
  *{box-sizing:border-box}
  .page-wrap   { display:flex; flex-direction:column; gap:18px; }
  .card        { background:#fff; border:1px solid rgba(0,0,0,.06); border-radius:14px; padding:18px; box-shadow:0 8px 24px rgba(2,6,23,.08); }
  .card h2     { margin:0 0 14px; font-size:22px; }
  .card h3     { margin:0 0 12px; font-size:18px; }
  .grid-2      { display:grid; grid-template-columns: 1fr 1fr; gap:16px; }
  .full        { grid-column: 1 / -1; }
  label        { display:block; font-weight:600; margin-bottom:6px; }
  input[type="text"], input[type="email"], input[type="password"], select {
    width:100%; padding:10px 12px; border:1px solid #d1d5db; border-radius:10px; background:#fff;
  }
  input[disabled] { background:#f8fafc; color:#6b7280; }
  .btn          { padding:10px 14px; border:0; border-radius:10px; cursor:pointer; }
  .btn-primary  { background:#2563eb; color:#fff; }
  .btn-ghost    { background:#f3f4f6; color:#111827; }
  .badge        { display:inline-block; padding:4px 10px; border-radius:999px; font-size:12px; font-weight:600; border:1px solid transparent;}
  .badge-ok     { background:#ecfdf5; color:#065f46; border-color:#a7f3d0; }
  .badge-warn   { background:#fff7ed; color:#9a3412; border-color:#fed7aa; }
  .kv { display:flex; align-items:center; gap:8px; }
  .kv .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace; }
  .timeline { display:grid; grid-template-columns: 1fr 1fr; gap:12px; }
  .timeline .item { background:#f9fafb; border:1px solid #eef2f7; border-radius:10px; padding:10px 12px; }
  .timeline label { margin-bottom:4px; font-weight:600; }
  .helper { color:#6b7280; font-size:13px; }
  .copy-btn { padding:6px 8px; border-radius:8px; border:1px solid #e5e7eb; background:#fff; cursor:pointer; font-size:12px; }
  @media (max-width: 900px) { .grid-2, .timeline { grid-template-columns: 1fr; } }

  /* Flash styles */
  .flash{position:relative;margin:0 0 14px;padding:10px 12px;border-radius:10px;border:1px solid transparent}
  .flash.success{background:#ecfdf5;border-color:#bbf7d0;color:#065f46}
  .flash.error{background:#fef2f2;border-color:#fecaca;color:#991b1b}
  .flash .close{position:absolute;right:10px;top:8px;border:0;background:transparent;font-size:16px;cursor:pointer;color:inherit}

  /* Password meter (Change Password) */
  .pw-wrap { margin-top:6px; }
  .pw-meter { display:flex; gap:6px; margin:8px 0 6px 0; }
  .pw-meter span { flex:1; height:8px; border-radius:6px; background:#eee; transition:background .25s, transform .25s; }
  .pw-label { font-size:.9em; }
  .pw-req { margin-top:6px; font-size:.9em; color:#444; }
  .pw-req li { margin:3px 0; list-style: none; }
  .pw-req li::before { content:"• "; color:#888; }
  .pw-req li.ok { color:#0a7a20; }
  .pw-req li.ok::before { content:"✔ "; }
  .match { font-size:.9em; margin-top:6px; }
</style>

<div class="page-wrap">

  <?php if ($flash_success): ?>
    <div class="flash success" id="flashBox">
      <strong>Success:</strong> <span><?= htmlspecialchars($flash_success) ?></span>
      <button class="close" aria-label="Close" onclick="this.parentElement.remove()">×</button>
    </div>
  <?php elseif ($flash_error): ?>
    <div class="flash error" id="flashBox">
      <strong>Error:</strong> <span><?= htmlspecialchars($flash_error) ?></span>
      <button class="close" aria-label="Close" onclick="this.parentElement.remove()">×</button>
    </div>
  <?php endif; ?>

  <?php if ($pass_success): ?>
    <div class="flash success" id="flashBox2">
      <strong>Success:</strong> <span><?= htmlspecialchars($pass_success) ?></span>
      <button class="close" aria-label="Close" onclick="this.parentElement.remove()">×</button>
    </div>
  <?php elseif ($pass_error): ?>
    <div class="flash error" id="flashBox2">
      <strong>Error:</strong> <span><?= htmlspecialchars($pass_error) ?></span>
      <button class="close" aria-label="Close" onclick="this.parentElement.remove()">×</button>
    </div>
  <?php endif; ?>

  <div class="card">
    <h2>👤 My Profile</h2>

    <form method="post" action="profile-update.php" autocomplete="on" id="profileForm">
      <input type="hidden" name="id" value="<?= (int)$member['id'] ?>">
      <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($CSRF) ?>">

      <div class="grid-2">
        <div>
          <label>Full Name</label>
          <input type="text" name="full_name" value="<?= htmlspecialchars($member['full_name']) ?>" required maxlength="100" autocomplete="name">
        </div>

        <div>
          <label>No. Anggota (Staff Number)</label>
          <div class="kv">
            <input type="text" value="<?= htmlspecialchars($member['staff_number']) ?>" disabled class="mono" autocomplete="off">
            <button class="copy-btn" type="button" onclick="copyVal(this)">Copy</button>
          </div>
        </div>

        <div>
          <label>No. KP (IC Number)</label>
          <div class="kv">
            <input type="text" value="<?= htmlspecialchars($member['ic_number']) ?>" disabled class="mono" autocomplete="off">
            <button class="copy-btn" type="button" onclick="copyVal(this)">Copy</button>
          </div>
        </div>

        <div>
          <label>Email</label>
          <input type="email" name="email" value="<?= htmlspecialchars($member['email']) ?>" required maxlength="100" autocomplete="email">
        </div>

        <div>
          <label>No. Tel Bimbit (Phone)</label>
          <input
            type="text"
            name="phone"
            value="<?= htmlspecialchars($member['phone']) ?>"
            required
            maxlength="20"
            inputmode="tel"
            pattern="^[0-9+\-\s]{7,20}$"
            title="Hanya nombor / + / - / ruang (7–20 aksara)"
            autocomplete="tel"
            data-phonemask="my"
          >
        </div>

        <div>
          <label>No. Tel Kediaman</label>
          <input
            type="text"
            name="home_phone"
            value="<?= htmlspecialchars($member['home_phone'] ?? '') ?>"
            maxlength="20"
            inputmode="tel"
            pattern="^[0-9+\-\s]{7,20}$"
            title="Hanya nombor / + / - / ruang (7–20 aksara)"
            autocomplete="tel"
            data-phonemask="my"
          >
        </div>

        <div>
          <label>Bangsa (Race)</label>
          <select name="race" required>
            <option value="">-- Select Race --</option>
            <?php foreach (['Malay','Chinese','Indian','Bumiputera','Others'] as $r): ?>
              <option value="<?= htmlspecialchars($r,ENT_QUOTES) ?>" <?= ($member['race'] === $r) ? 'selected' : '' ?>><?= htmlspecialchars($r) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div>
          <label>Jawatan (Job Title)</label>
          <?php if (!empty($jobTitles)): ?>
            <select name="job_title" required>
              <option value="">-- Sila Pilih Jawatan --</option>
              <?php foreach ($jobTitles as $jt): ?>
                <option value="<?= htmlspecialchars($jt) ?>" <?= ($member['job_title'] === $jt) ? 'selected' : '' ?>>
                  <?= htmlspecialchars($jt) ?>
                </option>
              <?php endforeach; ?>
            </select>
            <div class="helper">Jika tiada dalam senarai, sila hubungi Admin untuk pengemaskinian.</div>
          <?php else: ?>
            <input type="text" name="job_title" value="<?= htmlspecialchars($member['job_title'] ?? '') ?>" required maxlength="100">
          <?php endif; ?>
        </div>

        <div class="full">
          <label>Alamat Kediaman</label>
          <input type="text" name="address" value="<?= htmlspecialchars($member['address'] ?? '') ?>" required maxlength="255" autocomplete="street-address">
        </div>

        <div>
          <label>Poskod</label>
          <input type="text" name="postcode" value="<?= htmlspecialchars($member['postcode'] ?? '') ?>"
                 required maxlength="10" pattern="^\d{5}$" title="Masukkan poskod 5 digit">
        </div>

        <!-- ====== PAPAR SAHAJA (user tak boleh ubah) ====== -->
        <?php
          // Kira display string yang robust sebelum HTML
          $displayDistrict = '-';
          $displayWorkloc  = '-';

          // District: jika model baharu ada → guna nama district; kalau tiada, fallback ke legacy 'location'
          if ($has_tbl_districts && $has_district_id) {
            $displayDistrict = trim((string)($member['district_name'] ?? '')) ?: '-';
          } else {
            if ($has_location_str) $displayDistrict = trim((string)($member['location'] ?? '')) ?: '-';
          }

          // Work Location: jika model baharu ada → guna nama work location;
          // jika tiada jadual/kolum baharu → fallback ke legacy 'location' supaya tetap ada paparan
          if ($has_tbl_worklocs && $has_workloc_id) {
            $displayWorkloc = trim((string)($member['work_location_name'] ?? '')) ?: '-';
          } else {
            if ($has_location_str) $displayWorkloc = trim((string)($member['location'] ?? '')) ?: '-';
          }
        ?>

        <div>
          <label>Work District</label>
          <input type="text" value="<?= htmlspecialchars($displayDistrict) ?>" disabled>
          <div class="helper">Perubahan hanya boleh dibuat oleh Admin.</div>
        </div>

        <div>
          <label>Work Location</label>
          <input type="text" value="<?= htmlspecialchars($displayWorkloc) ?>" disabled>
          <div class="helper">Perubahan hanya boleh dibuat oleh Admin.</div>
        </div>
        <!-- ================================================ -->

      </div>

      <!-- Maklumat Keahlian -->
      <div style="margin-top: 18px;">
        <h3>Maklumat Keahlian</h3>
        <div class="timeline">
          <div class="item"><label>Tarikh Permohonan</label><div><?= fmtDT($member['application_date'], 'd/m/Y H:i') ?></div></div>
          <div class="item"><label>Kelulusan EXCO</label><div><?= fmtDT($member['exco_approved_at'], 'd/m/Y H:i') ?></div></div>
          <div class="item"><label>Kelulusan AJK</label><div><?= fmtDT($member['ajk_approved_at'], 'd/m/Y H:i') ?></div></div>
          <div class="item"><label>Kelulusan Admin</label><div><?= fmtDT($member['admin_approved_at'], 'd/m/Y H:i') ?></div></div>
          <div class="item"><label>Ahli Rasmi Sejak</label><div><?= fmtDT($member['official_member_since'], 'd/m/Y') ?></div></div>
        </div>
        <p class="helper" style="margin-top:8px;"><em>Makluman: Tarikh ahli rasmi mengambil kira kelulusan AJK (atau Admin jika AJK tiada). Yuran keahlian akan mula ditolak pada hujung bulan berikutnya.</em></p>

        <?php if (!empty($member['ack_form'])): ?>
          <p style="margin-top:8px;">
            <span class="badge badge-ok">ACK Form Available</span>
            <a class="btn-ghost" style="margin-left:8px; padding:6px 10px; display:inline-block; border:1px solid #e5e7eb; border-radius:8px;"
               href="generate_form.php?user_id=<?= (int)$member['id'] ?>" target="_blank" rel="noopener">
               📄 Muat Turun Borang Pengesahan Penolakan Gaji
            </a>
          </p>
        <?php else: ?>
          <p class="helper" style="margin-top:8px;">
            <span class="badge badge-warn">Tiada ACK Form</span>
          </p>
        <?php endif; ?>
      </div>

      <!-- Maklumat Waris -->
      <div style="margin-top: 18px;">
        <h3>Maklumat Waris</h3>
        <div class="grid-2">
          <div>
            <label>Nama Waris</label>
            <input type="text" name="waris_name" value="<?= htmlspecialchars($member['waris_name'] ?? '') ?>" maxlength="150" autocomplete="name">
          </div>
          <div>
            <label>No. Telefon Waris</label>
            <input
              type="text"
              name="waris_phone"
              value="<?= htmlspecialchars($member['waris_phone'] ?? '') ?>"
              maxlength="30"
              pattern="^[0-9+\-\s]{7,20}$"
              title="Hanya nombor / + / - / ruang (7–20 aksara)"
              autocomplete="tel"
              data-phonemask="my"
            >
          </div>
        </div>
      </div>

      <div style="margin-top: 22px;">
        <button type="submit" class="btn btn-primary">Update Profile</button>
      </div>
    </form>
  </div>

  <div class="card">
    <h2>🔒 Change Password</h2>
    <form method="post" action="change-password.php" onsubmit="return confirm('Are you sure you want to change your password?');" autocomplete="off">
      <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($CSRF) ?>">

      <div class="grid-2">
        <div class="full">
          <label>Old Password</label>
          <div class="kv">
            <input type="password" name="old_password" required autocomplete="current-password">
            <button class="copy-btn" type="button" onclick="togglePwd(this)">Show</button>
          </div>
        </div>
        <div>
          <label>New Password</label>
          <div class="kv">
            <input type="password" name="new_password" id="new_password" required autocomplete="new-password">
            <button class="copy-btn" type="button" onclick="togglePwd(this)">Show</button>
          </div>

          <!-- Password meter ringkas -->
          <div class="pw-wrap" id="pw_help">
            <div class="pw-meter" aria-hidden="true" id="npw_meter">
              <span></span><span></span><span></span><span></span><span></span>
            </div>
            <div class="pw-label" id="npw_strength_label">Sangat Lemah</div>
            <ul class="pw-req" aria-live="polite">
              <li id="npw_len8">Sekurang-kurangnya 8 aksara</li>
              <li id="npw_mixcase">Gabungan huruf besar & kecil</li>
              <li id="npw_digit">Mengandungi nombor</li>
              <li id="npw_special">Mengandungi simbol</li>
              <li id="npw_personal">Tidak mengandungi nama/emel/no. anggota/no. KP</li>
              <li id="npw_seq">Tiada jujukan mudah (cth: 1234, abcd, qwer)</li>
            </ul>
          </div>
        </div>
        <div>
          <label>Confirm Password</label>
          <div class="kv">
            <input type="password" name="confirm_password" id="confirm_password" required autocomplete="new-password">
            <button class="copy-btn" type="button" onclick="togglePwd(this)">Show</button>
          </div>
          <div id="npw_match_msg" class="match"></div>
        </div>
      </div>

      <div style="margin-top: 22px;">
        <button type="submit" class="btn btn-primary">Change Password</button>
      </div>
    </form>
  </div>

</div>

<script>
function copyVal(btn){
  const input = btn.parentElement.querySelector('input');
  if (!input) return;
  navigator.clipboard.writeText(input.value).then(()=>{
    const old = btn.textContent;
    btn.textContent = 'Copied!';
    setTimeout(()=>btn.textContent=old, 1000);
  });
}
function togglePwd(btn){
  const input = btn.parentElement.querySelector('input');
  if (!input) return;
  if (input.type === 'password') { input.type = 'text'; btn.textContent = 'Hide'; }
  else { input.type = 'password'; btn.textContent = 'Show'; }
}

// Auto-hide flash
(function(){
  const boxes = [document.getElementById('flashBox'), document.getElementById('flashBox2')].filter(Boolean);
  if (boxes.length) { window.scrollTo({top:0,behavior:'smooth'}); }
  boxes.forEach((fb)=>{
    setTimeout(()=>{ if(fb){ fb.style.transition='opacity .4s'; fb.style.opacity='0'; setTimeout(()=>fb.remove(), 400); } }, 4000);
  });
})();

/* ========= MALAYSIA PHONE AUTO-MASK ========= */
function formatMYPhone(raw){
  if (!raw) return '';
  raw = String(raw).replace(/\s+/g,'');
  const hasPlus = raw[0] === '+';
  let digits = raw.replace(/[^\d]/g, '');
  if (hasPlus) {
    if (digits.startsWith('60')) {
      digits = digits.slice(2);
      return '+60 ' + localFormat(digits);
    }
    return '+' + genericFormat(digits);
  }
  return localFormat(digits);
}
function localFormat(d){
  if (!d) return '';
  if (d.startsWith('01')) {
    if (d.length >= 11) {
      const a = d.slice(0,3), b = d.slice(3,7), c = d.slice(7,11);
      return [a,b,c].filter(Boolean).join('-');
    } else if (d.length >= 10) {
      const a = d.slice(0,3), b = d.slice(3,6), c = d.slice(6,10);
      return [a,b,c].filter(Boolean).join('-');
    } else if (d.length > 3) {
      const a = d.slice(0,3), rest = d.slice(3);
      return a + '-' + chunk(rest);
    }
    return d;
  }
  if (/^0[3-9]/.test(d)) {
    const a = d.slice(0,2), rest = d.slice(2);
    if (rest.length >= 8)      return a + '-' + rest.slice(0,4) + ' ' + rest.slice(4,8);
    else if (rest.length >= 7) return a + '-' + rest.slice(0,3) + ' ' + rest.slice(3,7);
    else if (rest.length > 0)  return a + '-' + rest;
    return a;
  }
  return genericFormat(d);
}
function genericFormat(d){
  if (d.length >= 10) return d.slice(0,3) + '-' + d.slice(3,6) + '-' + d.slice(6,10);
  else if (d.length > 6) return d.slice(0,3) + '-' + d.slice(3,6) + '-' + d.slice(6);
  else if (d.length > 3) return d.slice(0,3) + '-' + d.slice(3);
  return d;
}
function chunk(s){
  if (s.length >= 7) return s.slice(0,4) + ' ' + s.slice(4,8);
  if (s.length >= 4) return s.slice(0,3) + ' ' + s.slice(3,7);
  return s;
}
function attachPhoneMask(el){
  if (!el) return;
  const handle = ()=>{
    const before = el.value;
    el.value = formatMYPhone(before);
    try { el.setSelectionRange(el.value.length, el.value.length); } catch(e){}
  };
  el.addEventListener('input', handle);
  el.addEventListener('keyup', handle);
  el.addEventListener('paste', ()=>{ setTimeout(handle, 0); });
  el.value = formatMYPhone(el.value);
}
document.querySelectorAll('input[data-phonemask="my"]').forEach(attachPhoneMask);

/* ========= PASSWORD METER (Change Password) ========= */
function sanitizeStr(s){ return String(s||'').toLowerCase().replace(/[^a-z0-9]/g,''); }
function hasSeq(pw){
  const s = String(pw||'').toLowerCase();
  const rows = ["qwertyuiop","asdfghjkl","zxcvbnm"];
  const alpha = "abcdefghijklmnopqrstuvwxyz", num = "0123456789";
  const pools = [alpha, num, ...rows];
  for (const pool of pools){
    for (let i=0;i<=pool.length-4;i++){
      const seg = pool.slice(i,i+4);
      if (s.includes(seg) || s.includes([...seg].reverse().join(''))) return true;
    }
  }
  return false;
}
function evalPassword(pw, ctx){
  const length=pw.length, hasLower=/[a-z]/.test(pw), hasUpper=/[A-Z]/.test(pw), hasDigit=/\d/.test(pw), hasSpecial=/[\W_]/.test(pw);
  const uniqueChars=new Set(pw).size;
  const personal=[ctx.name, ctx.email, ctx.staff, (ctx.ic||'').replace(/\D/g,'')].filter(Boolean).map(sanitizeStr);
  const pwSan=sanitizeStr(pw);
  const containsPersonal=personal.some(p=>p.length>=4 && pwSan.includes(p));
  const repetitive=/(.)\1{2,}/.test(pw);
  const sequential=hasSeq(pw);

  let score=0;
  if (length>=8) score++;
  if (length>=12) score++;
  if (hasLower && hasUpper) score++;
  if (hasDigit) score++;
  if (hasSpecial) score++;
  if (uniqueChars>=Math.min(8,length)) score++;

  if (repetitive) score--;
  if (sequential) score--;
  if (containsPersonal) score-=2;

  score=Math.max(0, Math.min(5, score));
  return {score, checks:{length8:length>=8, lower:hasLower, upper:hasUpper, digit:hasDigit, special:hasSpecial, noPersonal:!containsPersonal, noSeq:!sequential}};
}
function paintMeter(score){
  const bars=document.querySelectorAll('#npw_meter span');
  bars.forEach((b,i)=>{
    if (i < score){
      const colors=['#e74c3c','#f39c12','#d4ac0d','#2ecc71','#17a589'];
      b.style.background=colors[Math.min(score-1,colors.length-1)];
      b.style.transform='scaleY(1.15)';
    } else {
      b.style.background='#eee';
      b.style.transform='scaleY(1)';
    }
  });
  const label=document.getElementById('npw_strength_label');
  const texts=['Sangat Lemah','Lemah','Sederhana','Kuat','Sangat Kuat','Sangat Kuat'];
  label.textContent=texts[Math.min(score,5)];
  label.style.color=(score<=1)?'#e74c3c':(score===2?'#f39c12':(score===3?'#27ae60':'#148f77'));
}
function updateChecklist(checks){
  const map={ npw_len8:checks.length8, npw_mixcase:(checks.lower && checks.upper), npw_digit:checks.digit, npw_special:checks.special, npw_personal:checks.noPersonal, npw_seq:checks.noSeq };
  Object.entries(map).forEach(([id,ok])=>{ const li=document.getElementById(id); if(li) li.classList.toggle('ok', !!ok); });
}
function setPasswordValidity(pw, checks){
  const el=document.getElementById('new_password');
  let msg='';
  if (!checks.length8) msg='Kata laluan mesti sekurang-kurangnya 8 aksara.';
  else if (!(checks.lower && checks.upper)) msg='Gabungan huruf besar & kecil diperlukan.';
  else if (!checks.digit) msg='Mesti mengandungi sekurang-kurangnya 1 nombor.';
  else if (!checks.special) msg='Mesti mengandungi sekurang-kurangnya 1 simbol.';
  else if (!checks.noPersonal) msg='Jangan guna nama, emel, no. anggota atau no. KP.';
  el.setCustomValidity(msg);
}
function checkConfirmMatch(){
  const p1=document.getElementById('new_password')?.value||'';
  const p2=document.getElementById('confirm_password')?.value||'';
  const m=document.getElementById('npw_match_msg');
  if (!m) return;
  if (!p2){ m.textContent=''; return; }
  if (p1===p2){ m.textContent='✔ Kata laluan sepadan'; m.style.color='#1e7e34'; }
  else { m.textContent='✖ Kata laluan tidak sepadan'; m.style.color='#e74c3c'; }
}
(function(){
  const ctx = <?=
    json_encode([
      'name'  => (string)($member['full_name'] ?? ''),
      'email' => (string)($member['email'] ?? ''),
      'staff' => (string)($member['staff_number'] ?? ''),
      'ic'    => (string)($member['ic_number'] ?? ''),
    ], JSON_UNESCAPED_UNICODE)
  ?>;

  const npw=document.getElementById('new_password');
  const cpw=document.getElementById('confirm_password');

  function onNPWInput(){
    // Sync jika user tukar nama/emel atas
    const nEl=document.querySelector('input[name="full_name"]'); if (nEl) ctx.name=nEl.value;
    const eEl=document.querySelector('input[name="email"]');     if (eEl) ctx.email=eEl.value;

    const res=evalPassword(npw.value, ctx);
    paintMeter(res.score);
    updateChecklist(res.checks);
    setPasswordValidity(npw.value, res.checks);
    checkConfirmMatch();
  }

  npw && npw.addEventListener('input', onNPWInput);
  cpw && cpw.addEventListener('input', checkConfirmMatch);

  // Boot sekali supaya bar bergerak jika browser auto-fill
  if (npw) onNPWInput();
})();
</script>

<?php
$content = ob_get_clean();
include 'layout.php';
