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

/* ============================================================
 * FIX: Bila user buka borang (GET), bersihkan pending_id lama
 * supaya aliran draf/ack baharu tidak terbaca rekod lama.
 * ============================================================ */
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    unset($_SESSION['pending_id']);
}

/**
 * ===========================
 *  Inline AJAX endpoints
 *  — EXCO ikut district (1 aktif / district)
 *  — EXCO (Penyokong) GLOBAL (semua EXCO aktif)
 *  — Duplicate checks (staff/email/ic)
 *  — Response pulangkan {id, name, ...} bila perlu
 * ===========================
 */
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json; charset=utf-8');
    $ajax = $_GET['ajax'];

    // ====== Locations ikut district (kekal) ======
    if ($ajax === 'locations') {
        $district_id = (int)($_GET['district_id'] ?? 0);
        $stmt = $conn->prepare("SELECT id, name FROM locations WHERE active=1 AND district_id=? ORDER BY name ASC");
        $stmt && $stmt->bind_param('i', $district_id);
        $rows = [];
        if ($stmt && $stmt->execute()) {
            $res = $stmt->get_result();
            while ($r = $res->fetch_assoc()) $rows[] = $r;
            $stmt->close();
        }
        echo json_encode($rows, JSON_UNESCAPED_UNICODE);
        exit;
    }

    // ====== Approvers: EXCO by district, EXCO (Penyokong) GLOBAL ======
    if ($ajax === 'approvers') {
        $district_id = (int)($_GET['district_id'] ?? 0);
        $data = ['exco'=>[], 'ajk'=>[]]; // NOTE: 'ajk' dikekalkan utk kompat, tapi memuat EXCO (Penyokong)

        // EXCO — maksimum 1 ikut district (Pencadang)
        if ($district_id > 0) {
            $stmt = $conn->prepare("SELECT id, full_name FROM members WHERE role='exco' AND district_id=? AND COALESCE(status,1)=1 LIMIT 1");
            if ($stmt) {
                $stmt->bind_param('i', $district_id);
                if ($stmt->execute()) {
                    $res = $stmt->get_result();
                    if ($row = $res->fetch_assoc()) {
                        $data['exco'][] = ['id' => (int)$row['id'], 'name' => $row['full_name']];
                    }
                }
                $stmt->close();
            }
        }

        // EXCO (Penyokong) — GLOBAL
        $sql = "SELECT m.id, m.full_name, COALESCE(d.name,'-') AS district_name
                FROM members m
                LEFT JOIN districts d ON d.id = m.district_id
                WHERE m.role='exco' AND COALESCE(m.status,1)=1
                ORDER BY m.full_name ASC";
        if ($rs = $conn->query($sql)) {
            while ($r = $rs->fetch_assoc()) {
                $data['ajk'][] = [
                    'id'            => (int)$r['id'],
                    'name'          => $r['full_name'],
                    'district_name' => $r['district_name'],
                ];
            }
        }

        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }

    // ====== Duplicate checks: staff / email / ic ======
    if ($ajax === 'check') {
        $field = strtolower(trim($_GET['field'] ?? ''));
        $value = trim((string)($_GET['value'] ?? ''));

        // Normalize
        if ($field === 'email') {
            $value = strtolower($value);
        } elseif ($field === 'staff') {
            $value = strtoupper(preg_replace('/\s+/', '', $value));
        } elseif ($field === 'ic') {
            $d = preg_replace('/\D/', '', $value);
            if (strlen($d) === 12) {
                $value = substr($d,0,6) . '-' . substr($d,6,2) . '-' . substr($d,8,4);
            }
        }

        $map = [
            'staff' => ['col' => 'staff_number'],
            'email' => ['col' => 'email'],
            'ic'    => ['col' => 'ic_number'],
        ];
        if (!isset($map[$field]) || $value === '') {
            echo json_encode(['exists'=>false,'where'=>[]]); exit;
        }

        $col = $map[$field]['col'];
        $tables = ['members', 'pending_exco', 'pending_ajk'];
        $where = [];

        foreach ($tables as $t) {
            $sql = "SELECT id FROM `$t` WHERE $col = ? LIMIT 1";
            $st = $conn->prepare($sql);
            if ($st) {
                $st->bind_param('s', $value);
                if ($st->execute()) {
                    $st->store_result();
                    if ($st->num_rows > 0) $where[] = $t;
                }
                $st->close();
            }
        }

        echo json_encode(['exists'=> !empty($where), 'where' => $where], JSON_UNESCAPED_UNICODE);
        exit;
    }

    echo json_encode(['error'=>'unknown ajax'], JSON_UNESCAPED_UNICODE);
    exit;
}

/**
 * Flash handler (PRG + SweetAlert2)
 */
