<?php
/* ============================================================================
   WBMCZ — REGISTRATION with mobile OTP
   ----------------------------------------------------------------------------
   Three screens, one file:

     form   the details, exactly as before
     otp    the six digit code that just went to the phone
     done   congratulations, with the new User ID

   The account is only created once the code is confirmed, so a wrong or made-up
   number can never leave a half-real member behind. Everything typed into the
   form waits inside the OTP row until then — the password already hashed.

   If OTP is switched off in Admin → Website Settings → SMS & OTP, the form
   behaves exactly the way it always did.
   ============================================================================ */
require_once __DIR__ . '/header.php';
require_once __DIR__ . '/includes/sms.php';

if (isLoggedIn()) { redirect('index.php'); }

$error = '';
$notice = '';
$step   = 'form';          // form | otp | done
$OTP_ON = sms_cfg_on('otp_register_enabled');

$ref_code = isset($_GET['ref']) ? sanitize($_GET['ref']) : '';

/* what the form shows after a mistake, so nothing has to be typed twice */
$old = ['name' => '', 'mobile' => '', 'email' => '', 'gender' => 'male',
        'state' => '', 'district' => '', 'pincode' => '', 'referral_code' => $ref_code];

$otp_mobile = '';
$otp_test   = '';
$otp_info   = ['cooldown' => 0, 'seconds' => 0];
$done       = ['name' => '', 'userid' => '', 'mobile' => '', 'sms' => false];

/* ---------------------------------------------------------------------------
   Everything the form has to get right, in one place, so the same rules apply
   whether the account is made now or after the code is confirmed.
   --------------------------------------------------------------------------- */
function reg_validate($db, $lang, $p) {
    $out = ['error' => '', 'data' => null];

    $name     = sanitize($p['name'] ?? '');
    $mobile   = sms_clean_mobile($p['mobile'] ?? '');
    $email    = sanitize($p['email'] ?? '');
    $gender   = sanitize($p['gender'] ?? 'male');
    $password = (string)($p['password'] ?? '');
    $confirm  = (string)($p['confirm_password'] ?? '');
    $state    = sanitize($p['state'] ?? '');
    $district = sanitize($p['district'] ?? '');
    $pincode  = sanitize($p['pincode'] ?? '');
    $refin    = strtoupper(trim((string)($p['referral_code'] ?? '')));

    $referred_by = null;
    $ref_ok = false;
    if ($refin !== '' && strpos($refin, 'WBMCZ') === 0) {
        $ref_id = (int)str_replace('WBMCZ', '', $refin);
        if ($ref_id > 0 && !empty($db->select("SELECT id FROM users WHERE id = ?", [$ref_id]))) {
            $referred_by = $ref_id;
            $ref_ok = true;
        }
    }

    if ($name === '' || $mobile === '' || $email === '' || $gender === '' || $password === ''
        || $state === '' || $district === '' || $pincode === '') {
        $out['error'] = $lang->translate('fill_all_fields', 'Please fill all fields.');
    } elseif (!sms_valid_mobile($mobile)) {
        $out['error'] = $lang->translate('valid_mobile', 'Please enter a correct 10 digit mobile number.');
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $out['error'] = $lang->translate('valid_email', 'Please enter a valid email address.');
    } elseif (strlen($password) < 6) {
        $out['error'] = $lang->translate('password_short', 'Password must be at least 6 characters.');
    } elseif ($password !== $confirm) {
        $out['error'] = $lang->translate('password_mismatch', 'Passwords do not match!');
    } elseif (!$ref_ok) {
        $out['error'] = $lang->translate('invalid_referral', 'সঠিক রেফারেল কোড দিন। রেফারেল কোড আবশ্যক।');
    } elseif (!empty($db->select("SELECT id FROM users WHERE mobile = ? OR email = ?", [$mobile, $email]))) {
        $out['error'] = $lang->translate('mobile_exists', 'This mobile number or email is already registered.');
    } else {
        $out['data'] = [
            'name' => $name, 'mobile' => $mobile, 'email' => $email, 'gender' => $gender,
            'password_hash' => password_hash($password, PASSWORD_DEFAULT),
            'state' => $state, 'district' => $district, 'pincode' => $pincode,
            'referred_by' => $referred_by,
        ];
    }
    return $out;
}

