<?php
/* ============================================================================
   WBMCZ — Field level KYC requirements

   A product no longer asks for a whole "Address Details" section: the admin
   ticks the exact boxes it needs — village, pincode, IFSC, Aadhaar number,
   or one of their own questions. When a customer tries to buy, only the
   boxes they have NOT filled yet are shown in the popup.

   Key format used in `seller_services.required_kyc`
       personal.aadhar_number      a column of kyc_details
       address.pincode
       custom.7                    a question the admin wrote themselves
       address                     (legacy) the whole section — still works,
                                   it simply expands to all of its fields
   ============================================================================ */

if (!function_exists('kycf_ensure_schema')) {

function kycf_ensure_schema($db) {
    static $done = false;
    if ($done) return;
    $done = true;

    $conn = $db->getConnection();
    try {
        $conn->query("CREATE TABLE IF NOT EXISTS kyc_custom_fields (
            id INT AUTO_INCREMENT PRIMARY KEY,
            field_label VARCHAR(200) NOT NULL,
            field_label_bn VARCHAR(200) NULL,
            field_type VARCHAR(20) NOT NULL DEFAULT 'text',
            options TEXT NULL,
            placeholder VARCHAR(200) NULL,
            help_text VARCHAR(255) NULL,
            group_name VARCHAR(60) NOT NULL DEFAULT 'Additional Information',
            display_order INT NOT NULL DEFAULT 0,
            status TINYINT(1) NOT NULL DEFAULT 1,
            created_by INT NULL,
            created_by_name VARCHAR(120) NULL,
            created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
            KEY idx_kcf_live (status, display_order)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    } catch (\Throwable $e) {}

    try {
        $conn->query("CREATE TABLE IF NOT EXISTS kyc_custom_values (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            field_id INT NOT NULL,
            value TEXT NULL,
            file_path VARCHAR(255) NULL,
            created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT NULL,
            UNIQUE KEY uniq_kcv (user_id, field_id),
            KEY idx_kcv_user (user_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    } catch (\Throwable $e) {}
}

/* ---------------------------------------------------------------------------
   The built-in fields, grouped exactly the way the KYC wizard shows them
   --------------------------------------------------------------------------- */
function kycf_builtin() {
    return [
        'personal' => [
            'label'  => 'Personal Details',
            'icon'   => 'fa-user',
            'fields' => [
                'full_name'      => 'Full name',
                'gender'         => 'Gender',
                'dob'            => 'Date of birth',
                'father_name'    => "Father's name",
                'email'          => 'Email',
                'phone_number'   => 'Phone number',
                'aadhar_number'  => 'Aadhaar number',
                'pancard_number' => 'PAN number',
                'aadhar_front'   => 'Aadhaar — front photo',
                'aadhar_back'    => 'Aadhaar — back photo',
                'pan_card'       => 'PAN card photo',
                'photo'          => 'Passport photo',
            ],
        ],
        'address' => [
            'label'  => 'Address Details',
            'icon'   => 'fa-location-dot',
            'fields' => [
                'village'       => 'Village / Locality',
                'post_office'   => 'Post office',
                'block_city'    => 'Block / City / Municipality',
                'landmark'      => 'Landmark',
                'district'      => 'District',
                'state'         => 'State',
                'pincode'       => 'Pin code',
                'address_proof' => 'Address proof document',
            ],
        ],
        'bank' => [
            'label'  => 'Bank Details',
            'icon'   => 'fa-building-columns',
            'fields' => [
                'bank_name'      => 'Bank name',
                'branch_name'    => 'Branch name',
                'account_number' => 'Account number',
                'ifsc_code'      => 'IFSC code',
                'bank_passbook'  => 'Passbook / cheque photo',
            ],
        ],
        'business' => [
            'label'  => 'Business Details',
            'icon'   => 'fa-store',
            'fields' => [
                'business_name'   => 'Business name',
                'business_phone'  => 'Business phone',
                'business_email'  => 'Business email',
                'biz_village'     => 'Business village / locality',
                'biz_post_office' => 'Business post office',
                'biz_block_city'  => 'Business block / city',
                'biz_landmark'    => 'Business landmark',
                'biz_district'    => 'Business district',
                'biz_state'       => 'Business state',
                'biz_pincode'     => 'Business pin code',
                'business_proof'  => 'Business proof document',
            ],
        ],
    ];
}

/* Which built-in fields are photo uploads (they live in the same table) */
function kycf_file_fields() {
    return ['aadhar_front', 'aadhar_back', 'pan_card', 'photo', 'address_proof', 'bank_passbook', 'business_proof'];
}

/* The admin's own questions, live ones only unless $all */
function kycf_custom_list($db, $all = false) {
    kycf_ensure_schema($db);
    try {
        $w = $all ? '' : 'WHERE status = 1';
        return $db->select("SELECT * FROM kyc_custom_fields $w ORDER BY display_order ASC, id ASC");
    } catch (\Throwable $e) { return []; }
}

/**
 * Everything an admin can tick, as one tree:
 *   [ group_key => ['label'=>.., 'icon'=>.., 'fields'=> [full_key => label]] ]
 */
function kycf_catalog($db) {
    $out = [];
    foreach (kycf_builtin() as $sec => $def) {
        $fields = [];
        foreach ($def['fields'] as $col => $label) { $fields[$sec . '.' . $col] = $label; }
        $out[$sec] = ['label' => $def['label'], 'icon' => $def['icon'], 'fields' => $fields];
    }

    $custom = kycf_custom_list($db);
    if (!empty($custom)) {
        $groups = [];
        foreach ($custom as $c) {
            $g = trim((string)$c['group_name']) !== '' ? $c['group_name'] : 'Additional Information';
            $groups[$g]['custom.' . (int)$c['id']] = $c['field_label'];
        }
        $i = 0;
        foreach ($groups as $g => $fields) {
            $out['custom_' . (++$i)] = ['label' => $g, 'icon' => 'fa-list-check', 'fields' => $fields];
        }
    }
    return $out;
}

/* key => label for everything in the catalog, flattened */
function kycf_flat_labels($db) {
    static $flat = null;
    if ($flat !== null) return $flat;
    $flat = [];
    foreach (kycf_catalog($db) as $g) {
        foreach ($g['fields'] as $k => $l) { $flat[$k] = $l; }
    }
    return $flat;
}

/* One readable label for a stored key (works for legacy section keys too) */
function kycf_label($db, $key) {
    $sections = kycf_builtin();
    if (isset($sections[$key])) return $sections[$key]['label'];
    $flat = kycf_flat_labels($db);
    if (isset($flat[$key])) return $flat[$key];
    return ucwords(str_replace(['_', '.'], [' ', ' — '], (string)$key));
}

/**
 * Turn what the admin saved into a flat list of individual field keys.
 * A bare section key ('address') expands to every field in that section, so
 * old products keep working and simply become more precise.
 */
function kycf_expand($db, $keys) {
    $sections = kycf_builtin();
    $out = [];
    foreach ((array)$keys as $k) {
        $k = trim((string)$k);
        if ($k === '') continue;
        if (isset($sections[$k])) {
            foreach (array_keys($sections[$k]['fields']) as $col) { $out[] = $k . '.' . $col; }
        } else {
            $out[] = $k;
        }
    }
    return array_values(array_unique($out));
}

/* The custom answers a user has already given: field_id => value */
function kycf_user_values($db, $user_id) {
    static $cache = [];
    $k = (int)$user_id;
    if (array_key_exists($k, $cache)) return $cache[$k];
    kycf_ensure_schema($db);
    $out = [];
    try {
        $r = $db->select("SELECT field_id, value, file_path FROM kyc_custom_values WHERE user_id = ?", [$k]);
        foreach ($r as $row) {
            $v = trim((string)$row['value']);
            if ($v === '') { $v = trim((string)$row['file_path']); }
            $out[(int)$row['field_id']] = $v;
        }
    } catch (\Throwable $e) {}
    return $cache[$k] = $out;
}

function kycf_save_value($db, $user_id, $field_id, $value, $file = '') {
    kycf_ensure_schema($db);
    try {
        $db->insert("INSERT INTO kyc_custom_values (user_id, field_id, value, file_path, updated_at)
                     VALUES (?,?,?,?,NOW())
                     ON DUPLICATE KEY UPDATE value = VALUES(value),
                                             file_path = IF(VALUES(file_path) = '', file_path, VALUES(file_path)),
                                             updated_at = NOW()",
            [(int)$user_id, (int)$field_id, (string)$value, (string)$file]);
        return true;
    } catch (\Throwable $e) { return false; }
}

/**
 * Which of the required keys has this user NOT filled in yet?
 * $kyc_row is the kyc_details row (pass it in to avoid a second query).
 */
function kycf_missing($db, $user_id, $required_keys, $kyc_row = null) {
    if (empty($required_keys)) return [];

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

    $missing = [];
    foreach ($required_keys as $key) {
        if (strpos($key, 'custom.') === 0) {
            $fid = (int)substr($key, 7);
            if (empty($custom[$fid])) { $missing[] = $key; }
            continue;
        }
        $parts = explode('.', $key, 2);
        $col   = $parts[1] ?? '';
        if ($col === '') { continue; }
        if (empty($kyc_row[$col])) { $missing[] = $key; }
    }
    return $missing;
}

/* Group the keys for display: ['Address Details' => ['Village', 'Pin code']] */
function kycf_group_labels($db, $keys) {
    $sections = kycf_builtin();
    $custom   = [];
    foreach (kycf_custom_list($db, true) as $c) { $custom[(int)$c['id']] = $c; }

    $out = [];
    foreach ((array)$keys as $key) {
        if (strpos($key, 'custom.') === 0) {
            $fid = (int)substr($key, 7);
            $g   = isset($custom[$fid]) ? ($custom[$fid]['group_name'] ?: 'Additional Information') : 'Additional Information';
            $out[$g][] = isset($custom[$fid]) ? $custom[$fid]['field_label'] : $key;
            continue;
        }
        $parts = explode('.', $key, 2);
        $sec   = $parts[0];
        $col   = $parts[1] ?? '';
        $g     = $sections[$sec]['label'] ?? ucfirst($sec);
        $out[$g][] = $sections[$sec]['fields'][$col] ?? $col;
    }
    return $out;
}

} // end function_exists guard
