<?php
/* ============================================================================
   WBMCZ — Admin · KYC Questions

   Your own questions, on top of the standard KYC. Tick one against a product
   in Product Management → Customer Data Recruitment and the buyer is asked
   for it before they can purchase.
   ============================================================================ */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';
require_once __DIR__ . '/../includes/admin_list.php';
require_once __DIR__ . '/../includes/rbac.php';
require_once __DIR__ . '/../includes/kyc_fields.php';

if (!isLoggedIn() || !isAdmin()) { redirect('login.php'); }
rbac_guard('manage_services');

$lang         = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id      = (int)$_SESSION['user_id'];

$can_users        = hasPermission('manage_users');
$can_sellers      = hasPermission('manage_sellers');
$can_staff        = hasPermission('manage_staff_roles');
$can_services     = hasPermission('manage_services');
$can_orders       = hasPermission('manage_orders');
$can_transactions = hasPermission('manage_transactions');
$can_tickets      = hasPermission('manage_tickets');
$can_settings     = hasPermission('manage_settings');

kycf_ensure_schema($db);

$me_row = $db->select("SELECT id, name FROM users WHERE id = ?", [$user_id]);
$me     = !empty($me_row) ? $me_row[0] : ['id' => $user_id, 'name' => 'Admin'];

if (isset($_SESSION['flash_success'])) { $success_msg = $_SESSION['flash_success']; unset($_SESSION['flash_success']); }
if (isset($_SESSION['flash_error']))   { $error_msg   = $_SESSION['flash_error'];   unset($_SESSION['flash_error']); }

/* ---------------------------------------------------------------------------
   Save / update / delete
   --------------------------------------------------------------------------- */
