<?php
/* ============================================================================
   Shared KYC module — used by customer profile.php, seller/profile.php and
   read by admin/user_list.php.
   UI: 4 square flash-cards; clicking one opens that section's form in a popup.
   Each section submits & updates independently.  State & District are
   dependent dropdowns.
   ============================================================================ */

/* ---- Section -> columns / files (single source of truth) ---- */
function kyc_sections() {
    return [
        'personal' => [
            'label' => 'Personal Details',
            'cols'  => ['full_name','gender','dob','father_name','email','phone_number','business_name_personal','aadhar_number','pancard_number'],
            'files' => ['aadhar_front','aadhar_back','pan_card','photo'],
        ],
        'address' => [
            'label' => 'Address Details',
            'cols'  => ['village','post_office','block_city','landmark','district','state','pincode'],
            'files' => ['address_proof'],
        ],
        'bank' => [
            'label' => 'Bank Details',
            'cols'  => ['bank_name','branch_name','account_number','ifsc_code'],
            'files' => ['bank_passbook'],
        ],
        'business' => [
            'label' => 'Business Details',
            'cols'  => ['business_name','business_phone','business_email','same_as_personal','biz_village','biz_post_office','biz_block_city','biz_landmark','biz_district','biz_state','biz_pincode'],
            'files' => ['business_proof'],
        ],
    ];
}
function kyc_file_cols() {
    $all = [];
    foreach (kyc_sections() as $s) { $all = array_merge($all, $s['files']); }
    return $all;
}

