<?php
/* ============================================================================
   WBMCZ — Additional Information

   The questions an admin wrote in Admin → Service Management → KYC Questions.
   A member answers them here, and a product that asks for one of these
   answers unlocks as soon as it is filled in.
   ============================================================================ */
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/kyc_fields.php';

if (!isLoggedIn()) { redirect('login.php'); }

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

$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($user_data) ? $user_data[0] : null;
if (!$user) { session_destroy(); redirect('login.php'); }

kycf_ensure_schema($db);

$fields = kycf_custom_list($db);

/* ---------------------------------------------------------------------------
   Save
   --------------------------------------------------------------------------- */
if (isset($_POST['save_extra'])) {
    $saved = 0;

    /* Once an answer is on the record it is locked — only the office can
       change it. Read it straight from the table, not through the cache. */
    $locked = [];
    try {
        foreach ($db->select("SELECT field_id, value, file_path FROM kyc_custom_values WHERE user_id = ?", [$user_id]) as $__r) {
            $__v = trim((string)$__r['value']);
            if ($__v === '') { $__v = trim((string)$__r['file_path']); }
            if ($__v !== '') { $locked[(int)$__r['field_id']] = true; }
        }
    } catch (\Throwable $e) {}

    foreach ($fields as $f) {
        $fid  = (int)$f['id'];
        if (!empty($locked[$fid])) { continue; }
        $key  = 'f_' . $fid;
        $file = '';

        if ($f['field_type'] === 'file') {
            if (!empty($_FILES[$key]['name']) && is_uploaded_file($_FILES[$key]['tmp_name'])) {
                $ext = strtolower(pathinfo($_FILES[$key]['name'], PATHINFO_EXTENSION));
                if (in_array($ext, ['jpg', 'jpeg', 'png', 'webp', 'pdf'], true)) {
                    $dir = __DIR__ . '/uploads/kyc_extra/';
                    if (!is_dir($dir)) { @mkdir($dir, 0777, true); }
                    $name = 'x' . $user_id . '_' . $fid . '_' . time() . '.' . $ext;
                    if (move_uploaded_file($_FILES[$key]['tmp_name'], $dir . $name)) {
                        $file = 'uploads/kyc_extra/' . $name;
                    }
                }
            }
            if ($file !== '') { kycf_save_value($db, $user_id, $fid, $file, $file); $saved++; }
            continue;
        }

        if (isset($_POST[$key])) {
            $val = sanitize($_POST[$key]);
            kycf_save_value($db, $user_id, $fid, $val);
            if ($val !== '') $saved++;
        }
    }
    $_SESSION['flash_success'] = $saved > 0
        ? 'Saved — thank you. Any service waiting on this information is unlocked now.'
        : 'Nothing was filled in.';
    redirect('kyc_extra.php');
}

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

$values = kycf_user_values($db, $user_id);

/* group them the way the admin arranged them */
$groups = [];
foreach ($fields as $f) {
    $g = trim((string)$f['group_name']) !== '' ? $f['group_name'] : 'Additional Information';
    $groups[$g][] = $f;
}

$done = 0;
foreach ($fields as $f) { if (!empty($values[(int)$f['id']])) $done++; }
$pct = count($fields) > 0 ? (int)round($done / count($fields) * 100) : 100;

$unread_notifs  = $db->select("SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5", [$user_id]);
$wallet_balance = isset($user['wallet_balance']) ? $user['wallet_balance'] : '0.00';
$company_logo   = getSetting('company_logo', 'assets/images/logo.png');
$company_logo   = (strpos($company_logo, 'http') === 0) ? $company_logo : ltrim($company_logo, '/');
$company_name   = getSetting('company_name', 'WBMCZ');