if (isset($_POST['save_field'])) {
    $fid   = (int)($_POST['field_id'] ?? 0);
    $label = sanitize($_POST['field_label'] ?? '');
    if ($label === '') {
        $_SESSION['flash_error'] = 'The question needs a label.';
        redirect('kyc_fields.php');
    }
    $type = in_array($_POST['field_type'] ?? 'text', ['text', 'number', 'date', 'email', 'select', 'textarea', 'file'], true)
            ? $_POST['field_type'] : 'text';

    $args = [
        $label,
        sanitize($_POST['field_label_bn'] ?? ''),
        $type,
        sanitize($_POST['options'] ?? ''),
        sanitize($_POST['placeholder'] ?? ''),
        sanitize($_POST['help_text'] ?? ''),
        sanitize($_POST['group_name'] ?? '') !== '' ? sanitize($_POST['group_name']) : 'Additional Information',
        (int)($_POST['display_order'] ?? 0),
        ((int)($_POST['status'] ?? 1) === 1) ? 1 : 0,
    ];

    if ($fid > 0) {
        $args[] = $fid;
        $db->insert("UPDATE kyc_custom_fields SET field_label = ?, field_label_bn = ?, field_type = ?, options = ?,
                            placeholder = ?, help_text = ?, group_name = ?, display_order = ?, status = ?
                     WHERE id = ?", $args);
        $_SESSION['flash_success'] = 'Question updated.';
    } else {
        $args[] = $me['id'];
        $args[] = $me['name'];
        $db->insert("INSERT INTO kyc_custom_fields (field_label, field_label_bn, field_type, options, placeholder,
                            help_text, group_name, display_order, status, created_by, created_by_name)
                     VALUES (?,?,?,?,?,?,?,?,?,?,?)", $args);
        $_SESSION['flash_success'] = 'Question added — you can now tick it against any product.';
    }
    redirect('kyc_fields.php');
}

if (isset($_POST['toggle_field'])) {
    $db->insert("UPDATE kyc_custom_fields SET status = IF(status = 1, 0, 1) WHERE id = ?", [(int)$_POST['field_id']]);
    $_SESSION['flash_success'] = 'Question visibility changed.';
    redirect('kyc_fields.php');
}

if (isset($_POST['delete_field'])) {
    $fid = (int)$_POST['field_id'];
    $db->insert("DELETE FROM kyc_custom_values WHERE field_id = ?", [$fid]);
    $db->insert("DELETE FROM kyc_custom_fields WHERE id = ?", [$fid]);
    $_SESSION['flash_success'] = 'Question deleted along with the answers given to it.';
    redirect('kyc_fields.php');
}

/* ---------------------------------------------------------------------------
   Data
   --------------------------------------------------------------------------- */
$fields = kycf_custom_list($db, true);

/* how many members answered each one, and which products ask for it */
$answers = [];
try {
    foreach ($db->select("SELECT field_id, COUNT(*) c FROM kyc_custom_values WHERE value <> '' OR file_path <> '' GROUP BY field_id") as $r) {
        $answers[(int)$r['field_id']] = (int)$r['c'];
    }
} catch (\Throwable $e) {}

$used = [];
try {
    foreach ($db->select("SELECT id, title, required_kyc FROM seller_services WHERE required_kyc LIKE '%custom.%'") as $r) {
        foreach (array_filter(array_map('trim', explode(',', (string)$r['required_kyc']))) as $k) {
            if (strpos($k, 'custom.') === 0) { $used[(int)substr($k, 7)][] = $r['title']; }
        }
    }
} catch (\Throwable $e) {}

$live = 0;
foreach ($fields as $f) { if ((int)$f['status'] === 1) $live++; }
$next_order = 0;
foreach ($fields as $f) { $next_order = max($next_order, (int)$f['display_order']); }
$next_order++;

$company_logo = getSetting('company_logo', '../assets/images/logo.png');
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KYC Questions - Admin Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&family=Hind+Siliguri:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family:'Inter','Hind Siliguri',sans-serif; }
        .lbl { display:block; font-size:10px; font-weight:800; color:#64748b; margin-bottom:.25rem; text-transform:uppercase; letter-spacing:.05em; }
        .fld { width:100%; padding:.6rem .75rem; background:#fff; border:1.5px solid #cbd5e1; border-radius:.75rem; font-size:.82rem; outline:none; color:#0f172a; }
        .fld:focus { border-color:#6366f1; box-shadow:0 0 0 3px rgba(99,102,241,.14); }
        .qcard { background:#fff; border:1px solid #e2e8f0; border-radius:1rem; padding:1rem 1.1rem; }
        .pill { display:inline-flex; align-items:center; gap:.25rem; padding:.15rem .55rem; border-radius:999px;
                font-size:9.5px; font-weight:900; text-transform:uppercase; letter-spacing:.04em; }
        .cbtn { display:inline-flex; align-items:center; justify-content:center; gap:.3rem; padding:.4rem .7rem;
                border-radius:.6rem; font-size:11px; font-weight:800; color:#fff; border:0; cursor:pointer; }
    </style>
</head>
<body class="bg-gray-50" x-data="qApp()">
<div class="flex h-screen overflow-hidden">

    <?php include __DIR__ . '/includes/sidebar.php'; ?>

    <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">
        <header class="h-20 bg-white text-slate-800 flex items-center justify-between px-4 shadow-sm border-b border-gray-200 z-40 relative">
            <div class="flex items-center">
                <button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-emerald-600 rounded-lg"><i class="fas fa-bars text-xl"></i></button>
                <h2 class="text-xl font-bold hidden md:block text-slate-800">KYC Questions</h2>
            </div>
            <button type="button" @click="openAdd()" class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-gradient-to-r from-violet-600 to-indigo-600 text-white text-sm font-bold shadow">
                <i class="fas fa-plus"></i> Add Question
            </button>
        </header>

        <main class="flex-1 overflow-y-auto p-4 md:p-6">
            <?php echo alist_styles(); ?>

            <?php if (isset($success_msg)): ?>
            <div class="mb-5 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl flex items-center shadow-sm">
                <i class="fas fa-check-circle mr-2"></i><span class="font-medium"><?php echo htmlspecialchars($success_msg); ?></span>
            </div>
            <?php endif; ?>
            <?php if (isset($error_msg)): ?>
            <div class="mb-5 bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl flex items-center shadow-sm">
                <i class="fas fa-triangle-exclamation mr-2"></i><span class="font-medium"><?php echo htmlspecialchars($error_msg); ?></span>
            </div>
            <?php endif; ?>

            <div class="mb-5">
                <h2 class="text-2xl font-bold text-slate-800 mb-1">Your own KYC questions</h2>
                <p class="text-gray-500 text-sm">
                    Anything the standard KYC does not cover — a shop photo, a GST number, a reference name.
                    Add it here, then tick it against the products that need it in
                    <a href="product_management.php" class="text-indigo-600 font-bold">Product Management → Customer Data Recruitment</a>.
                    Members answer them on their <b>Additional Information</b> page.
                </p>
            </div>

            <?php echo alist_stats([
                ['label' => 'Questions', 'value' => count($fields), 'icon' => 'fa-list-check', 'colour' => 'violet'],
                ['label' => 'Live',      'value' => $live,          'icon' => 'fa-circle-check', 'colour' => 'emerald'],
                ['label' => 'Hidden',    'value' => count($fields) - $live, 'icon' => 'fa-eye-slash', 'colour' => 'slate'],
            ]); ?>

            <?php if (empty($fields)): ?>
                <div class="bg-white border border-dashed border-slate-300 rounded-2xl p-10 text-center">
                    <i class="fas fa-list-check text-4xl text-slate-300 mb-3"></i>
                    <p class="font-bold text-slate-700">No custom questions yet</p>
                    <p class="text-sm text-slate-500 mb-4">The standard KYC boxes are always available — add a question here only when you need something extra.</p>
                    <button type="button" @click="openAdd()" class="px-5 py-2.5 rounded-xl bg-violet-600 text-white text-sm font-bold"><i class="fas fa-plus mr-1"></i>Add Question</button>
                </div>
            <?php else: ?>
                <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                    <?php foreach ($fields as $f):
                        $fid = (int)$f['id'];
                        $js  = json_encode($f, JSON_HEX_APOS | JSON_HEX_QUOT);
                    ?>
                    <div class="qcard flex flex-col">
                        <div class="flex items-start justify-between gap-2 mb-1">
                            <p class="text-[9.5px] font-black uppercase tracking-widest text-violet-500"><?php echo esc($f['group_name']); ?></p>
                            <span class="pill <?php echo (int)$f['status'] === 1 ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-500'; ?>">
                                <?php echo (int)$f['status'] === 1 ? 'Live' : 'Hidden'; ?>
                            </span>
                        </div>
                        <p class="font-extrabold text-slate-800 leading-snug"><?php echo esc($f['field_label']); ?></p>
                        <?php if (!empty($f['field_label_bn'])): ?>
                            <p class="text-[12px] text-slate-500"><?php echo esc($f['field_label_bn']); ?></p>
                        <?php endif; ?>
                        <?php if (!empty($f['help_text'])): ?>
                            <p class="text-[11px] text-slate-400 mt-1"><?php echo esc($f['help_text']); ?></p>
                        <?php endif; ?>

                        <div class="flex flex-wrap gap-1.5 mt-3">
                            <span class="pill bg-slate-100 text-slate-600"><i class="fas fa-keyboard"></i><?php echo esc($f['field_type']); ?></span>
                            <span class="pill bg-sky-50 text-sky-700"><i class="fas fa-users"></i><?php echo (int)($answers[$fid] ?? 0); ?> answered</span>
                            <span class="pill bg-amber-50 text-amber-700"><i class="fas fa-box"></i><?php echo count($used[$fid] ?? []); ?> product(s)</span>
                            <span class="pill bg-slate-50 text-slate-400">key: custom.<?php echo $fid; ?></span>
                        </div>

                        <?php if (!empty($used[$fid])): ?>
                            <p class="text-[10.5px] text-slate-400 mt-2 line-clamp-2">Asked for by: <?php echo esc(implode(', ', array_slice($used[$fid], 0, 4))); ?></p>
                        <?php endif; ?>

                        <div class="flex flex-wrap gap-1.5 mt-auto pt-3">
                            <button type="button" @click='openEdit(<?php echo $js; ?>)' class="cbtn bg-indigo-600 hover:bg-indigo-700"><i class="fas fa-pen"></i> Edit</button>
                            <form method="POST" class="inline">
                                <input type="hidden" name="field_id" value="<?php echo $fid; ?>">
                                <button type="submit" name="toggle_field" value="1" class="cbtn <?php echo (int)$f['status'] === 1 ? 'bg-slate-500 hover:bg-slate-600' : 'bg-emerald-600 hover:bg-emerald-700'; ?>">
                                    <i class="fas <?php echo (int)$f['status'] === 1 ? 'fa-eye-slash' : 'fa-eye'; ?>"></i>
                                    <?php echo (int)$f['status'] === 1 ? 'Hide' : 'Show'; ?>
                                </button>
                            </form>
                            <form method="POST" class="inline ml-auto" onsubmit="return confirm('Delete this question and every answer given to it?')">
                                <input type="hidden" name="field_id" value="<?php echo $fid; ?>">
                                <button type="submit" name="delete_field" value="1" class="cbtn bg-rose-600 hover:bg-rose-700"><i class="fas fa-trash"></i></button>
                            </form>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </main>
    </div>
</div>

<template x-teleport="body">
<div x-show="modal" x-transition.opacity class="fixed inset-0 z-[100] flex items-center justify-center p-4" style="display:none;">
    <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="modal = false"></div>
    <div class="relative w-full max-w-xl bg-white rounded-2xl shadow-2xl overflow-hidden max-h-[92vh] flex flex-col">
        <div class="bg-gradient-to-r from-violet-600 to-indigo-600 px-5 py-4 flex items-center justify-between flex-shrink-0">
            <h3 class="text-white font-bold text-lg"><i class="fas fa-list-check mr-2"></i><span x-text="mode==='add' ? 'Add Question' : 'Edit Question'"></span></h3>
            <button @click="modal = false" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>
        </div>
        <form method="POST" class="flex flex-col overflow-hidden">
            <input type="hidden" name="field_id" :value="f.id">
            <div class="p-5 overflow-y-auto space-y-4">
                <div><label class="lbl">Question / label <span class="text-rose-500">*</span></label>
                    <input name="field_label" x-model="f.field_label" class="fld" required placeholder="e.g. GST number, Shop photo, Reference name"></div>
                <div><label class="lbl">Same in Bengali <span class="text-slate-400 normal-case font-medium">(optional)</span></label>
                    <input name="field_label_bn" x-model="f.field_label_bn" class="fld" placeholder="যেমন — দোকানের ছবি"></div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
                    <div><label class="lbl">Answer type</label>
                        <select name="field_type" x-model="f.field_type" class="fld">
                            <option value="text">Short text</option>
                            <option value="textarea">Long text</option>
                            <option value="number">Number</option>
                            <option value="date">Date</option>
                            <option value="email">Email</option>
                            <option value="select">Choose from a list</option>
                            <option value="file">File / photo upload</option>
                        </select></div>
                    <div><label class="lbl">Group heading</label>
                        <input name="group_name" x-model="f.group_name" class="fld" placeholder="Additional Information"></div>
                    <div><label class="lbl">Order</label><input type="number" name="display_order" x-model="f.display_order" class="fld"></div>
                </div>

                <div x-show="f.field_type === 'select'" style="display:none">
                    <label class="lbl">Choices — separate with commas</label>
                    <input name="options" x-model="f.options" class="fld" placeholder="Own shop, Rented shop, Home based">
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <div><label class="lbl">Placeholder</label><input name="placeholder" x-model="f.placeholder" class="fld"></div>
                    <div><label class="lbl">Status</label>
                        <select name="status" x-model="f.status" class="fld"><option value="1">Live</option><option value="0">Hidden</option></select></div>
                </div>

                <div><label class="lbl">Helper line under the box</label>
                    <input name="help_text" x-model="f.help_text" class="fld" placeholder="Shown in small grey text to the member"></div>

                <div class="text-[11px] bg-violet-50 border border-violet-100 text-violet-700 rounded-xl p-3 leading-relaxed">
                    <i class="fas fa-circle-info mr-1"></i>
                    Once saved, tick this question against a product in <b>Product Management → Customer Data Recruitment</b>.
                    The buyer then sees it in the purchase popup until it is answered.
                </div>
            </div>
            <div class="flex justify-end gap-2 px-5 py-4 border-t bg-slate-50 flex-shrink-0">
                <button type="button" @click="modal = false" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-200 rounded-lg">Cancel</button>
                <button type="submit" name="save_field" value="1" class="px-5 py-2 text-sm font-bold text-white bg-violet-600 hover:bg-violet-700 rounded-lg shadow"><i class="fas fa-save mr-1"></i>Save</button>
            </div>
        </form>
    </div>
</div>
</template>

<script>
function qApp() {
    return {
        sidebarOpen: window.innerWidth >= 768,
        modal: false, mode: 'add', f: {},
        blank() {
            return { id: '', field_label: '', field_label_bn: '', field_type: 'text', options: '',
                     placeholder: '', help_text: '', group_name: 'Additional Information',
                     display_order: <?php echo (int)$next_order; ?>, status: '1' };
        },
        openAdd() { this.f = this.blank(); this.mode = 'add'; this.modal = true; },
        openEdit(row) {
            const b = this.blank();
            Object.keys(b).forEach(k => { b[k] = (row[k] === null || row[k] === undefined) ? '' : String(row[k]); });
            this.f = b; this.mode = 'edit'; this.modal = true;
        }
    }
}
</script>
</body>
</html>