/* ---- Ensure the kyc_details table exists (no manual migration needed) ---- */
function kyc_ensure_schema($db) {
    try {
        $db->getConnection()->query("
            CREATE TABLE IF NOT EXISTS kyc_details (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL UNIQUE,
                full_name VARCHAR(150) NULL, gender VARCHAR(20) NULL, dob VARCHAR(20) NULL,
                father_name VARCHAR(150) NULL, email VARCHAR(150) NULL,
                phone_number VARCHAR(30) NULL, business_name_personal VARCHAR(200) NULL,
                aadhar_number VARCHAR(30) NULL, pancard_number VARCHAR(30) NULL,
                aadhar_front VARCHAR(255) NULL, aadhar_back VARCHAR(255) NULL,
                pan_card VARCHAR(255) NULL, photo VARCHAR(255) NULL,
                village VARCHAR(150) NULL, post_office VARCHAR(150) NULL, block_city VARCHAR(150) NULL,
                landmark VARCHAR(255) NULL, district VARCHAR(150) NULL, state VARCHAR(150) NULL, pincode VARCHAR(20) NULL,
                address_proof VARCHAR(255) NULL,
                bank_name VARCHAR(150) NULL, branch_name VARCHAR(150) NULL,
                account_number VARCHAR(50) NULL, ifsc_code VARCHAR(30) NULL, bank_passbook VARCHAR(255) NULL,
                business_name VARCHAR(200) NULL, business_phone VARCHAR(30) NULL, business_email VARCHAR(150) NULL,
                same_as_personal TINYINT(1) NOT NULL DEFAULT 0,
                biz_village VARCHAR(150) NULL, biz_post_office VARCHAR(150) NULL, biz_block_city VARCHAR(150) NULL,
                biz_landmark VARCHAR(255) NULL, biz_district VARCHAR(150) NULL, biz_state VARCHAR(150) NULL, biz_pincode VARCHAR(20) NULL,
                business_proof VARCHAR(255) NULL,
                status ENUM('pending','approved','rejected') DEFAULT 'pending',
                admin_remark TEXT NULL,
                created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NULL DEFAULT NULL
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    } catch (\Throwable $e) { /* ignore */ }

    /* ---- Self-healing: columns added by the 4-step wizard.
            sspmigration.php does the same thing explicitly, but this keeps an
            already-live database working even if the migration has not run. ---- */
    static $patched = false;
    if ($patched) return;
    $patched = true;
    $add = [
        'phone_number'           => "VARCHAR(30) NULL",
        'business_name_personal' => "VARCHAR(200) NULL",
        'same_as_personal'       => "TINYINT(1) NOT NULL DEFAULT 0",
    ];
    foreach ($add as $col => $def) {
        try {
            $conn = $db->getConnection();
            $r = $conn->query("SHOW COLUMNS FROM kyc_details LIKE '$col'");
            if ($r && $r->num_rows === 0) { $conn->query("ALTER TABLE kyc_details ADD COLUMN `$col` $def"); }
        } catch (\Throwable $e) { /* ignore */ }
    }
}

/* ---- Get KYC data for a user: existing row, else prefill from profile ---- */
function kyc_get_data($db, $user_id) {
    $row = $db->select("SELECT * FROM kyc_details WHERE user_id = ?", [$user_id]);
    if (!empty($row)) return $row[0];

    $u = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
    $u = !empty($u) ? $u[0] : [];

    $seller = []; $upgrade = [];
    try { $s = $db->select("SELECT * FROM sellers WHERE user_id = ? ORDER BY id DESC LIMIT 1", [$user_id]); $seller = !empty($s) ? $s[0] : []; } catch (\Throwable $e) {}
    try { $r = $db->select("SELECT * FROM seller_upgrade_requests WHERE user_id = ? ORDER BY id DESC LIMIT 1", [$user_id]); $upgrade = !empty($r) ? $r[0] : []; } catch (\Throwable $e) {}

    $biz_name  = $seller['business_name'] ?? ($upgrade['business_name'] ?? '');
    $biz_phone = $seller['phone'] ?? ($upgrade['business_phone'] ?? ($u['whatsapp_number'] ?? ''));
    $biz_email = $seller['email'] ?? ($u['email'] ?? '');

    $data = [
        'full_name'    => $u['name'] ?? '', 'gender' => $u['gender'] ?? '', 'dob' => '',
        'father_name'  => '', 'email' => $u['email'] ?? '',
        'phone_number' => $u['mobile'] ?? '', 'business_name_personal' => $biz_name,
        'aadhar_number' => '', 'pancard_number' => '', 'same_as_personal' => 0,
        'village'      => $u['village'] ?? '', 'post_office' => $u['post_office'] ?? '',
        'block_city'   => $u['block_city'] ?? '', 'landmark' => $u['landmark'] ?? '',
        'district'     => $u['district'] ?? '', 'state' => $u['state'] ?? '', 'pincode' => $u['pincode'] ?? '',
        'bank_name'    => '', 'branch_name' => '', 'account_number' => '', 'ifsc_code' => '',
        'business_name'=> $biz_name, 'business_phone' => $biz_phone, 'business_email' => $biz_email,
        'biz_village'  => $u['village'] ?? '', 'biz_post_office' => $u['post_office'] ?? '',
        'biz_block_city'=> $u['block_city'] ?? '', 'biz_landmark' => $u['landmark'] ?? '',
        'biz_district' => $u['district'] ?? '', 'biz_state' => $u['state'] ?? '', 'biz_pincode' => $u['pincode'] ?? '',
        'status'       => 'not_submitted', 'admin_remark' => '',
    ];
    foreach (kyc_file_cols() as $fc) { $data[$fc] = ''; }
    return $data;
}

/* ---- Handle a single-section KYC submission ---- */
/* ============================================================================
   MANDATORY SECTIONS
     everyone → Personal Details, Address Details, Bank Details
     sellers  → the above plus Business Details
   ============================================================================ */
function kyc_required_sections($user_type = 'customer') {
    $req = ['personal', 'address', 'bank'];
    if ($user_type === 'seller') { $req[] = 'business'; }
    return $req;
}

/* Is one section filled in? (any field in it has a value) */
function kyc_section_filled($row, $section) {
    $s = kyc_sections();
    if (!isset($s[$section])) return false;
    foreach ($s[$section]['cols'] as $c) { if (!empty($row[$c])) return true; }
    return false;
}

/**
 * Completion state for a user.
 * Returns ['required','done','missing','complete','percent','status']
 */
function kyc_progress($db, $user_id, $user_type = null) {
    kyc_ensure_schema($db);

    if ($user_type === null) {
        try {
            $u = $db->select("SELECT user_type FROM users WHERE id = ?", [(int)$user_id]);
            $user_type = !empty($u) ? $u[0]['user_type'] : 'customer';
        } catch (\Throwable $e) { $user_type = 'customer'; }
    }

    $row = [];
    try {
        $r = $db->select("SELECT * FROM kyc_details WHERE user_id = ?", [(int)$user_id]);
        $row = !empty($r) ? $r[0] : [];
    } catch (\Throwable $e) {}

    $req = kyc_required_sections($user_type);
    $done = []; $missing = [];
    foreach ($req as $sec) {
        if (kyc_section_filled($row, $sec)) $done[] = $sec; else $missing[] = $sec;
    }

    $labels = kyc_sections();
    return [
        'required'       => $req,
        'done'           => $done,
        'missing'        => $missing,
        'missing_labels' => array_map(function ($s) use ($labels) { return $labels[$s]['label'] ?? ucfirst($s); }, $missing),
        'complete'       => empty($missing),
        'percent'        => count($req) > 0 ? (int)round((count($done) / count($req)) * 100) : 100,
        'status'         => $row['status'] ?? 'not_submitted',
        'approved'       => (($row['status'] ?? '') === 'approved') && empty($missing),
        'user_type'      => $user_type,
    ];
}

function kyc_handle_post($db, $user_id, $uploads_rel, $redirect_to) {
    if (!isset($_POST['kyc_submit'])) return;
    $section = $_POST['kyc_section'] ?? '';
    $sections = kyc_sections();

    /* 'all' = the 4-step wizard submitting every section in one go.
       Individual section keys are still accepted (admin tools / old links). */
    $is_all = ($section === 'all');
    if (!$is_all && !isset($sections[$section])) return;

    $use_cols  = $is_all ? kyc_all_cols()  : $sections[$section]['cols'];
    $use_files = $is_all ? kyc_file_cols() : $sections[$section]['files'];
    $label     = $is_all ? 'KYC'           : $sections[$section]['label'];

    $data = [];
    foreach ($use_cols as $c) {
        if ($c === 'same_as_personal') { $data[$c] = !empty($_POST['same_as_personal']) ? 1 : 0; continue; }
        $data[$c] = isset($_POST[$c]) ? sanitize($_POST[$c]) : '';
    }

    /* "Business address is the same as my address" — copy it server side too,
       so the saved row is correct even if JS was blocked. */
    if (!empty($_POST['same_as_personal'])) {
        $pairs = [
            'biz_village' => 'village', 'biz_post_office' => 'post_office', 'biz_block_city' => 'block_city',
            'biz_landmark' => 'landmark', 'biz_district' => 'district', 'biz_state' => 'state', 'biz_pincode' => 'pincode',
        ];
        foreach ($pairs as $bz => $src) {
            if (array_key_exists($bz, $data)) {
                $data[$bz] = isset($_POST[$src]) ? sanitize($_POST[$src]) : ($data[$bz] ?? '');
            }
        }
    }

    if (!is_dir($uploads_rel)) { @mkdir($uploads_rel, 0777, true); }

    $files = [];
    foreach ($use_files as $fc) {
        if (!empty($_FILES[$fc]['name']) && isset($_FILES[$fc]['tmp_name']) && is_uploaded_file($_FILES[$fc]['tmp_name'])) {
            $ext = strtolower(pathinfo($_FILES[$fc]['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg','jpeg','png','webp','pdf'])) {
                $fn = 'kyc_' . $user_id . '_' . $fc . '_' . time() . '.' . $ext;
                if (move_uploaded_file($_FILES[$fc]['tmp_name'], rtrim($uploads_rel, '/') . '/' . $fn)) { $files[$fc] = $fn; }
            }
        }
    }

    /* ------------------------------------------------------------------
       LOCK. Whatever is already on the record cannot be changed by the
       member — not from this form, not from the checkout page, not by a
       hand-made POST. Only the office can correct a saved line.
       Name, email and phone are owned by the registration record and are
       always written from there.
       ------------------------------------------------------------------ */
    $existing = $db->select("SELECT * FROM kyc_details WHERE user_id = ?", [$user_id]);
    $prev     = !empty($existing) ? $existing[0] : [];

    $__acct = ['full_name' => 'name', 'email' => 'email', 'phone_number' => 'mobile'];
    $__ur   = $db->select("SELECT name, email, mobile FROM users WHERE id = ?", [$user_id]);
    $__ur   = !empty($__ur) ? $__ur[0] : [];
    foreach ($__acct as $__c => $__src) {
        if (array_key_exists($__c, $data)) { $data[$__c] = trim((string)($__ur[$__src] ?? '')); }
    }
    foreach (array_keys($data) as $__c) {
        if ($__c === 'same_as_personal') continue;
        if (isset($prev[$__c]) && trim((string)$prev[$__c]) !== '') { unset($data[$__c]); }
    }
    foreach (array_keys($files) as $__c) {
        if (isset($prev[$__c]) && trim((string)$prev[$__c]) !== '') { unset($files[$__c]); }
    }
    if (empty($data) && empty($files)) {
        $_SESSION['flash_success'] = 'Nothing changed — everything on your KYC is already saved and locked.';
        redirect($redirect_to);
    }

    if (!empty($existing)) {
        $sets = []; $params = [];
        foreach ($data as $c => $v)  { $sets[] = "`$c` = ?"; $params[] = $v; }
        foreach ($files as $c => $v) { $sets[] = "`$c` = ?"; $params[] = $v; }
        $sets[] = "status = 'pending'";
        $sets[] = "updated_at = NOW()";
        $params[] = $user_id;
        $db->insert("UPDATE kyc_details SET " . implode(', ', $sets) . " WHERE user_id = ?", $params);
    } else {
        $all = $data;
        foreach ($files as $c => $v) { $all[$c] = $v; }
        $all['user_id'] = $user_id;
        $all['status']  = 'pending';
        $cols = array_keys($all);
        $ph   = implode(',', array_fill(0, count($cols), '?'));
        $colstr = '`' . implode('`,`', $cols) . '`';
        $db->insert("INSERT INTO kyc_details ($colstr) VALUES ($ph)", array_values($all));
    }
    $_SESSION['flash_success'] = $label . " submitted successfully! Your KYC is now under review.";
    redirect($redirect_to);
}

/* ---- All editable text columns across every section ---- */
function kyc_all_cols() {
    $cols = [];
    foreach (kyc_sections() as $s) { $cols = array_merge($cols, $s['cols']); }
    return $cols;
}

/* ---- Admin edit: save ALL sections at once for a target user ---- */
function kyc_admin_save($db, $user_id, $uploads_rel, $me) {
    $data = [];
    foreach (kyc_all_cols() as $c) { if (isset($_POST[$c])) { $data[$c] = sanitize($_POST[$c]); } }

    if (!is_dir($uploads_rel)) { @mkdir($uploads_rel, 0777, true); }

    $files = [];
    foreach (kyc_file_cols() as $fc) {
        if (!empty($_FILES[$fc]['name']) && isset($_FILES[$fc]['tmp_name']) && is_uploaded_file($_FILES[$fc]['tmp_name'])) {
            $ext = strtolower(pathinfo($_FILES[$fc]['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg','jpeg','png','webp','pdf'])) {
                $fn = 'kyc_' . $user_id . '_' . $fc . '_' . time() . '.' . $ext;
                if (move_uploaded_file($_FILES[$fc]['tmp_name'], rtrim($uploads_rel, '/') . '/' . $fn)) { $files[$fc] = $fn; }
            }
        }
    }

    $existing = $db->select("SELECT id FROM kyc_details WHERE user_id = ?", [$user_id]);
    if (!empty($existing)) {
        $sets = []; $params = [];
        foreach ($data as $c => $v)  { $sets[] = "`$c` = ?"; $params[] = $v; }
        foreach ($files as $c => $v) { $sets[] = "`$c` = ?"; $params[] = $v; }
        if (!empty($sets)) {
            $sets[] = "updated_at = NOW()";
            $params[] = $user_id;
            $db->insert("UPDATE kyc_details SET " . implode(', ', $sets) . " WHERE user_id = ?", $params);
        }
    } else {
        $all = $data;
        foreach ($files as $c => $v) { $all[$c] = $v; }
        $all['user_id'] = $user_id;
        $all['status']  = 'pending';
        $cols = array_keys($all);
        $ph   = implode(',', array_fill(0, count($cols), '?'));
        $colstr = '`' . implode('`,`', $cols) . '`';
        $db->insert("INSERT INTO kyc_details ($colstr) VALUES ($ph)", array_values($all));
    }
    try {
        $db->insert("INSERT INTO user_update_history (user_id, field_label, old_value, new_value, updated_by, updated_by_name) VALUES (?, 'KYC Details', '', 'Updated by admin', ?, ?)",
            [$user_id, $me['id'] ?? 0, $me['name'] ?? 'Admin']);
    } catch (\Throwable $e) {}
}

/* ---- Render: progress + status banner + the 4-STEP KYC WIZARD.
       $rel = '' from the site root, '../' from inside /seller.              ---- */
function kyc_render_form($d, $rel = '', $user_type = 'customer') {
    $status    = $d['status'] ?? 'not_submitted';
    $required  = kyc_required_sections($user_type);
    $submitted = ($status !== 'not_submitted');
    $is_seller = ($user_type === 'seller');
    $docUrl = function ($f) use ($rel) { return $rel . 'uploads/kyc/' . $f; };
    $val    = function ($k) use ($d) { return htmlspecialchars($d[$k] ?? '', ENT_QUOTES); };

    $secFilled = [];
    foreach (kyc_sections() as $key => $sec) {
        $f = false;
        foreach (array_merge($sec['cols'], $sec['files']) as $c) { if (!empty($d[$c])) { $f = true; break; } }
        $secFilled[$key] = $submitted && $f;
    }

    $steps = [
        ['key' => 'personal', 'label' => 'Personal',  'icon' => 'fa-user',            'grad' => 'from-amber-400 to-orange-500'],
        ['key' => 'address',  'label' => 'Address',   'icon' => 'fa-location-dot',    'grad' => 'from-blue-500 to-indigo-500'],
        ['key' => 'bank',     'label' => 'Bank',      'icon' => 'fa-building-columns','grad' => 'from-rose-500 to-pink-500'],
        ['key' => 'business', 'label' => 'Business',  'icon' => 'fa-store',           'grad' => 'from-emerald-500 to-teal-500'],
    ];

    $__done = 0;
    foreach ($required as $__r) { if (!empty($secFilled[$__r])) $__done++; }
    $__pct  = count($required) > 0 ? (int)round(($__done / count($required)) * 100) : 100;
    $__miss = [];
    $__labels = ['personal' => 'Personal Details', 'address' => 'Address Details', 'bank' => 'Bank Details', 'business' => 'Business Details'];
    foreach ($required as $__r) { if (empty($secFilled[$__r])) $__miss[] = $__labels[$__r]; }

    $same_checked = !empty($d['same_as_personal']);

    /* Which boxes are already settled and must not be editable again.
       Name / email / phone belong to the registration record and are always
       locked; everything else locks as soon as it holds a value. */
    $__locked = ['full_name', 'email', 'phone_number'];
    if ($status !== 'not_submitted') {
        $__skip = ['id', 'user_id', 'status', 'admin_remark', 'created_at', 'updated_at', 'same_as_personal'];
        foreach ($d as $__c => $__v) {
            if (in_array($__c, $__skip, true)) continue;
            if (trim((string)$__v) !== '') { $__locked[] = $__c; }
        }
    }
    $__locked = array_values(array_unique($__locked));

    ob_start();
    ?>
    <style>
        .kyw-step-dot{display:flex;flex-direction:column;align-items:center;gap:.4rem;flex:1;position:relative;}
        .kyw-step-dot::before{content:"";position:absolute;top:19px;left:-50%;width:100%;height:2px;background:#E2E8F0;z-index:0;}
        .kyw-step-dot:first-child::before{display:none;}
        .kyw-step-dot.done::before{background:#10B981;}
        .kyw-bub{width:38px;height:38px;border-radius:9999px;display:flex;align-items:center;justify-content:center;
                 font-size:.85rem;font-weight:800;background:#F1F5F9;color:#94A3B8;border:2px solid #E2E8F0;
                 position:relative;z-index:1;transition:all .25s;}
        .kyw-step-dot.on   .kyw-bub{background:#1E293B;color:#fff;border-color:#1E293B;box-shadow:0 0 0 4px rgba(30,41,59,.12);}
        .kyw-step-dot.done .kyw-bub{background:#10B981;color:#fff;border-color:#10B981;}
        .kyw-step-lbl{font-size:.62rem;font-weight:800;text-transform:uppercase;letter-spacing:.05em;color:#94A3B8;text-align:center;}
        .kyw-step-dot.on .kyw-step-lbl,.kyw-step-dot.done .kyw-step-lbl{color:#1E293B;}
        @media(min-width:640px){.kyw-step-lbl{font-size:.7rem;}}

        .kyw-doc{border:1px dashed #CBD5E1;border-radius:.9rem;padding:.85rem;background:#F8FAFC;}
        .kyw-doc-head{display:flex;align-items:center;justify-content:space-between;gap:.5rem;margin-bottom:.5rem;}
        .kyw-sample{width:100%;max-width:190px;border-radius:.5rem;border:1px solid #E2E8F0;background:#fff;display:block;}
        .kyw-sample-wrap{display:flex;align-items:center;gap:.6rem;margin-top:.55rem;}
        .kyw-sample-note{font-size:.62rem;color:#94A3B8;line-height:1.35;}
        .kyw-lbl{display:block;font-size:.68rem;font-weight:800;color:#475569;text-transform:uppercase;letter-spacing:.04em;margin-bottom:.28rem;}
        .kyw-in{width:100%;padding:.62rem .9rem;background:#fff;border:1px solid #CBD5E1;border-radius:.6rem;font-size:.85rem;}
        .kyw-in:focus{outline:none;border-color:#3B82F6;box-shadow:0 0 0 3px rgba(59,130,246,.15);}
        .kyw-file{width:100%;font-size:.7rem;color:#64748B;}
        .kyw-file::file-selector-button{margin-right:.5rem;padding:.3rem .6rem;border:0;border-radius:.35rem;background:#EFF6FF;color:#1D4ED8;font-weight:700;font-size:.7rem;cursor:pointer;}
        .kyw-req{color:#E11D48;}
        .kyw-optional{font-size:.6rem;font-weight:700;color:#94A3B8;text-transform:none;letter-spacing:0;}
    </style>

    <div x-data="{
            step: 1,
            last: 4,
            sameAddr: <?php echo $same_checked ? 'true' : 'false'; ?>,
            isSeller: <?php echo $is_seller ? 'true' : 'false'; ?>,
            go(n){ if(n < 1 || n > this.last) return; this.step = n; this.$el.scrollIntoView({behavior:'smooth', block:'start'}); },
            copyAddr(){
                if(!this.sameAddr) return;
                var map = {village:'biz_village', post_office:'biz_post_office', block_city:'biz_block_city',
                           landmark:'biz_landmark', pincode:'biz_pincode'};
                for (var s in map){
                    var a = this.$root.querySelector('[name=\'' + s + '\']');
                    var b = this.$root.querySelector('[name=\'' + map[s] + '\']');
                    if(a && b) b.value = a.value;
                }
                var ss = this.$root.querySelector('#kyc_state'), bs = this.$root.querySelector('#kyc_biz_state');
                var sd = this.$root.querySelector('#kyc_district'), bd = this.$root.querySelector('#kyc_biz_district');
                if(ss && bs){ bs.value = ss.value; bs.dispatchEvent(new Event('change')); }
                if(sd && bd){ setTimeout(function(){ bd.value = sd.value; }, 120); }
            }
         }" class="space-y-5">

        <!-- ===== Progress ===== -->
        <div class="bg-white border-2 <?php echo empty($__miss) ? 'border-emerald-200' : 'border-amber-200'; ?> rounded-2xl p-5">
            <div class="flex flex-wrap items-center justify-between gap-3 mb-3">
                <div>
                    <p class="font-bold text-slate-800 text-sm">
                        <i class="fas <?php echo empty($__miss) ? 'fa-circle-check text-emerald-500' : 'fa-triangle-exclamation text-amber-500'; ?> mr-1.5"></i>
                        Required KYC <?php echo $is_seller ? '(Seller)' : ''; ?>
                    </p>
                    <p class="text-xs text-slate-500 mt-0.5">
                        <?php if (empty($__miss)): ?>
                            All mandatory sections are filled in.
                        <?php else: ?>
                            Still to fill: <b class="text-amber-700"><?php echo htmlspecialchars(implode(', ', $__miss)); ?></b>
                        <?php endif; ?>
                    </p>
                </div>
                <span class="text-2xl font-black <?php echo empty($__miss) ? 'text-emerald-600' : 'text-amber-600'; ?>"><?php echo $__pct; ?>%</span>
            </div>
            <div class="h-2.5 rounded-full bg-slate-100 overflow-hidden">
                <div class="h-full rounded-full transition-all duration-500 <?php echo empty($__miss) ? 'bg-emerald-500' : 'bg-amber-500'; ?>" style="width:<?php echo $__pct; ?>%"></div>
            </div>
            <p class="text-[11px] text-slate-400 mt-2">
                Mandatory for <?php echo $is_seller ? 'sellers' : 'all members'; ?>:
                <b><?php echo htmlspecialchars(implode(' · ', array_map(function ($r) use ($__labels) { return $__labels[$r]; }, $required))); ?></b>
                <?php if (!$is_seller): ?><br><span class="text-slate-400">Business Details is optional for members — mandatory only for sellers.</span><?php endif; ?>
            </p>
        </div>

        <!-- ===== Status banner ===== -->
        <?php if ($status === 'approved'): ?>
            <div class="flex items-center gap-3 bg-emerald-50 border border-emerald-200 text-emerald-800 rounded-2xl px-5 py-4"><i class="fas fa-circle-check text-2xl"></i><div><p class="font-bold">KYC Approved</p><p class="text-sm">Your identity has been verified successfully.</p></div></div>
        <?php elseif ($status === 'pending'): ?>
            <div class="flex items-center gap-3 bg-amber-50 border border-amber-200 text-amber-800 rounded-2xl px-5 py-4"><i class="fas fa-hourglass-half text-2xl"></i><div><p class="font-bold">Verification Pending</p><p class="text-sm">Your KYC is under review. You can still edit and resubmit below.</p></div></div>
        <?php elseif ($status === 'rejected'): ?>
            <div class="flex items-start gap-3 bg-rose-50 border border-rose-200 text-rose-800 rounded-2xl px-5 py-4"><i class="fas fa-circle-xmark text-2xl mt-0.5"></i><div><p class="font-bold">KYC Rejected</p><p class="text-sm">Please correct the details and submit again.<?php echo !empty($d['admin_remark']) ? ' <b>Reason:</b> ' . htmlspecialchars($d['admin_remark']) : ''; ?></p></div></div>
        <?php endif; ?>

        <?php if ($is_seller): ?>
        <div class="flex items-start gap-3 bg-slate-50 border border-slate-200 text-slate-600 rounded-2xl px-5 py-4 text-xs leading-relaxed">
            <i class="fas fa-circle-info text-slate-400 text-lg mt-0.5"></i>
            <span>A complete and <b>approved</b> KYC — including <b>Business Details</b> — is mandatory before you can use any <b>Agency &amp; Software</b> service.</span>
        </div>
        <?php endif; ?>

        <!-- ===== WIZARD ===== -->
        <form method="POST" enctype="multipart/form-data" class="bg-white border border-slate-200 rounded-2xl overflow-hidden">
            <input type="hidden" name="kyc_section" value="all">

            <!-- Stepper -->
            <div class="px-4 sm:px-6 pt-6 pb-5 border-b border-slate-100 bg-slate-50/60">
                <div class="flex items-start">
                    <?php foreach ($steps as $i => $s): $n = $i + 1; ?>
                    <div class="kyw-step-dot" :class="{ 'on': step === <?php echo $n; ?>, 'done': step > <?php echo $n; ?> }">
                        <button type="button" @click="go(<?php echo $n; ?>)" class="kyw-bub">
                            <template x-if="step > <?php echo $n; ?>"><i class="fas fa-check"></i></template>
                            <template x-if="step <= <?php echo $n; ?>"><span><?php echo $n; ?></span></template>
                        </button>
                        <span class="kyw-step-lbl"><?php echo $s['label']; ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="p-4 sm:p-6">

            <!-- ============ STEP 1 — PERSONAL ============ -->
            <div x-show="step === 1" x-transition.opacity>
                <h4 class="text-base font-extrabold text-slate-800 mb-1"><i class="fas fa-user text-amber-500 mr-2"></i>Personal Details</h4>
                <p class="text-xs text-slate-500 mb-5">Your identity as it appears on your Aadhaar card.</p>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div><label class="kyw-lbl">Full Name <span class="kyw-req">*</span></label>
                        <input type="text" name="full_name" value="<?php echo $val('full_name'); ?>" class="kyw-in" required></div>
                    <?php echo kyc_select('Gender', 'gender', $d['gender'] ?? ''); ?>
                    <div><label class="kyw-lbl">Date of Birth</label>
                        <input type="date" name="dob" value="<?php echo $val('dob'); ?>" class="kyw-in"></div>
                    <div><label class="kyw-lbl">Father's Name</label>
                        <input type="text" name="father_name" value="<?php echo $val('father_name'); ?>" class="kyw-in"></div>
                    <div><label class="kyw-lbl">Phone Number <span class="kyw-req">*</span></label>
                        <input type="tel" name="phone_number" value="<?php echo $val('phone_number'); ?>" class="kyw-in" placeholder="10-digit mobile number" required></div>
                    <div><label class="kyw-lbl">Email</label>
                        <input type="email" name="email" value="<?php echo $val('email'); ?>" class="kyw-in"></div>
                    <div class="md:col-span-2"><label class="kyw-lbl">Business / Shop Name <span class="kyw-optional">(if you have one)</span></label>
                        <input type="text" name="business_name_personal" value="<?php echo $val('business_name_personal'); ?>" class="kyw-in" placeholder="e.g. Molla Cyber Cafe"></div>
                </div>

                <!-- Aadhaar: number + uploads side by side -->
                <div class="kyw-doc mt-5">
                    <div class="kyw-doc-head">
                        <p class="text-sm font-extrabold text-slate-700"><i class="fas fa-address-card text-blue-500 mr-1.5"></i>Aadhaar Card</p>
                        <span class="text-[10px] font-black uppercase tracking-wide text-rose-600 bg-rose-50 px-2 py-0.5 rounded-full">Required</span>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 items-start">
                        <div>
                            <label class="kyw-lbl">Aadhaar Number <span class="kyw-req">*</span></label>
                            <input type="text" name="aadhar_number" value="<?php echo $val('aadhar_number'); ?>" class="kyw-in" placeholder="1234 5678 9012" inputmode="numeric" maxlength="14">
                            <div class="kyw-sample-wrap">
                                <?php echo kyc_sample_aadhaar(); ?>
                                <span class="kyw-sample-note">This is what an Aadhaar card looks like.<br>Upload clear photos of <b>both</b> sides.</span>
                            </div>
                        </div>
                        <div>
                            <label class="kyw-lbl">Aadhaar — Front Side</label>
                            <input type="file" name="aadhar_front" accept="image/*,application/pdf" class="kyw-file">
                            <?php if (!empty($d['aadhar_front'])): ?><a href="<?php echo $docUrl($d['aadhar_front']); ?>" target="_blank" class="inline-flex items-center gap-1 mt-2 text-[11px] font-bold text-emerald-600"><i class="fas fa-circle-check"></i> View uploaded</a><?php endif; ?>
                        </div>
                        <div>
                            <label class="kyw-lbl">Aadhaar — Back Side</label>
                            <input type="file" name="aadhar_back" accept="image/*,application/pdf" class="kyw-file">
                            <?php if (!empty($d['aadhar_back'])): ?><a href="<?php echo $docUrl($d['aadhar_back']); ?>" target="_blank" class="inline-flex items-center gap-1 mt-2 text-[11px] font-bold text-emerald-600"><i class="fas fa-circle-check"></i> View uploaded</a><?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- PAN: number + upload side by side -->
                <div class="kyw-doc mt-4">
                    <div class="kyw-doc-head">
                        <p class="text-sm font-extrabold text-slate-700"><i class="fas fa-id-card text-indigo-500 mr-1.5"></i>PAN Card</p>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 items-start">
                        <div>
                            <label class="kyw-lbl">PAN Number</label>
                            <input type="text" name="pancard_number" value="<?php echo $val('pancard_number'); ?>" class="kyw-in uppercase" placeholder="ABCDE1234F" maxlength="10">
                            <div class="kyw-sample-wrap">
                                <?php echo kyc_sample_pan(); ?>
                                <span class="kyw-sample-note">This is what a PAN card looks like.<br>Upload one clear photo.</span>
                            </div>
                        </div>
                        <div>
                            <label class="kyw-lbl">PAN Card Upload</label>
                            <input type="file" name="pan_card" accept="image/*,application/pdf" class="kyw-file">
                            <?php if (!empty($d['pan_card'])): ?><a href="<?php echo $docUrl($d['pan_card']); ?>" target="_blank" class="inline-flex items-center gap-1 mt-2 text-[11px] font-bold text-emerald-600"><i class="fas fa-circle-check"></i> View uploaded</a><?php endif; ?>
                        </div>
                        <div>
                            <label class="kyw-lbl">Passport Photo</label>
                            <input type="file" name="photo" accept="image/*" class="kyw-file">
                            <?php if (!empty($d['photo'])): ?><a href="<?php echo $docUrl($d['photo']); ?>" target="_blank" class="inline-flex items-center gap-1 mt-2 text-[11px] font-bold text-emerald-600"><i class="fas fa-circle-check"></i> View uploaded</a><?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ============ STEP 2 — ADDRESS ============ -->
            <div x-show="step === 2" x-transition.opacity style="display:none;">
                <h4 class="text-base font-extrabold text-slate-800 mb-1"><i class="fas fa-location-dot text-blue-500 mr-2"></i>Address Details</h4>
                <p class="text-xs text-slate-500 mb-5">Your residential address, as printed on your address proof.</p>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div><label class="kyw-lbl">Village / Locality <span class="kyw-req">*</span></label>
                        <input type="text" name="village" value="<?php echo $val('village'); ?>" class="kyw-in"></div>
                    <div><label class="kyw-lbl">Post Office</label>
                        <input type="text" name="post_office" value="<?php echo $val('post_office'); ?>" class="kyw-in"></div>
                    <div><label class="kyw-lbl">Block / City / Municipality</label>
                        <input type="text" name="block_city" value="<?php echo $val('block_city'); ?>" class="kyw-in"></div>
                    <div><label class="kyw-lbl">Landmark</label>
                        <input type="text" name="landmark" value="<?php echo $val('landmark'); ?>" class="kyw-in"></div>
                    <?php echo kyc_state_select('State', 'state', 'kyc_state', $d['state'] ?? ''); ?>
                    <?php echo kyc_district_select('District', 'district', 'kyc_district', $d['district'] ?? ''); ?>
                    <div><label class="kyw-lbl">Pin Code <span class="kyw-req">*</span></label>
                        <input type="text" name="pincode" value="<?php echo $val('pincode'); ?>" class="kyw-in" inputmode="numeric" maxlength="6"></div>
                </div>

                <div class="kyw-doc mt-5">
                    <div class="kyw-doc-head"><p class="text-sm font-extrabold text-slate-700"><i class="fas fa-file-lines text-blue-500 mr-1.5"></i>Address Proof</p></div>
                    <p class="text-[11px] text-slate-500 mb-2">Aadhaar, voter card, ration card or an electricity bill are all accepted.</p>
                    <input type="file" name="address_proof" accept="image/*,application/pdf" class="kyw-file">
                    <?php if (!empty($d['address_proof'])): ?><a href="<?php echo $docUrl($d['address_proof']); ?>" target="_blank" class="inline-flex items-center gap-1 mt-2 text-[11px] font-bold text-emerald-600"><i class="fas fa-circle-check"></i> View uploaded</a><?php endif; ?>
                </div>
            </div>

            <!-- ============ STEP 3 — BANK ============ -->
            <div x-show="step === 3" x-transition.opacity style="display:none;">
                <h4 class="text-base font-extrabold text-slate-800 mb-1"><i class="fas fa-building-columns text-rose-500 mr-2"></i>Bank Details</h4>
                <p class="text-xs text-slate-500 mb-5">Where your withdrawals will be sent. The account must be in your own name.</p>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div><label class="kyw-lbl">Bank Name <span class="kyw-req">*</span></label>
                        <input type="text" name="bank_name" value="<?php echo $val('bank_name'); ?>" class="kyw-in"></div>
                    <div><label class="kyw-lbl">Branch Name</label>
                        <input type="text" name="branch_name" value="<?php echo $val('branch_name'); ?>" class="kyw-in"></div>
                    <div><label class="kyw-lbl">Account Number <span class="kyw-req">*</span></label>
                        <input type="text" name="account_number" value="<?php echo $val('account_number'); ?>" class="kyw-in" inputmode="numeric"></div>
                    <div><label class="kyw-lbl">IFSC Code <span class="kyw-req">*</span></label>
                        <input type="text" name="ifsc_code" value="<?php echo $val('ifsc_code'); ?>" class="kyw-in uppercase" maxlength="11" placeholder="SBIN0001234"></div>
                </div>

                <div class="kyw-doc mt-5">
                    <div class="kyw-doc-head"><p class="text-sm font-extrabold text-slate-700"><i class="fas fa-book text-rose-500 mr-1.5"></i>Passbook / Cancelled Cheque</p></div>
                    <p class="text-[11px] text-slate-500 mb-2">The page showing your name, account number and IFSC.</p>
                    <input type="file" name="bank_passbook" accept="image/*,application/pdf" class="kyw-file">
                    <?php if (!empty($d['bank_passbook'])): ?><a href="<?php echo $docUrl($d['bank_passbook']); ?>" target="_blank" class="inline-flex items-center gap-1 mt-2 text-[11px] font-bold text-emerald-600"><i class="fas fa-circle-check"></i> View uploaded</a><?php endif; ?>
                </div>
            </div>

            <!-- ============ STEP 4 — BUSINESS ============ -->
            <div x-show="step === 4" x-transition.opacity style="display:none;">
                <h4 class="text-base font-extrabold text-slate-800 mb-1">
                    <i class="fas fa-store text-emerald-500 mr-2"></i>Business Details
                    <?php if ($is_seller): ?>
                        <span class="ml-1 align-middle text-[10px] font-black uppercase tracking-wide text-rose-600 bg-rose-50 px-2 py-0.5 rounded-full">Mandatory for sellers</span>
                    <?php else: ?>
                        <span class="ml-1 align-middle text-[10px] font-black uppercase tracking-wide text-slate-500 bg-slate-100 px-2 py-0.5 rounded-full">Optional</span>
                    <?php endif; ?>
                </h4>
                <p class="text-xs text-slate-500 mb-5">
                    <?php echo $is_seller
                        ? 'Sellers must complete this section before any Agency & Software service can be used.'
                        : 'Members can skip this step. Fill it in only if you run a shop or a business.'; ?>
                </p>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div><label class="kyw-lbl">Business / Shop Name <?php if ($is_seller): ?><span class="kyw-req">*</span><?php endif; ?></label>
                        <input type="text" name="business_name" value="<?php echo $val('business_name'); ?>" class="kyw-in"></div>
                    <div><label class="kyw-lbl">Business Phone Number</label>
                        <input type="tel" name="business_phone" value="<?php echo $val('business_phone'); ?>" class="kyw-in"></div>
                    <div class="md:col-span-2"><label class="kyw-lbl">Business Email</label>
                        <input type="email" name="business_email" value="<?php echo $val('business_email'); ?>" class="kyw-in"></div>
                </div>

                <!-- Same-as-personal-address switch -->
                <label class="flex items-start gap-3 mt-5 p-4 rounded-xl border border-emerald-200 bg-emerald-50/60 cursor-pointer">
                    <input type="checkbox" name="same_as_personal" value="1" x-model="sameAddr" @change="copyAddr()"
                           class="mt-0.5 w-4 h-4 rounded border-emerald-300 text-emerald-600 focus:ring-emerald-500">
                    <span>
                        <span class="block text-sm font-bold text-emerald-900">My business address is the same as my own address</span>
                        <span class="block text-xs text-emerald-700 mt-0.5">Tick this and every field below is filled in automatically from Step 2.</span>
                    </span>
                </label>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-5" :class="sameAddr ? 'opacity-60' : ''">
                    <div><label class="kyw-lbl">Village / Locality</label>
                        <input type="text" name="biz_village" value="<?php echo $val('biz_village'); ?>" class="kyw-in" :readonly="sameAddr"></div>
                    <div><label class="kyw-lbl">Post Office</label>
                        <input type="text" name="biz_post_office" value="<?php echo $val('biz_post_office'); ?>" class="kyw-in" :readonly="sameAddr"></div>
                    <div><label class="kyw-lbl">Block / City / Municipality</label>
                        <input type="text" name="biz_block_city" value="<?php echo $val('biz_block_city'); ?>" class="kyw-in" :readonly="sameAddr"></div>
                    <div><label class="kyw-lbl">Landmark</label>
                        <input type="text" name="biz_landmark" value="<?php echo $val('biz_landmark'); ?>" class="kyw-in" :readonly="sameAddr"></div>
                    <?php echo kyc_state_select('State', 'biz_state', 'kyc_biz_state', $d['biz_state'] ?? ''); ?>
                    <?php echo kyc_district_select('District', 'biz_district', 'kyc_biz_district', $d['biz_district'] ?? ''); ?>
                    <div><label class="kyw-lbl">Pin Code</label>
                        <input type="text" name="biz_pincode" value="<?php echo $val('biz_pincode'); ?>" class="kyw-in" inputmode="numeric" maxlength="6" :readonly="sameAddr"></div>
                </div>

                <div class="kyw-doc mt-5">
                    <div class="kyw-doc-head"><p class="text-sm font-extrabold text-slate-700"><i class="fas fa-file-contract text-emerald-500 mr-1.5"></i>Business Proof</p></div>
                    <p class="text-[11px] text-slate-500 mb-2">Trade licence, GST certificate, Udyam registration or a shop photo.</p>
                    <input type="file" name="business_proof" accept="image/*,application/pdf" class="kyw-file">
                    <?php if (!empty($d['business_proof'])): ?><a href="<?php echo $docUrl($d['business_proof']); ?>" target="_blank" class="inline-flex items-center gap-1 mt-2 text-[11px] font-bold text-emerald-600"><i class="fas fa-circle-check"></i> View uploaded</a><?php endif; ?>
                </div>
            </div>

            </div><!-- /body -->

            <!-- ===== Footer navigation ===== -->
            <div class="px-4 sm:px-6 py-4 border-t border-slate-100 bg-slate-50 flex items-center justify-between gap-3">
                <button type="button" @click="go(step - 1)" x-show="step > 1"
                        class="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl font-bold text-sm text-slate-600 bg-white border border-slate-200 hover:bg-slate-100 transition">
                    <i class="fas fa-arrow-left"></i> Back
                </button>
                <span x-show="step === 1"></span>

                <span class="text-xs font-bold text-slate-400">Step <span x-text="step"></span> of 4</span>

                <button type="button" @click="go(step + 1)" x-show="step < 4"
                        class="inline-flex items-center gap-2 px-6 py-2.5 rounded-xl font-bold text-sm text-white bg-gradient-to-r from-slate-800 to-slate-900 hover:from-slate-900 shadow-md transition">
                    Next <i class="fas fa-arrow-right"></i>
                </button>
                <button type="submit" name="kyc_submit" x-show="step === 4" style="display:none;"
                        class="inline-flex items-center gap-2 px-6 py-2.5 rounded-xl font-bold text-sm text-white bg-gradient-to-r from-emerald-500 to-teal-600 hover:from-emerald-600 shadow-md transition">
                    <i class="fas fa-paper-plane"></i> Submit KYC
                </button>
            </div>
        </form>
    </div>

    <!-- Dependent State/District dropdown loader -->
    <script>
    (function () {
        var pairs = [
            { s: 'kyc_state',     d: 'kyc_district',     sv: <?php echo json_encode($d['state'] ?? ''); ?>,     dv: <?php echo json_encode($d['district'] ?? ''); ?> },
            { s: 'kyc_biz_state', d: 'kyc_biz_district', sv: <?php echo json_encode($d['biz_state'] ?? ''); ?>, dv: <?php echo json_encode($d['biz_district'] ?? ''); ?> }
        ];
        fetch('https://raw.githubusercontent.com/sab99r/Indian-States-And-Districts/master/states-and-districts.json')
            .then(function (r) { return r.json(); })
            .then(function (data) {
                var map = {};
                data.states.forEach(function (it) { map[it.state] = it.districts; });
                pairs.forEach(function (p) {
                    var ss = document.getElementById(p.s), ds = document.getElementById(p.d);
                    if (!ss || !ds) return;
                    ss.innerHTML = '<option value="">Select State</option>';
                    Object.keys(map).forEach(function (st) {
                        var o = document.createElement('option');
                        o.value = st; o.textContent = st;
                        if (st === p.sv) o.selected = true;
                        ss.appendChild(o);
                    });
                    function fillDist(sel) {
                        ds.innerHTML = '<option value="">Select District</option>';
                        (map[sel] || []).forEach(function (dt) {
                            var o = document.createElement('option');
                            o.value = dt; o.textContent = dt;
                            if (dt === p.dv) o.selected = true;
                            ds.appendChild(o);
                        });
                        ds.disabled = false;
                    }
                    if (p.sv) fillDist(p.sv);
                    ss.addEventListener('change', function () { fillDist(ss.value); });
                });
            })
            .catch(function (e) { console.error('State data load failed', e); });
    })();
    </script>

    <!-- Saved lines are locked -->
    <style>
        .kyw-locked { background:#F1F5F9 !important; color:#64748B !important; cursor:not-allowed; }
        .kyw-lockbadge { margin-left:.3rem; font-size:.6rem; font-weight:800; color:#059669;
                         text-transform:none; letter-spacing:0; }
    </style>
    <script>
    (function () {
        var locked = <?php echo json_encode($__locked); ?>;
        function apply() {
            locked.forEach(function (n) {
                var els = document.querySelectorAll('[name="' + n + '"]');
                for (var i = 0; i < els.length; i++) {
                    var el = els[i];
                    el.removeAttribute('required');
                    el.classList.add('kyw-locked');
                    if (el.tagName === 'SELECT' || el.type === 'file' || el.type === 'date') {
                        el.disabled = true;
                    } else {
                        el.readOnly = true;
                    }
                    var box = el.closest('div');
                    var lab = box ? box.querySelector('label') : null;
                    if (lab && !lab.querySelector('.kyw-lockbadge')) {
                        var b = document.createElement('span');
                        b.className = 'kyw-lockbadge';
                        b.innerHTML = '<i class="fas fa-lock"></i> locked';
                        lab.appendChild(b);
                    }
                }
            });
        }
        if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', apply); }
        else { apply(); }
        /* the state / district lists arrive later and re-enable themselves */
        setTimeout(apply, 800); setTimeout(apply, 2500); setTimeout(apply, 6000);
    })();
    </script>
    <?php
    return ob_get_clean();
}

/* ---- Tiny inline sample cards so the member knows what to upload ---- */
function kyc_sample_aadhaar() {
    return '<svg class="kyw-sample" viewBox="0 0 260 164" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Sample Aadhaar card">'
        . '<rect width="260" height="164" rx="8" fill="#FFFFFF" stroke="#E2E8F0"/>'
        . '<rect x="1" y="1" width="258" height="30" rx="7" fill="#FFF7ED"/>'
        . '<circle cx="20" cy="16" r="8" fill="#E11D48"/><circle cx="20" cy="16" r="3.5" fill="#FDE68A"/>'
        . '<rect x="34" y="9" width="96" height="6" rx="3" fill="#9A3412"/>'
        . '<rect x="34" y="19" width="70" height="5" rx="2.5" fill="#C2410C" opacity=".7"/>'
        . '<rect x="205" y="8" width="45" height="16" rx="3" fill="#FDBA74" opacity=".55"/>'
        . '<rect x="14" y="44" width="52" height="62" rx="4" fill="#E2E8F0"/>'
        . '<circle cx="40" cy="66" r="12" fill="#94A3B8"/><path d="M22 104c0-11 8-19 18-19s18 8 18 19z" fill="#94A3B8"/>'
        . '<rect x="78" y="46" width="110" height="7" rx="3.5" fill="#0F172A"/>'
        . '<rect x="78" y="61" width="80" height="5" rx="2.5" fill="#64748B"/>'
        . '<rect x="78" y="74" width="94" height="5" rx="2.5" fill="#64748B"/>'
        . '<rect x="78" y="87" width="60" height="5" rx="2.5" fill="#64748B"/>'
        . '<rect x="196" y="44" width="50" height="50" rx="4" fill="#0F172A" opacity=".08"/>'
        . '<g fill="#0F172A" opacity=".55">'
        . '<rect x="202" y="50" width="10" height="10"/><rect x="230" y="50" width="10" height="10"/>'
        . '<rect x="202" y="78" width="10" height="10"/><rect x="218" y="64" width="6" height="6"/>'
        . '<rect x="230" y="72" width="6" height="6"/><rect x="216" y="82" width="6" height="6"/></g>'
        . '<rect x="1" y="120" width="258" height="43" rx="7" fill="#F8FAFC"/>'
        . '<rect x="60" y="132" width="140" height="14" rx="4" fill="#0F172A" opacity=".08"/>'
        . '<text x="130" y="143" text-anchor="middle" font-family="monospace" font-size="13" font-weight="700" fill="#334155" letter-spacing="2">1234 5678 9012</text>'
        . '</svg>';
}

function kyc_sample_pan() {
    return '<svg class="kyw-sample" viewBox="0 0 260 164" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Sample PAN card">'
        . '<rect width="260" height="164" rx="8" fill="#EFF6FF" stroke="#E2E8F0"/>'
        . '<rect x="1" y="1" width="258" height="26" rx="7" fill="#DBEAFE"/>'
        . '<circle cx="18" cy="14" r="7" fill="#1D4ED8" opacity=".6"/>'
        . '<rect x="32" y="8" width="120" height="5" rx="2.5" fill="#1E3A8A"/>'
        . '<rect x="32" y="17" width="86" height="4" rx="2" fill="#1D4ED8" opacity=".7"/>'
        . '<rect x="16" y="40" width="70" height="6" rx="3" fill="#1E3A8A"/>'
        . '<text x="16" y="66" font-family="monospace" font-size="17" font-weight="700" fill="#0F172A" letter-spacing="3">ABCDE1234F</text>'
        . '<rect x="16" y="80" width="46" height="4" rx="2" fill="#64748B"/>'
        . '<rect x="16" y="92" width="96" height="6" rx="3" fill="#0F172A"/>'
        . '<rect x="16" y="110" width="46" height="4" rx="2" fill="#64748B"/>'
        . '<rect x="16" y="121" width="78" height="6" rx="3" fill="#0F172A"/>'
        . '<rect x="16" y="140" width="60" height="4" rx="2" fill="#64748B"/>'
        . '<rect x="186" y="42" width="58" height="70" rx="4" fill="#CBD5E1"/>'
        . '<circle cx="215" cy="68" r="13" fill="#94A3B8"/><path d="M196 110c0-12 8-21 19-21s19 9 19 21z" fill="#94A3B8"/>'
        . '<path d="M188 132c10-8 18 6 28-2s16 4 26-3" stroke="#1E3A8A" stroke-width="2" fill="none" opacity=".7"/>'
        . '</svg>';
}


/* ---- Modal open / close wrappers ---- */
function kyc_modal_head($key, $title, $icon, $grad) {
    $q = "'";
    return '<div x-show="kycModal===' . $q . $key . $q . '" x-transition.opacity style="display:none;" class="fixed inset-0 z-[100] flex items-center justify-center p-4">'
        . '<div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="kycModal=null"></div>'
        . '<form method="POST" enctype="multipart/form-data" class="relative w-full max-w-3xl bg-white rounded-2xl shadow-2xl max-h-[90vh] flex flex-col">'
        . '<input type="hidden" name="kyc_section" value="' . $key . '">'
        . '<div class="px-6 py-4 bg-gradient-to-r ' . $grad . ' flex items-center justify-between flex-shrink-0">'
        . '<h4 class="text-white font-extrabold tracking-wide text-lg"><i class="fas ' . $icon . ' mr-2"></i>' . strtoupper($title) . '</h4>'
        . '<button type="button" @click="kycModal=null" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>'
        . '</div><div class="p-6 overflow-y-auto">';
}
function kyc_modal_foot($color) {
    $grad = [
        'amber'   => 'from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600',
        'blue'    => 'from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700',
        'rose'    => 'from-rose-500 to-pink-500 hover:from-rose-600 hover:to-pink-600',
        'emerald' => 'from-emerald-500 to-teal-500 hover:from-emerald-600 hover:to-teal-600',
    ];
    $g = $grad[$color] ?? 'from-blue-600 to-indigo-600';
    return '</div><div class="px-6 py-4 border-t border-slate-100 bg-slate-50 flex justify-end gap-2 flex-shrink-0">'
        . '<button type="button" @click="kycModal=null" class="px-5 py-2.5 rounded-xl font-semibold text-slate-600 hover:bg-slate-200 transition">Cancel</button>'
        . '<button type="submit" name="kyc_submit" class="inline-flex items-center gap-2 px-6 py-2.5 rounded-xl text-white font-bold shadow-md bg-gradient-to-r ' . $g . ' transition-all"><i class="fas fa-floppy-disk"></i> Update</button>'
        . '</div></form></div>';
}

/* ---- Field helpers ---- */
function kyc_input($label, $name, $value, $type = 'text') {
    return '<div><label class="block text-xs font-bold text-slate-600 uppercase tracking-wide mb-1">' . htmlspecialchars($label) . '</label>'
        . '<input type="' . $type . '" name="' . $name . '" value="' . $value . '" class="w-full px-4 py-2.5 bg-white border border-slate-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"></div>';
}
function kyc_select($label, $name, $value) {
    $opts = ['male' => 'Male', 'female' => 'Female', 'other' => 'Other'];
    $h = '<div><label class="kyw-lbl">' . htmlspecialchars($label) . '</label>'
        . '<select name="' . $name . '" class="kyw-in">';
    foreach ($opts as $k => $v) { $h .= '<option value="' . $k . '"' . ($value === $k ? ' selected' : '') . '>' . $v . '</option>'; }
    return $h . '</select></div>';
}
function kyc_state_select($label, $name, $id, $selected) {
    return '<div><label class="kyw-lbl">' . htmlspecialchars($label) . '</label>'
        . '<select name="' . $name . '" id="' . $id . '" class="kyw-in">'
        . '<option value="">Select State</option>'
        . (!empty($selected) ? '<option value="' . htmlspecialchars($selected, ENT_QUOTES) . '" selected>' . htmlspecialchars($selected) . '</option>' : '')
        . '</select></div>';
}
function kyc_district_select($label, $name, $id, $selected) {
    return '<div><label class="kyw-lbl">' . htmlspecialchars($label) . '</label>'
        . '<select name="' . $name . '" id="' . $id . '" class="kyw-in">'
        . '<option value="">Select District</option>'
        . (!empty($selected) ? '<option value="' . htmlspecialchars($selected, ENT_QUOTES) . '" selected>' . htmlspecialchars($selected) . '</option>' : '')
        . '</select></div>';
}
function kyc_file($label, $name, $existing, $docUrl) {
    $h = '<div class="bg-white border border-slate-300 rounded-lg p-3">'
        . '<label class="block text-[11px] font-bold text-slate-600 mb-1.5">' . htmlspecialchars($label) . '</label>'
        . '<input type="file" name="' . $name . '" accept="image/*,application/pdf" class="w-full text-[11px] text-slate-500 file:mr-2 file:py-1 file:px-2 file:rounded file:border-0 file:bg-blue-50 file:text-blue-700 file:font-semibold file:text-[11px]">';
    if (!empty($existing)) {
        $h .= '<a href="' . $docUrl($existing) . '" target="_blank" class="inline-flex items-center gap-1 mt-2 text-[11px] font-bold text-emerald-600 hover:text-emerald-700"><i class="fas fa-circle-check"></i> View uploaded</a>';
    }
    return $h . '</div>';
}