/* The account itself. Returns the new id, or 0. */
function reg_create($db, $d) {
    try {
        return (int)$db->insert(
            "INSERT INTO users (name, mobile, email, gender, password, state, district, pincode, referred_by)
             VALUES (?,?,?,?,?,?,?,?,?)",
            [$d['name'], $d['mobile'], $d['email'], $d['gender'], $d['password_hash'],
             $d['state'], $d['district'], $d['pincode'], $d['referred_by']]
        );
    } catch (\Throwable $e) { return 0; }
}

/* ============================================================================
   START OVER — leave the code screen and go back to the form
   ============================================================================ */
if (isset($_POST['otp_cancel'])) {
    if (!empty($_SESSION['reg_otp']['mobile'])) { otp_clear('register', $_SESSION['reg_otp']['mobile']); }
    unset($_SESSION['reg_otp']);
    redirect('register.php');
}

/* ============================================================================
   SEND THE CODE AGAIN
   ============================================================================ */
if (isset($_POST['otp_resend']) && !empty($_SESSION['reg_otp'])) {
    $m    = $_SESSION['reg_otp']['mobile'];
    $data = $_SESSION['reg_otp']['data'] ?? [];
    $res  = otp_send('register', $m, ['name' => $data['name'] ?? ''], $data, null, $data['email'] ?? null);

    if ($res['ok'] || $res['skipped']) {
        $notice = $res['test_code'] !== ''
            ? 'Test mode is on, so nothing was texted. Your code is ' . $res['test_code']
            : 'A new code is on its way to ' . substr($m, 0, 2) . 'xxxxx' . substr($m, -3) . '.';
    } else {
        $error = $res['error'];
    }
    $step = 'otp';
}

/* ============================================================================
   THE CODE CAME BACK — check it, then make the account
   ============================================================================ */
if (isset($_POST['otp_verify']) && !empty($_SESSION['reg_otp'])) {
    $m   = $_SESSION['reg_otp']['mobile'];
    $chk = otp_check('register', $m, $_POST['otp_code'] ?? '');

    if (!$chk['ok']) {
        $error = $chk['error'];
        $step  = 'otp';
    } else {
        /* whatever was parked with the code is the truth — not the browser */
        $data = otp_payload($chk['row']);
        if (empty($data)) { $data = $_SESSION['reg_otp']['data'] ?? []; }

        /* somebody may have taken the number in the meantime */
        $taken = $db->select("SELECT id FROM users WHERE mobile = ? OR email = ?", [$data['mobile'], $data['email']]);
        if (!empty($taken)) {
            otp_clear('register', $m);
            unset($_SESSION['reg_otp']);
            $error = $lang->translate('mobile_exists', 'This mobile number or email is already registered.');
            $step  = 'form';
        } else {
            $newId = reg_create($db, $data);
            if (!$newId) {
                $error = 'The account could not be created. Please try again.';
                $step  = 'otp';
            } else {
                $sms = sms_send_welcome($newId, $data['name'], $data['mobile']);
                otp_clear('register', $m);
                unset($_SESSION['reg_otp']);

                $done = [
                    'name'   => $data['name'],
                    'userid' => sms_user_code($newId),
                    'mobile' => $data['mobile'],
                    'sms'    => (bool)($sms['ok'] ?? false) && empty($sms['skipped']),
                ];
                $step = 'done';
            }
        }
    }
}