$all_categories  = $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");
$sidebar_subcats = [1 => [], 5 => []];
foreach ($db->select("SELECT id, category_id, title, icon_class FROM agency_sub_categories WHERE category_id IN (1,5) AND status = 1 ORDER BY category_id, id") as $__r) {
    $sidebar_subcats[$__r['category_id']][] = $__r;
}
?>
<!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>Additional Information - <?php echo htmlspecialchars($company_name); ?></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&family=Hind+Siliguri:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family:'Inter','Hind Siliguri',sans-serif; }
        .xf-l { display:block; font-size:11px; font-weight:800; color:#475569; margin-bottom:.3rem; }
        .xf   { width:100%; padding:.7rem .85rem; background:#fff; border:1.5px solid #cbd5e1; border-radius:.8rem;
                font-size:.85rem; outline:none; color:#0f172a; }
        .xf:focus { border-color:#6366f1; box-shadow:0 0 0 3px rgba(99,102,241,.14); }
    </style>
</head>
<?php
require_once __DIR__ . '/includes/theme.php';
$__menu = theme_user_menu($sidebar_subcats, $all_categories);
theme_open([
    'panel'  => 'user',
    'base'   => '',
    'title'  => 'Additional Information',
    'active' => 'profile',
    'user'   => $user,
    'wallet' => $wallet_balance,
    'notifs' => $unread_notifs,
    'logo'   => $company_logo,
    'brand'  => $company_name,
    'menu'   => $__menu,
    'state'  => '',
]);
?>

            <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8">

                <?php if ($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; ?>

                <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden max-w-3xl">
                    <div class="px-6 py-5 border-b border-gray-100 bg-gray-50/50 flex flex-wrap items-center justify-between gap-3">
                        <div>
                            <h3 class="text-lg font-bold text-gray-800"><i class="fas fa-list-check text-violet-600 mr-2"></i>Additional Information</h3>
                            <p class="text-xs text-slate-500 mt-0.5">Some services need a little more than the standard KYC. Fill these once and they apply everywhere.</p>
                        </div>
                        <?php if (!empty($fields)): ?>
                        <div class="text-right">
                            <p class="text-[11px] font-bold text-slate-500"><?php echo $done; ?> of <?php echo count($fields); ?> answered</p>
                            <div class="w-32 h-2 rounded-full bg-slate-200 mt-1 overflow-hidden">
                                <div class="h-full rounded-full bg-gradient-to-r from-violet-500 to-indigo-500" style="width:<?php echo $pct; ?>%"></div>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>

                    <?php if (empty($fields)): ?>
                        <div class="p-10 text-center">
                            <i class="fas fa-clipboard-check text-4xl text-slate-300 mb-3"></i>
                            <p class="font-bold text-slate-700">Nothing extra is needed right now</p>
                            <p class="text-sm text-slate-500 mt-1">Your standard KYC is all we ask for at the moment.</p>
                            <a href="profile.php#kyc" class="inline-block mt-4 px-5 py-2.5 rounded-xl bg-slate-900 text-white text-sm font-bold">Open my KYC</a>
                        </div>
                    <?php else: ?>
                        <form method="POST" enctype="multipart/form-data" class="p-6 space-y-6">
                            <?php foreach ($groups as $gname => $gfields): ?>
                            <div>
                                <p class="text-[11px] font-bold uppercase tracking-wide text-violet-600 mb-3 border-b pb-1">
                                    <i class="fas fa-folder-open mr-1"></i><?php echo esc($gname); ?>
                                </p>
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <?php foreach ($gfields as $f):
                                        $fid   = (int)$f['id'];
                                        $val   = (string)($values[$fid] ?? '');
                                        $label = ($current_lang === 'bn' && !empty($f['field_label_bn'])) ? $f['field_label_bn'] : $f['field_label'];
                                        $wide  = in_array($f['field_type'], ['textarea'], true);
                                        $ro    = ($val !== '');   /* saved once, locked for good */
                                    ?>
                                    <div class="<?php echo $wide ? 'md:col-span-2' : ''; ?>">
                                        <label class="xf-l">
                                            <?php echo esc($label); ?>
                                            <?php if ($ro): ?>
                                                <span class="ml-1 text-[10px] font-black uppercase text-emerald-600"><i class="fas fa-lock"></i> saved &amp; locked</span>
                                            <?php endif; ?>
                                        </label>

                                        <?php if ($f['field_type'] === 'textarea'): ?>
                                            <textarea name="f_<?php echo $fid; ?>" rows="3" class="xf<?php echo $ro ? ' bg-slate-100 text-slate-500' : ''; ?>" <?php echo $ro ? 'disabled' : ''; ?> placeholder="<?php echo esc($f['placeholder']); ?>"><?php echo esc($val); ?></textarea>

                                        <?php elseif ($f['field_type'] === 'select'): ?>
                                            <select name="f_<?php echo $fid; ?>" class="xf<?php echo $ro ? ' bg-slate-100 text-slate-500' : ''; ?>" <?php echo $ro ? 'disabled' : ''; ?>>
                                                <option value="">— choose —</option>
                                                <?php foreach (array_filter(array_map('trim', explode(',', (string)$f['options']))) as $opt): ?>
                                                    <option value="<?php echo esc($opt); ?>" <?php echo $val === $opt ? 'selected' : ''; ?>><?php echo esc($opt); ?></option>
                                                <?php endforeach; ?>
                                            </select>

                                        <?php elseif ($f['field_type'] === 'file'): ?>
                                            <?php if ($ro): ?>
                                                <div class="xf bg-slate-100 text-slate-500"><i class="fas fa-paperclip mr-1"></i>File already uploaded</div>
                                            <?php else: ?>
                                                <input type="file" name="f_<?php echo $fid; ?>" accept="image/*,application/pdf" class="xf !py-2">
                                            <?php endif; ?>
                                            <?php if ($val !== ''): ?>
                                                <a href="<?php echo esc($val); ?>" target="_blank" class="text-[11px] font-bold text-indigo-600 mt-1 inline-block"><i class="fas fa-paperclip mr-1"></i>View uploaded file</a>
                                            <?php endif; ?>

                                        <?php else: ?>
                                            <input type="<?php echo in_array($f['field_type'], ['number','date','email'], true) ? esc($f['field_type']) : 'text'; ?>"
                                                   name="f_<?php echo $fid; ?>" value="<?php echo esc($val); ?>"
                                                   class="xf<?php echo $ro ? ' bg-slate-100 text-slate-500' : ''; ?>" <?php echo $ro ? 'disabled' : ''; ?>
                                                   placeholder="<?php echo esc($f['placeholder']); ?>">
                                        <?php endif; ?>

                                        <?php if (!empty($f['help_text'])): ?>
                                            <p class="text-[10.5px] text-slate-400 mt-1"><?php echo esc($f['help_text']); ?></p>
                                        <?php endif; ?>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php endforeach; ?>

                            <div class="flex flex-wrap items-center justify-between gap-3 pt-2 border-t border-slate-100">
                                <a href="profile.php#kyc" class="text-xs font-bold text-slate-500 hover:text-slate-700"><i class="fas fa-arrow-left mr-1"></i>Back to my KYC</a>
                                <button type="submit" name="save_extra" value="1"
                                        class="px-6 py-3 rounded-xl bg-gradient-to-r from-violet-600 to-indigo-600 text-white text-sm font-bold shadow">
                                    <i class="fas fa-save mr-1"></i>Save information
                                </button>
                            </div>
                        </form>
                    <?php endif; ?>
                </div>

            </main>
        </div>
    </div>
</body>
</html>