if (isset($_GET['error']) || isset($_GET['success'])) {
    $raw = trim((string)($_GET['error'] ?? $_GET['success'] ?? ''));

    $allowed = [
        'Staff number or email already exists.' => [
            'type'=>'error','message'=>'Staff number or email already exists.','focus'=>'staff_number','highlight'=>['staff_number','email']
        ],
        'Please fill in all required fields.'   => [
            'type'=>'error','message'=>'Please fill in all required fields.','focus'=>'','highlight'=>[], 'code'=>'required'
        ],
        'Invalid file content.'                 => [
            'type'=>'error','message'=>'Invalid file content.','focus'=>'receipt','highlight'=>['receipt']
        ],
        'Registration successful.'              => [
            'type'=>'success','message'=>'Registration successful.','focus'=>'','highlight'=>[]
        ],
    ];

    $cfg = $allowed[$raw] ?? (isset($_GET['error'])
        ? ['type'=>'error','message'=>'An error occurred.','focus'=>'','highlight'=>[]]
        : ['type'=>'success','message'=>'Success.','focus'=>'','highlight'=>[]]);

    $_SESSION['flash'] = $cfg;
    header("Location: register.php");
    exit;
}

// Flash sekali guna
$flash = $_SESSION['flash'] ?? null;
if ($flash) unset($_SESSION['flash']);

/**
 * Old form values (untuk repopulate)
 * - Di-set oleh register-process.php bila error
 */
$old = $_SESSION['old'] ?? [];
if ($old) unset($_SESSION['old']);

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

/**
 * Data sources — DISTRICT → LOCATIONS (kekal)
 */

// Dapatkan districts aktif
$districts = [];
$dq = $conn->query("SELECT id, name FROM districts WHERE is_active=1 ORDER BY name ASC");
while ($row = $dq->fetch_assoc()) $districts[] = $row;

// Jika ada old[district_id], pre-load lokasi untuk dropdown
$prefillLocations = [];
$oldDistrictId = isset($old['district_id']) ? (int)$old['district_id'] : 0;
if ($oldDistrictId) {
    $stmt = $conn->prepare("SELECT id, name FROM locations WHERE active=1 AND district_id=? ORDER BY name ASC");
    $stmt && $stmt->bind_param('i', $oldDistrictId);
    if ($stmt && $stmt->execute()) {
        $res = $stmt->get_result();
        while ($r = $res->fetch_assoc()) $prefillLocations[] = $r;
        $stmt->close();
    }
}

/**
 * Approvers prefill
 * - EXCO ikut district lama (jika ada)
 * - EXCO (Penyokong) GLOBAL
 */
$prefillExcoText = '';
$prefillExcoId   = 0;
$prefillAjkRows  = []; // senarai EXCO (Penyokong)
$prefillAjkSelectedId = 0;

if ($oldDistrictId) {
    $stmt = $conn->prepare("SELECT id, full_name FROM members WHERE role='exco' AND district_id=? AND COALESCE(status,1)=1 LIMIT 1");
    if ($stmt) {
        $stmt->bind_param('i', $oldDistrictId);
        if ($stmt->execute()) {
            $res = $stmt->get_result();
            if ($row = $res->fetch_assoc()) { $prefillExcoText = $row['full_name']; $prefillExcoId = (int)$row['id']; }
        }
        $stmt->close();
    }
}
// EXCO (Penyokong) GLOBAL
$sqlAjk = "SELECT m.id, m.full_name, COALESCE(d.name,'-') AS district_name
           FROM members m
           LEFT JOIN districts d ON d.id=m.district_id
           WHERE m.role='exco' AND COALESCE(m.status,1)=1
           ORDER BY m.full_name ASC";
if ($rs = $conn->query($sqlAjk)) {
    while ($r = $rs->fetch_assoc()) {
        $prefillAjkRows[] = ['id'=>(int)$r['id'],'name'=>$r['full_name'],'district_name'=>$r['district_name']];
        if (!empty($old['exco_select']) && $old['exco_select']===$r['full_name']) {
            $prefillAjkSelectedId = (int)$r['id'];
        }
    }
}