/* ============================================================================
   THE FORM
   ============================================================================ */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['do_register'])) {
    foreach (array_keys($old) as $k) { $old[$k] = sanitize($_POST[$k] ?? ''); }
    $old['mobile'] = sms_clean_mobile($_POST['mobile'] ?? '');

    $v = reg_validate($db, $lang, $_POST);

    if ($v['error'] !== '') {
        $error = $v['error'];
    } elseif (!$OTP_ON) {
        /* OTP switched off — behave exactly the way this page always did */
        $newId = reg_create($db, $v['data']);
        if (!$newId) {
            $error = 'The account could not be created. Please try again.';
        } else {
            $sms  = sms_send_welcome($newId, $v['data']['name'], $v['data']['mobile']);
            $done = ['name' => $v['data']['name'], 'userid' => sms_user_code($newId),
                     'mobile' => $v['data']['mobile'], 'sms' => (bool)($sms['ok'] ?? false) && empty($sms['skipped'])];
            $step = 'done';
        }
    } else {
        $res = otp_send('register', $v['data']['mobile'], ['name' => $v['data']['name']],
                        $v['data'], null, $v['data']['email']);
        if (!$res['ok'] && !$res['skipped']) {
            $error = $res['error'] ?: 'The code could not be sent. Please try again in a moment.';
        } else {
            $_SESSION['reg_otp'] = ['mobile' => $v['data']['mobile'], 'data' => $v['data'], 'at' => time()];
            $step   = 'otp';
            $notice = $res['test_code'] !== ''
                ? 'Test mode is on, so nothing was texted. Your code is ' . $res['test_code']
                : '';
        }
    }
}

/* Landing on the page mid-flow — the code screen is where they left off. */
if ($step === 'form' && $OTP_ON && !empty($_SESSION['reg_otp']['mobile'])
    && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    if (otp_active('register', $_SESSION['reg_otp']['mobile'])) { $step = 'otp'; }
    else { unset($_SESSION['reg_otp']); }
}

if ($step === 'otp') {
    $otp_mobile = $_SESSION['reg_otp']['mobile'] ?? '';
    $otp_info   = otp_state('register', $otp_mobile);
    $otp_test   = $otp_info['test_code'] ?? '';
    $old['name'] = $_SESSION['reg_otp']['data']['name'] ?? '';
}