// Payment
$pay = null;
$pq = $conn->query("SELECT bank_name, account_number, account_name, note, qr_image_path
                    FROM payment_settings WHERE active=1 ORDER BY updated_at DESC LIMIT 1");
if ($pq && $pq->num_rows) { $pay = $pq->fetch_assoc(); }

/* =========================
 * Draf: resit sedia ada?
 * ========================= */
$draftReceipt = null;
$lookupEmail = $old['email'] ?? ($_SESSION['draft_email'] ?? '');
$lookupStaff = $old['staff_number'] ?? ($_SESSION['draft_staff'] ?? '');
if ($lookupEmail || $lookupStaff) {
    $stmt = $conn->prepare("SELECT receipt FROM temp_register WHERE email=? OR staff_number=? ORDER BY id DESC LIMIT 1");
    if ($stmt) {
        $stmt->bind_param("ss", $lookupEmail, $lookupStaff);
        if ($stmt->execute()) {
            $stmt->bind_result($receiptPath);
            if ($stmt->fetch()) $draftReceipt = $receiptPath ?: null;
        }
        $stmt->close();
    }
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8" />
    <title>Register - KPPRSAJ</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        *, *::before, *::after { box-sizing: border-box; }
        body {
            font-family: Arial, sans-serif;
            background: linear-gradient(rgba(0,0,0,0.6), rgba(0,0,0,0.6)),
                        url('assets/img/background.jpg') no-repeat center center fixed;
            background-size: cover;
            display: flex; justify-content: center; align-items: flex-start;
            padding-top: 50px; min-height: 100vh;
        }
        .form-box { background:#fff; padding:30px; border-radius:10px;
            box-shadow:0 4px 12px rgba(0,0,0,0.1); width:100%; max-width:760px; }
        h2 { text-align:center; margin-top:0; }
        form > div { margin-bottom:15px; }
        label { display:block; font-weight:bold; margin-bottom:6px; }
        input, select, textarea {
            display:block; width:100%; max-width:100%; padding:8px 10px;
            border-radius:6px; border:1px solid #ccc; background:#fff; transition: border-color .2s, box-shadow .2s;
        }
        textarea { min-height:90px; resize:vertical; }
        button { width:100%; padding:10px 12px; background:#007bff; color:#fff; border:0; border-radius:8px; cursor:pointer; font-weight:600; }
        .back-btn { display:block; margin-top:20px; text-align:center; }
        .back-btn a { color:#007bff; text-decoration:none; }
        .back-btn a:hover { text-decoration:underline; }
        .info { font-size:0.9em; color:#d33; margin-top:3px; }
        .ok { color:#0a7a20 !important; }
        .toggle-pass { margin-top:5px; font-size:0.9em; color:#007bff; cursor:pointer; }
        small { font-weight:bold; }

        .section { border:1px solid #e5e7eb; border-radius:10px; padding:14px; background:#fafafa; }
        .section h3 { margin:0 0 8px; font-size:1.05rem; }
        .grid-2 { display:grid; grid-template-columns:repeat(2, minmax(0, 1fr)); gap:12px; }
        .grid-2 > * { min-width:0; }
        @media (max-width:640px) { .grid-2 { grid-template-columns:1fr; } }

        .field-error{ border-color:#e11d48 !important; box-shadow:0 0 0 3px rgba(225,29,72,.15); }

        .pay-card{display:grid; grid-template-columns:120px 1fr; gap:14px; align-items:start}
        .pay-card .qr img{max-width:120px;border:1px solid #eee;border-radius:10px; cursor: zoom-in;}
        @media (max-width:640px){ .pay-card{grid-template-columns:1fr} .pay-card .qr{margin-bottom:8px} }
        .muted{color:#666;font-size:.92em}
        .callout{background:#f1f8ff;border:1px solid #d6e9ff;padding:10px 12px;border-radius:10px;color:#0b5394}

        #preview { margin-top:8px; }
        .preview-img { max-width:240px; border:1px solid #e5e7eb; border-radius:8px; padding:4px; background:#fff; }
        .pdf-pill { display:inline-block; padding:6px 10px; border-radius:999px; border:1px solid #e5e7eb; background:#fff; font-size:12px; }
        .tip { font-size:12px; color:#555; }

        .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>

    <script>
        // ====== AUTO-FORMAT: IC & PHONE ======
        function digitsOnly(s){ return String(s||'').replace(/\D/g,''); }

        function formatICInput(el){
            let d = digitsOnly(el.value).slice(0,12);
            if (d.length > 6) d = d.slice(0,6) + '-' + d.slice(6);
            if (d.length > 9) d = d.slice(0,9) + '-' + d.slice(9);
            el.value = d;
        }

        function formatMobileInput(el){
            let d = digitsOnly(el.value).slice(0,11);
            if (d.startsWith('011')) {
                if (d.length > 3) d = d.slice(0,3) + '-' + d.slice(3);
                if (d.length > 8) d = d.slice(0,8) + '-' + d.slice(8);
            } else {
                if (d.length > 3) d = d.slice(0,3) + '-' + d.slice(3);
            }
            el.value = d;
        }

        function formatHomeInput(el){
            let d = digitsOnly(el.value).slice(0,12);
            if (d.startsWith('03')) {
                if (d.length > 2) d = d.slice(0,2) + '-' + d.slice(2);
            } else if (d.startsWith('0')) {
                if (d.length > 3) d = d.slice(0,3) + '-' + d.slice(3);
            }
            el.value = d;
        }

        function attachFormatter(id, fn){
            const el = document.getElementById(id);
            if (!el) return;
            const handler = ()=> fn(el);
            el.addEventListener('input', handler);
            el.addEventListener('paste', e => { setTimeout(handler, 0); });
            fn(el);
        }

        // ====== Password helpers ======
        function sanitizeStr(s){ return String(s||'').toLowerCase().replace(/[^a-z0-9]/g,''); }
        function hasSeq(pw){
            const s = pw.toLowerCase();
            const pools = ["abcdefghijklmnopqrstuvwxyz","0123456789","qwertyuiop","asdfghjkl","zxcvbnm"];
            for (const pool of pools) {
                for (let i=0;i<=pool.length-4;i++){
                    const t = pool.slice(i,i+4);
                    if (s.includes(t) || s.includes([...t].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),
                  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), 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,length12:length>=12,lower:hasLower,upper:hasUpper,digit:hasDigit,special:hasSpecial,noPersonal:!containsPersonal,noSeq:!sequential,noRepeat:!repetitive}};
        }
        function paintMeter(score){
            const bars=document.querySelectorAll('.pw-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('pw_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={'req_len8':checks.length8,'req_mixcase':(checks.lower&&checks.upper),'req_digit':checks.digit,'req_special':checks.special,'req_personal':checks.noPersonal,'req_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('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 dalam kata laluan.';
            el.setCustomValidity(msg);
        }
        function checkConfirmMatch(){
            const p1=document.getElementById('password').value;
            const p2=document.getElementById('confirm_password').value;
            const m=document.getElementById('match_msg');
            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'; }
        }

        // ====== Upload resit preview ======
        const MAX_MB=5;
        function bytes(size){ return (size/1024/1024).toFixed(2)+' MB'; }
        function isAllowed(name,type){
            const okExt=['pdf','jpeg','jpg','png']; const ext=(name.split('.').pop()||'').toLowerCase();
            if(!okExt.includes(ext)) return false;
            const okMime=['application/pdf','image/jpeg','image/png'];
            return !type || okMime.includes(type) || (ext==='jpg' && type==='image/jpg');
        }
        function previewFile(){
            const input=document.getElementById('receipt'); const pv=document.getElementById('preview'); pv.innerHTML='';
            if(!input.files || !input.files.length) return;
            const f=input.files[0];
            if(f.size > (MAX_MB*1024*1024)){ input.value=''; pv.innerHTML='<div class="info">Fail melebihi '+MAX_MB+'MB ('+bytes(f.size)+'). Sila pilih fail lain.</div>'; return; }
            if(!isAllowed(f.name,f.type)){ input.value=''; pv.innerHTML='<div class="info">Jenis fail tidak dibenarkan. Hanya PDF/JPEG/PNG.</div>'; return; }
            const ext=(f.name.split('.').pop()||'').toLowerCase();
            if(ext==='pdf'){ pv.innerHTML='<span class="pdf-pill">📄 '+f.name+' ('+bytes(f.size)+')</span>'; }
            else{
                const img=document.createElement('img');
                img.className='preview-img'; img.alt='Preview Resit';
                img.onload=()=>URL.revokeObjectURL(img.src);
                img.src=URL.createObjectURL(f);
                pv.appendChild(img);
                const cap=document.createElement('div'); cap.className='tip'; cap.textContent=f.name+' ('+bytes(f.size)+')';
                pv.appendChild(cap);
            }
        }

        // ====== UX helpers ======
        function highlightOnce(el){ if(!el) return; el.classList.add('field-error'); ['input','change','blur'].forEach(evt=>{ el.addEventListener(evt, ()=> el.classList.remove('field-error'), { once:true }); }); }
        function firstRequiredInvalid(){
            const form=document.querySelector('form'); if(!form) return null;
            let el=form.querySelector('[required]:invalid'); if(el) return el;
            const reqs=Array.from(form.querySelectorAll('[required]'));
            el=reqs.find(e=>{ if(e.type==='file') return !(e.files && e.files.length); return !(String(e.value||'').trim()); });
            return el||null;
        }
        function smoothFocus(el){ if(!el) return; el.scrollIntoView({behavior:'smooth', block:'center'}); setTimeout(()=>{ try{ el.focus({preventScroll:true}); }catch(e){ el.focus(); } }, 350); }

        // ====== Debounce util ======
        function debounce(fn, wait){ let t; return function(...args){ clearTimeout(t); t=setTimeout(()=>fn.apply(this,args), wait); } }

        // ====== Duplicate check (AJAX) ======
        const dupFlags = { staff:false, ic:false, email:false };
        function setMsg(id, ok, textOK, textErr){
            const el = document.getElementById(id);
            if (!el) return;
            el.textContent = ok ? textOK : textErr;
            el.classList.toggle('ok', ok);
            el.classList.toggle('info', !ok);
        }
        function callCheck(field, value, cb){
            $.getJSON('register.php', {ajax:'check', field, value}, function(res){
                cb && cb(res && res.exists===true, res && res.where ? res.where : []);
            }).fail(()=> cb && cb(false, []));
        }

        const validateStaff = debounce(function(el){
            const raw = (el && el.value) ? el.value : '';
            const norm = String(raw).replace(/\s+/g,'').toUpperCase();
            if (!norm || norm.length < 5) { dupFlags.staff=false; setMsg('staff_msg', true, '', ''); return; }
            callCheck('staff', norm, function(exists){
                dupFlags.staff = !!exists;
                if (exists) setMsg('staff_msg', false, '', 'No. Anggota sudah wujud dalam sistem.');
                else        setMsg('staff_msg', true, 'No. Anggota tersedia ✔', '');
            });
        }, 300);

        const validateIC = debounce(function(el){
            const raw = (el && el.value) ? el.value : '';
            const d = (raw||'').replace(/\D/g,'');
            if (d.length !== 12) { dupFlags.ic=false; setMsg('ic_msg','', '',''); return; }
            callCheck('ic', raw, function(exists){
                dupFlags.ic = !!exists;
                if (exists) setMsg('ic_msg', false, '', 'No. KP sudah wujud dalam sistem.');
                else        setMsg('ic_msg', true, 'No. KP tersedia ✔', '');
            });
        }, 300);

        const validateEmail = debounce(function(el){
            const raw = (el && el.value) ? el.value : '';
            if (!raw || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(raw)) { dupFlags.email=false; setMsg('email_msg','', '',''); return; }
            callCheck('email', raw, function(exists){
                dupFlags.email = !!exists;
                if (exists) setMsg('email_msg', false, '', 'Emel sudah wujud dalam sistem.');
                else        setMsg('email_msg', true, 'Emel tersedia ✔', '');
            });
        }, 300);

        // ==== District -> Locations & Approvers ====
        function loadLocations(districtId, selectedName){
            $('#location').html('<option value="">Loading...</option>');
            $('#location_id').val('');
            $.getJSON('register.php', {ajax:'locations', district_id: districtId}, function(rows){
                let opts = '<option value="">-- Pilih Lokasi --</option>';
                rows.forEach(r=>{
                    const sel = (selectedName && selectedName===r.name) ? ' selected' : '';
                    opts += `<option data-id="${r.id}" value="${r.name}"${sel}>${r.name}</option>`;
                });
                $('#location').html(opts);
                const opt = $('#location').find('option:selected');
                $('#location_id').val(opt.data('id') || '');
            });
        }

        // NOTE:
        //  - EXCO: isi #exco_auto (nama) + #exco_member_id (id) — ikut district
        //  - EXCO (Penyokong): GLOBAL — value=nama (compat), data-id=id
        function loadApprovers(districtId, selectedSupporterName){
            $('#approverBox').hide();
            // reset
            $('#exco_auto').val('');
            $('#exco_member_id').val('');
            $('#exco_select_id').val('');
            $('#exco_select').html('<option value="">Loading...</option>');

            $.getJSON('register.php', {ajax:'approvers', district_id: districtId}, function(res){
                // EXCO (Pencadang, max 1)
                if (res.exco && res.exco.length){
                    const item = res.exco[0]; // {id,name}
                    $('#exco_auto').val(item.name);
                    $('#exco_member_id').val(item.id);
                }

                // EXCO (Penyokong) GLOBAL
                let opts = '<option value="">-- Pilih EXCO (Penyokong) --</option>';
                if (res.ajk && res.ajk.length){
                    res.ajk.forEach(a=>{
                        const label = a.district_name ? `${a.name} — ${a.district_name}` : a.name;
                        const sel = (selectedSupporterName && selectedSupporterName===a.name) ? ' selected' : '';
                        opts += `<option value="${a.name}" data-id="${a.id}"${sel}>${label}</option>`;
                    });
                }
                $('#exco_select').html(opts);

                // Set hidden exco_select_id ikut option selected (kalau ada preselect)
                const cur = $('#exco_select').find('option:selected').data('id') || '';
                if (cur) $('#exco_select_id').val(cur);

                if ((res.exco && res.exco.length) || (res.ajk && res.ajk.length)) {
                    $('#approverBox').show();
                }
            });
        }

        function onDistrictChange(){
            const did = $('#district_id').val();
            if (!did) {
                $('#location').html('<option value="">-- Pilih Lokasi --</option>');
                $('#location_id').val('');
                $('#approverBox').hide();
                $('#exco_auto').val('');
                $('#exco_member_id').val('');
                $('#exco_select').html('<option value="">-- Pilih EXCO (Penyokong) --</option>');
                $('#exco_select_id').val('');
                return;
            }
            loadLocations(did, '');
            loadApprovers(did, '');
        }

        function onLocationChange(){
            const opt = $('#location').find('option:selected');
            $('#location_id').val(opt.data('id') || '');
        }

        document.addEventListener('DOMContentLoaded', function(){
            const flash = <?= json_encode($flash ?? null, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE) ?>;
            if (flash && flash.message) {
                Swal.fire({ icon: flash.type || 'info', title: flash.message, showConfirmButton:false, timer:2600 });
                if (flash.focus) { const el = document.getElementById(flash.focus); if (el) { smoothFocus(el); highlightOnce(el); } }
                if (Array.isArray(flash.highlight)) { flash.highlight.forEach(id => { const el = document.getElementById(id); if (el) highlightOnce(el); }); }
                if ((flash.code && flash.code === 'required') || flash.message === 'Please fill in all required fields.') {
                    const target = firstRequiredInvalid(); if (target) { smoothFocus(target); highlightOnce(target); }
                }
            }

            // Hook password meter
            const ctx = {
                name: document.getElementById('full_name')?.value || '',
                email: document.getElementById('email')?.value || '',
                staff: document.getElementById('staff_number')?.value || '',
                ic: document.getElementById('ic_number')?.value || ''
            };
            const pwInput = document.getElementById('password');
            if (pwInput) {
                pwInput.addEventListener('input', ()=>{
                    const res = evalPassword(pwInput.value, ctx);
                    paintMeter(res.score); updateChecklist(res.checks); setPasswordValidity(pwInput.value, res.checks); checkConfirmMatch();
                });
            }
            const cp = document.getElementById('confirm_password');
            if (cp) cp.addEventListener('input', checkConfirmMatch);

            // Auto-format fields
            attachFormatter('ic_number', formatICInput);
            attachFormatter('phone',      formatMobileInput);
            attachFormatter('home_phone', formatHomeInput);
            attachFormatter('waris_phone',formatMobileInput);

            // District change handlers
            $('#district_id').on('change', onDistrictChange);
            $('#location').on('change', onLocationChange);

            // EXCO (Penyokong) select → set hidden id setiap kali berubah
            $('#exco_select').on('change', function(){
                const id = $(this).find('option:selected').data('id') || '';
                $('#exco_select_id').val(id);
            });

            // ===== Real-time duplicate checks =====
            const staffEl  = document.getElementById('staff_number');
            const icEl     = document.getElementById('ic_number');
            const emailEl  = document.getElementById('email');

            if (staffEl){ staffEl.addEventListener('input', ()=>validateStaff(staffEl));
                          staffEl.addEventListener('blur',  ()=>validateStaff(staffEl));
                          if (staffEl.value) validateStaff(staffEl); }
            if (icEl){    icEl.addEventListener('input', ()=>validateIC(icEl));
                          icEl.addEventListener('blur',  ()=>validateIC(icEl));
                          if (icEl.value) validateIC(icEl); }
            if (emailEl){ emailEl.addEventListener('input', ()=>validateEmail(emailEl));
                          emailEl.addEventListener('blur',  ()=>validateEmail(emailEl));
                          if (emailEl.value) validateEmail(emailEl); }

            // Prefill
            const oldDid = '<?= (int)$oldDistrictId ?>';
            const oldLocName = <?= json_encode($old['location'] ?? '', JSON_UNESCAPED_UNICODE) ?>;
            const oldSupporterName = <?= json_encode($old['exco_select'] ?? '', JSON_UNESCAPED_UNICODE) ?>;

            if (oldDid) {
                const opt = $('#location').find('option').filter(function(){ return $(this).attr('value') === oldLocName; }).first();
                if (opt.length) $('#location_id').val(opt.data('id') || '');
                $('#exco_member_id').val('<?= (int)$prefillExcoId ?>');
                $('#exco_select_id').val('<?= (int)$prefillAjkSelectedId ?>');
                loadApprovers(oldDid, oldSupporterName);
            }

            // ====== Prevent submit if EXCO penyokong ID tiada (force sync) ======
            const form = document.querySelector('form');
            if (form){
                form.addEventListener('submit', function(e){
                    const selectedId = $('#exco_select').find('option:selected').data('id') || '';
                    $('#exco_select_id').val(selectedId);

                    const penyokongName = ($('#exco_select').val() || '').trim();
                    if (!penyokongName || !selectedId) {
                        e.preventDefault();
                        Swal.fire({ icon:'error', title:'Sila pilih EXCO Penyokong', text:'Sila pilih seorang EXCO sebagai Penyokong sebelum hantar.' });
                        const el = document.getElementById('exco_select');
                        smoothFocus(el); highlightOnce(el);
                        return false;
                    }
                });
            }
        });
    </script>
</head>
<body>
<div class="form-box">
    <h2>Permohonan Ahli Baharu</h2>

    <form method="post" action="register-process.php" enctype="multipart/form-data" novalidate>
        <!-- ====== Maklumat Peribadi ====== -->
        <div>
            <label>Nama Penuh <span style="color:red">*</span></label>
            <input type="text" name="full_name" id="full_name" required value="<?= h($old['full_name'] ?? '') ?>">
        </div>

        <div>
            <label>No. Anggota <span style="color:red">*</span></label>
            <input type="text" id="staff_number" name="staff_number" required value="<?= h($old['staff_number'] ?? '') ?>">
            <div id="staff_msg" class="info" aria-live="polite"></div>
        </div>

        <div>
            <label>No. KP <span style="color:red">*</span></label>
            <input type="text"
                   name="ic_number"
                   id="ic_number"
                   required
                   inputmode="numeric"
                   autocomplete="off"
                   maxlength="14"
                   placeholder="e.g. 900101-01-1234"
                   value="<?= h($old['ic_number'] ?? '') ?>">
            <div id="ic_msg" class="info" aria-live="polite"></div>
        </div>

        <div>
            <label>Alamat E-mel <span style="color:red">*</span></label>
            <input type="email" id="email" name="email" required value="<?= h($old['email'] ?? '') ?>">
            <div id="email_msg" class="info" aria-live="polite"></div>
        </div>

        <?php
        // Job Titles
        $jobTitles = [];
        $stmt = $conn->prepare("SELECT id, name FROM job_titles WHERE active = 1 ORDER BY name ASC");
        if ($stmt) { $stmt->execute(); $res = $stmt->get_result(); while ($r = $res->fetch_assoc()) $jobTitles[] = $r; $stmt->close(); }
        ?>
        <div>
            <label>Jawatan <span style="color:red">*</span></label>
            <select name="job_title" id="job_title" required>
                <option value="">-- Sila Pilih Jawatan --</option>
                <?php foreach ($jobTitles as $jt): ?>
                    <option value="<?= h($jt['name']) ?>" <?= (!empty($old['job_title']) && $old['job_title']===$jt['name'])?'selected':'' ?>><?= h($jt['name']) ?></option>
                <?php endforeach; ?>
            </select>
            <div class="info" style="color:#555">Jika tiada dalam senarai, sila hubungi Admin untuk pengemaskinian.</div>
        </div>

        <!-- ====== District & Location & Approvers ====== -->
        <div class="grid-2">
            <div>
                <label>Daerah Bertugas <span style="color:red">*</span></label>
                <select name="district_id" id="district_id" required>
                    <option value="">-- Pilih Daerah --</option>
                    <?php foreach ($districts as $d): ?>
                        <option value="<?= (int)$d['id'] ?>" <?= (!empty($oldDistrictId) && (int)$oldDistrictId===(int)$d['id'])?'selected':'' ?>>
                            <?= h($d['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label>Lokasi Bertugas <span style="color:red">*</span></label>
                <!-- NOTE: value = NAMA lokasi (kompat), data-id = id lokasi -->
                <select name="location" id="location" required>
                    <?php if (!$oldDistrictId): ?>
                        <option value="">-- Pilih Lokasi --</option>
                    <?php else: ?>
                        <option value="">-- Pilih Lokasi --</option>
                        <?php foreach ($prefillLocations as $L): ?>
                            <option value="<?= h($L['name']) ?>"
                                    data-id="<?= (int)$L['id'] ?>"
                                    <?= (!empty($old['location']) && $old['location']===$L['name'])?'selected':'' ?>>
                                <?= h($L['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </select>
                <input type="hidden" name="location_id" id="location_id" value="">
            </div>
        </div>

        <!-- Approver info -->
        <div id="approverBox" class="section" style="display: <?= ($oldDistrictId || !empty($prefillAjkRows)) ? 'block':'none' ?>;">
            <h3>EXCO (Pencadang & Penyokong)</h3>
            <div class="grid-2">
                <div>
                    <label>EXCO (Pencadang)</label>
                    <input type="text" id="exco_auto" name="exco_auto" readonly value="<?= h($prefillExcoText ?: ($old['exco_auto'] ?? '')) ?>">
                    <!-- Hantar ID EXCO (hidden) -->
                    <input type="hidden" name="exco_member_id" id="exco_member_id" value="<?= (int)$prefillExcoId ?>">
                </div>
                <div>
                    <label>EXCO (Penyokong) <span style="color:red">*</span></label>
                    <!-- value=nama (compat), option ada data-id; hantar hidden exco_select_id -->
                    <select name="exco_select" id="exco_select" required>
                        <option value="">-- Pilih EXCO (Penyokong) --</option>
                        <?php foreach ($prefillAjkRows as $ajk): ?>
                            <option
                                value="<?= h($ajk['name']) ?>"
                                data-id="<?= (int)$ajk['id'] ?>"
                                <?= (!empty($old['exco_select']) && $old['exco_select']===$ajk['name'])?'selected':'' ?>>
                                <?= h($ajk['name'].' — '.$ajk['district_name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <input type="hidden" name="exco_select_id" id="exco_select_id" value="<?= (int)$prefillAjkSelectedId ?>">
                </div>
            </div>
            <div class="muted" style="margin-top:6px">
                <b>EXCO (Pencadang)</b> dipilih automatik ikut daerah; <b>EXCO (Penyokong)</b> ialah senarai semua EXCO aktif.
                <br>Hanya EXCO yang dipilih akan boleh lihat & meluluskan permohonan ini pada peringkat masing-masing.
            </div>
        </div>
        <!-- ====== TAMAT: Approvers ====== -->

        <div class="grid-2">
            <div>
                <label>No. Tel Kediaman <span style="color:red">*</span></label>
                <input type="text" name="home_phone" id="home_phone" required placeholder="e.g. 03-3456789" value="<?= h($old['home_phone'] ?? '') ?>">
            </div>
            <div>
                <label>No. Tel Bimbit <span style="color:red">*</span></label>
                <input type="text"
                       name="phone"
                       id="phone"
                       required
                       inputmode="numeric"
                       autocomplete="off"
                       maxlength="13"
                       placeholder="e.g. 012-3456789 atau 011-1234-5678"
                       value="<?= h($old['phone'] ?? '') ?>">
            </div>
        </div>

        <div class="grid-2">
            <div>
                <label>Bangsa <span style="color:red">*</span></label>
                <select name="race" id="race" required>
                    <option value="">-- Select --</option>
                    <option value="Malay"      <?= (isset($old['race']) && $old['race']==='Malay')?'selected':'' ?>>Malay</option>
                    <option value="Chinese"    <?= (isset($old['race']) && $old['race']==='Chinese')?'selected':'' ?>>Chinese</option>
                    <option value="Indian"     <?= (isset($old['race']) && $old['race']==='Indian')?'selected':'' ?>>Indian</option>
                    <option value="Bumiputera" <?= (isset($old['race']) && $old['race']==='Bumiputera')?'selected':'' ?>>Bumiputera</option>
                    <option value="Others"     <?= (isset($old['race']) && $old['race']==='Others')?'selected':'' ?>>Others</option>
                </select>
            </div>
        </div>

        <div class="section">
            <h3>Maklumat Waris (Optional)</h3>
            <div class="grid-2">
                <div>
                    <label>Nama Waris</label>
                    <input type="text" name="waris_name" id="waris_name" maxlength="150" placeholder="Contoh: Aminah binti Ali" value="<?= h($old['waris_name'] ?? '') ?>">
                </div>
                <div>
                    <label>No. Telefon Waris</label>
                    <input type="text" name="waris_phone" id="waris_phone" maxlength="30"
                           pattern="^[0-9+\-\s]{7,20}$" title="Hanya nombor / + / - / ruang (7–20 aksara)"
                           placeholder="012-xxx xxxx" value="<?= h($old['waris_phone'] ?? '') ?>">
                </div>
            </div>
        </div>

        <div>
            <label for="address">Alamat Kediaman <span style="color:red">*</span></label>
            <textarea name="address" id="address" required><?= h($old['address'] ?? '') ?></textarea>
        </div>

        <div>
            <label for="postcode">Poskod <span style="color:red">*</span></label>
            <input type="text" name="postcode" id="postcode" required value="<?= h($old['postcode'] ?? '') ?>">
        </div>

        <!-- Upload Resit (Optional semasa draf; Wajib semasa submit akhir) -->
        <div>
            <label for="receipt">Muat Naik Resit (PDF, JPEG, PNG)</label>
            <input type="file" name="receipt" id="receipt" accept=".pdf,.jpeg,.jpg,.png" onchange="previewFile()">
            <div id="preview"></div>

            <?php if (!empty($draftReceipt)): ?>
                <div class="muted" style="margin-top:6px">
                    ✔ Resit telah disimpan sebelum ini.
                    <?php if (preg_match('~^uploads/~', $draftReceipt)): ?>
                        <a href="<?= h($draftReceipt) ?>" target="_blank" rel="noopener">Lihat resit sedia ada</a>.
                    <?php endif; ?>
                    <br>Anda boleh biarkan sahaja, atau muat naik resit baharu untuk menggantikan yang sedia ada.
                </div>
            <?php else: ?>
                <div class="muted" style="margin-top:6px">
                    Muat naik di sini jika sudah ada. Jika belum, anda boleh terus simpan draf; resit akan diperlukan semasa pengesahan/submit akhir.
                </div>
            <?php endif; ?>
        </div>

        <!-- Paparan Maklumat Pembayaran — pay-card -->
        <div class="section">
            <h3>Maklumat Pembayaran</h3>
            <?php if ($pay): ?>
                <div class="pay-card">
                    <div class="qr">
                        <?php if (!empty($pay['qr_image_path'])): ?>
                            <a href="<?= h($pay['qr_image_path']) ?>" target="_blank" rel="noopener" title="Klik untuk paparan penuh">
                                <img src="<?= h($pay['qr_image_path']) ?>?v=<?= time() ?>" alt="QR Payment">
                            </a>
                        <?php else: ?>
                            <div class="muted">QR belum dimuat naik.</div>
                        <?php endif; ?>
                    </div>
                    <div class="details">
                        <div><strong>Bank:</strong> <?= h($pay['bank_name']) ?></div>
                        <div><strong>No. Akaun:</strong> <?= h($pay['account_number']) ?></div>
                        <div><strong>Nama Akaun:</strong> <?= h($pay['account_name']) ?></div>
                        <?php if (!empty($pay['note'])): ?>
                            <div class="callout" style="margin-top:8px"><?= h($pay['note']) ?></div>
                        <?php endif; ?>
                        <div class="muted" style="margin-top:6px">
                            Sila buat bayaran menggunakan butiran di atas atau imbas kod QR.
                            Selepas pembayaran, muat naik resit pada medan di atas.
                        </div>
                        <?php if (!empty($pay['qr_image_path'])): ?>
                            <div class="muted" style="margin-top:4px">
                                <i><b>Nota:</b> Sila klik gambar QR untuk paparan penuh.</i>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php else: ?>
                <div class="callout">Maklumat pembayaran belum dikonfigurasi oleh admin.</div>
            <?php endif; ?>
        </div>

        <div>
            <label>Kata Laluan <span style="color:red">*</span></label>
            <input type="password" name="password" id="password" required autocomplete="new-password" aria-describedby="pw_help">
            <div class="toggle-pass" onclick="(function(){const el=document.getElementById('password'); el.type=(el.type==='password')?'text':'password';})()">👁️ Show/Hide Password</div>

            <div class="pw-wrap" id="pw_help">
                <div class="pw-meter" aria-hidden="true">
                    <span></span><span></span><span></span><span></span><span></span>
                </div>
                <div class="pw-label" id="pw_strength_label">Sangat Lemah</div>
                <ul class="pw-req" aria-live="polite">
                    <li id="req_len8">Sekurang-kurangnya 8 aksara</li>
                    <li id="req_mixcase">Gabungan huruf besar & kecil</li>
                    <li id="req_digit">Mengandungi nombor</li>
                    <li id="req_special">Mengandungi simbol</li>
                    <li id="req_personal">Tidak mengandungi nama/emel/no. anggota/no. KP</li>
                    <li id="req_seq">Tiada jujukan mudah (cth: 1234, abcd, qwerty)</li>
                </ul>
            </div>
        </div>

        <div>
            <label>Sahkan Kata Laluan <span style="color:red">*</span></label>
            <input type="password" name="confirm_password" id="confirm_password" required autocomplete="new-password" oninput="(function(){const p1=document.getElementById('password').value; const p2=this.value; const m=document.getElementById('match_msg'); 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';}})()">
            <div class="toggle-pass" onclick="(function(){const el=document.getElementById('confirm_password'); el.type=(el.type==='password')?'text':'password';})()">👁️ Show/Hide Password</div>
            <div id="match_msg" class="match"></div>
        </div>

        <button type="submit">Daftar</button>

        <!-- ⚠️ TIADA hidden duplicate di bawah. Semua hidden EXCO berada dalam kotak Approver. -->
    </form>

    <div class="back-btn">
        <a href="index.php">← Kembali Pada Log Masuk</a>
    </div>
</div>
</body>
</html>