/* 98xxxxx210 — enough to recognise, not enough to read over a shoulder */
function reg_mask($m) {
    $m = (string)$m;
    return strlen($m) === 10 ? substr($m, 0, 2) . 'xxxxx' . substr($m, -3) : $m;
}
?>
<!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><?php echo $lang->translate('register', 'Register'); ?> - <?php echo htmlspecialchars($company_name); ?></title>
    <script src="https://cdn.tailwindcss.com"></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=Poppins:wght@300;400;600;700&family=Noto+Sans+Bengali:wght@400;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Poppins', 'Noto Sans Bengali', sans-serif; }
        .otp-box { width: 46px; height: 56px; text-align: center; font-size: 22px; font-weight: 700;
                   border: 1px solid #cbd5e1; border-radius: 12px; color: #0f172a; }
        .otp-box:focus { outline: none; border-color: #2563eb; box-shadow: 0 0 0 3px rgba(37,99,235,.15); }
        @media (max-width: 380px) { .otp-box { width: 38px; height: 50px; font-size: 19px; } }
    </style>
</head>
<body class="bg-gray-50 flex flex-col min-h-screen">

<div class="flex-grow flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
<div class="max-w-md w-full bg-white p-8 rounded-2xl shadow-xl border border-gray-100">

<?php if ($step === 'done'): ?>
    <!-- ================= CONGRATULATIONS ================= -->
    <div class="text-center">
        <div class="w-20 h-20 rounded-full bg-emerald-50 border-4 border-emerald-100 text-emerald-500 flex items-center justify-center text-4xl mx-auto mb-5">
            <i class="fas fa-circle-check"></i>
        </div>
        <h2 class="text-2xl font-bold text-gray-900 mb-1">
            <?php echo $lang->translate('congratulations', 'Congratulations'); ?><?php echo $done['name'] !== '' ? ', ' . htmlspecialchars($done['name']) : ''; ?>!
        </h2>
        <p class="text-sm text-gray-500 mb-6">
            <?php echo $lang->translate('registration_done', 'Your account has been created successfully.'); ?>
        </p>

        <?php /* The User ID doubles as the referral code, and referring only pays
                 once a subscription is taken. Showing it the moment somebody signs
                 up invites them to share a code that earns them nothing yet, so it
                 waits — it is on the dashboard, and on Refer & Earn once they
                 subscribe. */ ?>

        <div class="text-left bg-gray-50 border border-gray-200 rounded-xl p-4 mb-6 space-y-2">
            <div class="flex justify-between text-sm">
                <span class="text-gray-500"><?php echo $lang->translate('mobile_number', 'Mobile Number'); ?></span>
                <span class="font-semibold text-gray-800"><?php echo htmlspecialchars($done['mobile']); ?>
                    <?php if ($OTP_ON): ?><i class="fas fa-circle-check text-emerald-500 ml-1" title="Verified"></i><?php endif; ?>
                </span>
            </div>
            <div class="flex justify-between text-sm">
                <span class="text-gray-500"><?php echo $lang->translate('login_with', 'Login with'); ?></span>
                <span class="font-semibold text-gray-800"><?php echo $lang->translate('mobile_and_password', 'Mobile & password'); ?></span>
            </div>
            <?php if ($done['sms']): ?>
            <p class="text-[11px] text-emerald-600 pt-1 border-t border-gray-200 mt-2">
                <i class="fas fa-comment-sms mr-1"></i><?php echo $lang->translate('welcome_sms_sent', 'A confirmation SMS has been sent to your mobile.'); ?>
            </p>
            <?php endif; ?>
        </div>

        <a href="login.php" class="w-full inline-flex justify-center items-center gap-2 py-3.5 px-4 text-sm font-bold rounded-lg text-white bg-blue-600 hover:bg-blue-700 transition-colors shadow-md">
            <i class="fas fa-right-to-bracket"></i> <?php echo $lang->translate('login_now', 'Login now'); ?>
        </a>
        <a href="index.php" class="block text-center text-xs text-gray-400 hover:text-gray-600 mt-4">
            <?php echo $lang->translate('back_home', 'Back to home'); ?>
        </a>
    </div>

<?php elseif ($step === 'otp'): ?>
    <!-- ================= THE CODE ================= -->
    <div class="text-center mb-7">
        <div class="w-16 h-16 rounded-2xl bg-blue-50 text-blue-600 flex items-center justify-center text-2xl mx-auto mb-4">
            <i class="fas fa-comment-sms"></i>
        </div>
        <h2 class="text-2xl font-bold text-gray-900"><?php echo $lang->translate('verify_mobile', 'Verify your mobile'); ?></h2>
        <p class="text-sm text-gray-500 mt-2">
            <?php echo $lang->translate('otp_sent_to', 'We sent a code to'); ?>
            <span class="font-semibold text-gray-800">+91 <?php echo htmlspecialchars(reg_mask($otp_mobile)); ?></span>
        </p>
    </div>

    <?php if ($error): ?>
        <div class="mb-5 bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded-lg text-sm flex items-start">
            <i class="fas fa-exclamation-circle mr-2 mt-0.5"></i><span><?php echo htmlspecialchars($error); ?></span>
        </div>
    <?php endif; ?>
    <?php if ($notice): ?>
        <div class="mb-5 bg-blue-50 border border-blue-200 text-blue-700 px-4 py-3 rounded-lg text-sm flex items-start">
            <i class="fas fa-circle-info mr-2 mt-0.5"></i><span><?php echo htmlspecialchars($notice); ?></span>
        </div>
    <?php endif; ?>

    <?php if ($otp_test !== ''): ?>
        <div class="mb-5 bg-amber-50 border border-amber-200 text-amber-800 px-4 py-3 rounded-lg text-sm text-center">
            <p class="text-[11px] uppercase font-bold tracking-wider mb-1">Test mode — nothing was texted</p>
            <p class="text-2xl font-extrabold tracking-[.3em]"><?php echo htmlspecialchars($otp_test); ?></p>
        </div>
    <?php endif; ?>

    <form method="POST" id="otpForm" class="space-y-5">
        <input type="hidden" name="otp_verify" value="1">
        <input type="hidden" name="otp_code" id="otpValue">

        <div class="flex justify-center gap-2" id="otpBoxes">
            <?php for ($i = 0; $i < max(4, min(8, (int)sms_cfg('otp_length'))); $i++): ?>
            <input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="otp-box" autocomplete="off"
                   <?php echo $i === 0 ? 'autofocus' : ''; ?>>
            <?php endfor; ?>
        </div>

        <p class="text-center text-xs text-gray-400">
            <?php if ($otp_info['seconds'] > 0): ?>
                <?php echo $lang->translate('code_expires_in', 'This code expires in'); ?>
                <span id="otpTimer" class="font-semibold text-gray-600" data-left="<?php echo (int)$otp_info['seconds']; ?>"></span>
            <?php else: ?>
                <?php echo $lang->translate('code_expired', 'This code has expired — please ask for a new one.'); ?>
            <?php endif; ?>
        </p>

        <button type="submit" class="w-full flex justify-center py-3.5 px-4 text-sm font-bold rounded-lg text-white bg-blue-600 hover:bg-blue-700 transition-colors shadow-md">
            <?php echo $lang->translate('verify_and_create', 'Verify & create my account'); ?>
        </button>
    </form>

    <div class="flex items-center justify-between mt-5 gap-3">
        <form method="POST">
            <input type="hidden" name="otp_cancel" value="1">
            <button type="submit" class="text-xs text-gray-400 hover:text-gray-600">
                <i class="fas fa-arrow-left mr-1"></i><?php echo $lang->translate('change_details', 'Change my details'); ?>
            </button>
        </form>
        <form method="POST" id="resendForm">
            <input type="hidden" name="otp_resend" value="1">
            <button type="submit" id="resendBtn" data-wait="<?php echo (int)$otp_info['cooldown']; ?>"
                    class="text-xs font-bold text-blue-600 hover:text-blue-700 disabled:text-gray-300 disabled:cursor-not-allowed">
                <i class="fas fa-rotate-right mr-1"></i><span id="resendText"><?php echo $lang->translate('resend_code', 'Resend the code'); ?></span>
            </button>
        </form>
    </div>

<?php else: ?>
    <!-- ================= THE FORM ================= -->
    <div class="text-center mb-8">
        <img src="<?php echo htmlspecialchars($company_logo); ?>" alt="Logo" class="h-16 mx-auto mb-4 bg-gray-50 p-2 rounded-xl object-contain">
        <h2 class="text-2xl font-bold text-gray-900"><?php echo $lang->translate('user_registration', 'User Registration'); ?></h2>
        <p class="text-sm text-gray-500 mt-2">
            <?php echo $lang->translate('or', 'or'); ?>
            <a href="login.php" class="font-medium text-blue-600 hover:text-blue-500"><?php echo $lang->translate('login_existing', 'Login to existing account'); ?></a>
        </p>
    </div>

    <?php if ($error): ?>
        <div class="mb-6 bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded-lg text-sm flex items-start shadow-sm">
            <i class="fas fa-exclamation-circle mr-2 mt-0.5 text-lg"></i> <span><?php echo $error; ?></span>
        </div>
    <?php endif; ?>

    <?php if ($OTP_ON): ?>
        <div class="mb-6 bg-blue-50 border border-blue-200 text-blue-700 px-4 py-3 rounded-lg text-xs flex items-start">
            <i class="fas fa-shield-halved mr-2 mt-0.5"></i>
            <span><?php echo $lang->translate('otp_note', 'We will text a code to your mobile to confirm it is yours. Your account is created once you enter that code.'); ?></span>
        </div>
    <?php endif; ?>

    <form method="POST" class="space-y-5">
        <input type="hidden" name="do_register" value="1">

        <div>
            <label class="block text-sm font-medium text-gray-700 mb-1"><?php echo $lang->translate('enter_full_name', 'Full Name'); ?></label>
            <input name="name" type="text" required value="<?php echo htmlspecialchars($old['name']); ?>" class="appearance-none rounded-lg relative block w-full px-4 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all">
        </div>

        <div>
            <label class="block text-sm font-medium text-gray-700 mb-1"><?php echo $lang->translate('mobile_number', 'Mobile Number'); ?></label>
            <input name="mobile" type="tel" required pattern="[0-9]{10}" maxlength="10" value="<?php echo htmlspecialchars($old['mobile']); ?>" class="appearance-none rounded-lg relative block w-full px-4 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all" placeholder="10 digit mobile number">
            <?php if ($OTP_ON): ?><p class="text-xs text-gray-400 mt-1"><i class="fas fa-comment-sms mr-1"></i><?php echo $lang->translate('otp_will_go_here', 'The code goes to this number, so please check it.'); ?></p><?php endif; ?>
        </div>

        <div>
            <label class="block text-sm font-medium text-gray-700 mb-1"><?php echo $lang->translate('email', 'Email Address'); ?></label>
            <input name="email" type="email" required value="<?php echo htmlspecialchars($old['email']); ?>" class="appearance-none rounded-lg relative block w-full px-4 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all">
        </div>

        <div>
            <label class="block text-sm font-medium text-gray-700 mb-2"><?php echo $lang->translate('gender', 'Gender'); ?></label>
            <div class="flex space-x-6 p-2 bg-gray-50 rounded-lg border border-gray-200">
                <label class="inline-flex items-center cursor-pointer">
                    <input type="radio" name="gender" value="male" class="form-radio h-4 w-4 text-blue-600" <?php echo $old['gender'] !== 'female' ? 'checked' : ''; ?>>
                    <span class="ml-2 text-gray-700 font-medium"><?php echo $lang->translate('male', 'Male'); ?></span>
                </label>
                <label class="inline-flex items-center cursor-pointer">
                    <input type="radio" name="gender" value="female" class="form-radio h-4 w-4 text-blue-600" <?php echo $old['gender'] === 'female' ? 'checked' : ''; ?>>
                    <span class="ml-2 text-gray-700 font-medium"><?php echo $lang->translate('female', 'Female'); ?></span>
                </label>
            </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1"><?php echo $lang->translate('state', 'State (রাজ্য)'); ?></label>
                <select name="state" id="state" required data-selected="<?php echo htmlspecialchars($old['state']); ?>" class="appearance-none rounded-lg relative block w-full px-4 py-3 border border-gray-300 bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all">
                    <option value="">Select State</option>
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1"><?php echo $lang->translate('district', 'District (জেলা)'); ?></label>
                <select name="district" id="district" required disabled data-selected="<?php echo htmlspecialchars($old['district']); ?>" class="appearance-none rounded-lg relative block w-full px-4 py-3 border border-gray-300 bg-gray-50 text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all disabled:opacity-75">
                    <option value="">Select District</option>
                </select>
            </div>
        </div>

        <div>
            <label class="block text-sm font-medium text-gray-700 mb-1"><?php echo $lang->translate('pincode', 'Pincode (পিনকোড)'); ?></label>
            <input name="pincode" id="pincode" type="text" pattern="[0-9]{6}" maxlength="6" required value="<?php echo htmlspecialchars($old['pincode']); ?>" class="appearance-none rounded-lg relative block w-full px-4 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all" placeholder="6-digit Pincode">
        </div>

        <div class="grid grid-cols-2 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1"><?php echo $lang->translate('password', 'পাসওয়ার্ড'); ?></label>
                <input name="password" type="password" required minlength="6" class="appearance-none rounded-lg relative block w-full px-4 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1"><?php echo $lang->translate('confirm_password', 'পাসওয়ার্ড কনফার্ম করুন'); ?></label>
                <input name="confirm_password" type="password" required minlength="6" class="appearance-none rounded-lg relative block w-full px-4 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all">
            </div>
        </div>

        <div>
            <label class="block text-sm font-medium text-gray-700 mb-1"><?php echo $lang->translate('referral_code', 'Referral Code (রেফারেল কোড)'); ?> <span class="text-red-500">*</span></label>
            <input name="referral_code" type="text" required value="<?php echo htmlspecialchars($old['referral_code'] !== '' ? $old['referral_code'] : $ref_code); ?>" class="appearance-none rounded-lg relative block w-full px-4 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all" placeholder="e.g. WBMCZ0001">
            <p class="text-xs text-red-500 mt-1"><?php echo $lang->translate('referral_required_note', 'রেফারেল কোড আবশ্যক। আপনার রেফারারের কোড দিন।'); ?></p>
        </div>

        <button type="submit" class="w-full flex justify-center py-3.5 px-4 border border-transparent text-sm font-bold rounded-lg text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors shadow-md mt-4">
            <?php echo $OTP_ON ? $lang->translate('send_otp', 'Send me the code') : $lang->translate('register', 'Register'); ?>
        </button>
    </form>
<?php endif; ?>

</div>
</div>

<?php require_once __DIR__ . '/footer.php'; ?>

<?php if ($step === 'otp'): ?>
<script>
/* ---- the six little boxes behave like one field ---- */
(function () {
    const wrap  = document.getElementById('otpBoxes');
    const boxes = Array.from(wrap.querySelectorAll('.otp-box'));
    const hidden = document.getElementById('otpValue');
    const form  = document.getElementById('otpForm');

    function collect() { hidden.value = boxes.map(b => b.value).join(''); }

    boxes.forEach((box, i) => {
        box.addEventListener('input', () => {
            box.value = box.value.replace(/\D/g, '').slice(0, 1);
            if (box.value && i < boxes.length - 1) boxes[i + 1].focus();
            collect();
            if (hidden.value.length === boxes.length) { form.requestSubmit ? form.requestSubmit() : form.submit(); }
        });
        box.addEventListener('keydown', e => {
            if (e.key === 'Backspace' && !box.value && i > 0) { boxes[i - 1].focus(); boxes[i - 1].value = ''; collect(); }
            if (e.key === 'ArrowLeft'  && i > 0) boxes[i - 1].focus();
            if (e.key === 'ArrowRight' && i < boxes.length - 1) boxes[i + 1].focus();
        });
        box.addEventListener('paste', e => {
            e.preventDefault();
            const digits = (e.clipboardData || window.clipboardData).getData('text').replace(/\D/g, '').split('');
            boxes.forEach((b, k) => { b.value = digits[k] || ''; });
            collect();
            boxes[Math.min(digits.length, boxes.length) - 1]?.focus();
            if (hidden.value.length === boxes.length) { form.requestSubmit ? form.requestSubmit() : form.submit(); }
        });
    });
    form.addEventListener('submit', collect);

    /* ---- how long the code has left ---- */
    const timer = document.getElementById('otpTimer');
    if (timer) {
        let left = parseInt(timer.dataset.left || '0', 10);
        const tick = () => {
            if (left <= 0) { timer.textContent = '0:00'; timer.classList.add('text-red-500'); return; }
            const m = Math.floor(left / 60), s = left % 60;
            timer.textContent = m + ':' + String(s).padStart(2, '0');
            left--; setTimeout(tick, 1000);
        };
        tick();
    }

    /* ---- the resend button waits its turn ---- */
    const btn  = document.getElementById('resendBtn');
    const text = document.getElementById('resendText');
    if (btn) {
        let wait = parseInt(btn.dataset.wait || '0', 10);
        const label = text.textContent;
        const tick = () => {
            if (wait <= 0) { btn.disabled = false; text.textContent = label; return; }
            btn.disabled = true;
            text.textContent = label + ' (' + wait + 's)';
            wait--; setTimeout(tick, 1000);
        };
        tick();
    }
})();
</script>
<?php endif; ?>

<?php if ($step === 'form'): ?>
<script>
/* ---- states and districts, and put back whatever was already chosen ---- */
(function () {
    const stateSelect    = document.getElementById('state');
    const districtSelect = document.getElementById('district');
    if (!stateSelect) return;

    const wantState    = stateSelect.dataset.selected || '';
    const wantDistrict = districtSelect.dataset.selected || '';
    let locationData = {};

    function fillDistricts(state, want) {
        districtSelect.innerHTML = '<option value="">Select District</option>';
        const districts = locationData[state] || [];
        districts.forEach(d => {
            const o = document.createElement('option');
            o.value = d; o.textContent = d;
            if (want && want === d) o.selected = true;
            districtSelect.appendChild(o);
        });
        districtSelect.disabled = !state;
        districtSelect.classList.toggle('bg-gray-50', !state);
        districtSelect.classList.toggle('bg-white', !!state);
    }

    fetch('https://raw.githubusercontent.com/sab99r/Indian-States-And-Districts/master/states-and-districts.json')
        .then(r => r.json())
        .then(data => {
            data.states.forEach(item => { locationData[item.state] = item.districts; });
            for (let state in locationData) {
                const o = document.createElement('option');
                o.value = state; o.textContent = state;
                if (wantState && wantState === state) o.selected = true;
                stateSelect.appendChild(o);
            }
            if (wantState) fillDistricts(wantState, wantDistrict);
        })
        .catch(err => console.error('Error loading states data:', err));

    stateSelect.addEventListener('change', function () { fillDistricts(this.value, ''); });
})();
</script>
<?php endif; ?>

</body>
</html>
