<?php
/* ============================================================================
   WBMCZ — FORGOT PASSWORD
   ----------------------------------------------------------------------------
   Two ways back in, and the admin decides which are open:

     Mobile OTP   a code goes to the registered number, and once it is confirmed
                  the new password screen opens straight away
     Email link   the old way — a one-time link lands in the inbox

   Both switches live in Admin → Website Settings → SMS & OTP. Turn one off and
   its tab simply disappears; turn both off and the page says so politely.
   ============================================================================ */
require_once __DIR__ . '/header.php';
require_once __DIR__ . '/includes/sms.php';

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

$error   = '';
$success = '';
$notice  = '';

$OTP_ON   = sms_cfg_on('otp_reset_enabled');
$EMAIL_ON = sms_cfg_on('reset_email_enabled');

$step = 'ask';                       // ask | otp
$mode = $OTP_ON ? 'mobile' : 'email';
if (isset($_GET['mode']) && in_array($_GET['mode'], ['mobile', 'email'], true)) { $mode = $_GET['mode']; }
if ($mode === 'mobile' && !$OTP_ON)   { $mode = 'email'; }
if ($mode === 'email'  && !$EMAIL_ON) { $mode = 'mobile'; }

$otp_mobile = '';
$otp_test   = '';
$otp_info   = ['cooldown' => 0, 'seconds' => 0];
$old_mobile = '';
$old_email  = '';

function fp_mask($m) {
    $m = (string)$m;
    return strlen($m) === 10 ? substr($m, 0, 2) . 'xxxxx' . substr($m, -3) : $m;
}

/* ============================================================================
   START OVER
   ============================================================================ */
if (isset($_POST['otp_cancel'])) {
    if (!empty($_SESSION['fp_otp']['mobile'])) { otp_clear('reset', $_SESSION['fp_otp']['mobile']); }
    unset($_SESSION['fp_otp']);
    redirect('forgot-password.php');
}

/* ============================================================================
   MOBILE — ask for the code
   ============================================================================ */
if (isset($_POST['send_otp']) && $OTP_ON) {
    $mobile = sms_clean_mobile($_POST['mobile'] ?? '');
    $old_mobile = $mobile;
    $mode = 'mobile';

    if (!sms_valid_mobile($mobile)) {
        $error = 'Please enter a correct 10 digit mobile number.';
    } else {
        $u = $db->select("SELECT id, name, email FROM users WHERE mobile = ? AND (deleted_at IS NULL OR deleted_at = '') LIMIT 1", [$mobile]);
        if (empty($u)) {
            $u = $db->select("SELECT id, name, email FROM users WHERE mobile = ? LIMIT 1", [$mobile]);
        }
        if (empty($u)) {
            $error = 'No account is registered with that mobile number.';
        } else {
            $res = otp_send('reset', $mobile, ['name' => $u[0]['name']], null, (int)$u[0]['id'], $u[0]['email']);
            if (!$res['ok'] && !$res['skipped']) {
                $error = $res['error'] ?: 'The code could not be sent. Please try again in a moment.';
            } else {
                $_SESSION['fp_otp'] = ['mobile' => $mobile, 'user_id' => (int)$u[0]['id'], 'at' => time()];
                $step   = 'otp';
                $notice = $res['test_code'] !== ''
                    ? 'Test mode is on, so nothing was texted. Your code is ' . $res['test_code'] : '';
            }
        }
    }
}

/* ============================================================================
   MOBILE — send it again
   ============================================================================ */
if (isset($_POST['otp_resend']) && !empty($_SESSION['fp_otp'])) {
    $m   = $_SESSION['fp_otp']['mobile'];
    $uid = (int)($_SESSION['fp_otp']['user_id'] ?? 0);
    $nm  = '';
    try { $r = $db->select("SELECT name FROM users WHERE id = ?", [$uid]); $nm = $r[0]['name'] ?? ''; } catch (\Throwable $e) {}

    $res = otp_send('reset', $m, ['name' => $nm], null, $uid);
    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 ' . fp_mask($m) . '.';
    } else {
        $error = $res['error'];
    }
    $step = 'otp'; $mode = 'mobile';
}

/* ============================================================================
   MOBILE — the code came back
   ============================================================================ */
if (isset($_POST['otp_verify']) && !empty($_SESSION['fp_otp'])) {
    $m   = $_SESSION['fp_otp']['mobile'];
    $chk = otp_check('reset', $m, $_POST['otp_code'] ?? '');

    if (!$chk['ok']) {
        $error = $chk['error'];
        $step = 'otp'; $mode = 'mobile';
    } else {
        otp_clear('reset', $m);
        unset($_SESSION['fp_otp']);
        /* a short-lived pass to the new-password screen, nothing more */
        $_SESSION['pwd_reset'] = [
            'user_id' => (int)($chk['row']['user_id'] ?? 0),
            'mobile'  => $m,
            'at'      => time(),
        ];
        redirect('reset-password.php');
    }
}

/* ============================================================================
   EMAIL — the old one-time link
   ============================================================================ */
if (isset($_POST['send_email']) && $EMAIL_ON) {
    $email = sanitize($_POST['email'] ?? '');
    $old_email = $email;
    $mode = 'email';

    $user = $db->select("SELECT * FROM users WHERE email = ?", [$email]);

    if (empty($user)) {
        /* say the same thing either way, so the page cannot be used to find out
           which addresses are registered */
        $success = "If this email is registered, you will receive a password reset link shortly.";
    } else {
        $token = bin2hex(random_bytes(32));
        $db->insert("INSERT INTO password_resets (email, token) VALUES (?, ?)", [$email, $token]);

        $reset_link = SITE_URL . "/reset-password.php?token=" . $token;
        $subject = "Password Reset Request - " . $company_name;
        $message = "
        <html><body style='font-family: Arial, sans-serif; line-height: 1.6; color: #333;'>
            <div style='max-width: 480px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 10px;'>
                <h2 style='color: #2563eb;'>Password Reset Request</h2>
                <p>We received a request to reset the password on your " . htmlspecialchars($company_name) . " account.</p>
                <p>Click the button below to set a new one:</p>
                <a href='$reset_link' style='display: inline-block; padding: 10px 20px; margin: 15px 0; color: #fff; background-color: #2563eb; text-decoration: none; border-radius: 5px; font-weight: bold;'>Reset Password</a>
                <p>If you did not ask for this, you can safely ignore this email.</p>
                <br><p>Best Regards,<br><strong>Team " . htmlspecialchars($company_name) . "</strong></p>
            </div>
        </body></html>";

        $headers  = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8\r\n";
        $headers .= "From: " . $company_name . " <no-reply@wbmcz.online>\r\n";
        $headers .= "Reply-To: no-reply@wbmcz.online\r\n";

        @mail($email, $subject, $message, $headers);
        $success = "If this email is registered, you will receive a password reset link shortly.";
    }
}

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

if ($step === 'otp') {
    $otp_mobile = $_SESSION['fp_otp']['mobile'] ?? '';
    $otp_info   = otp_state('reset', $otp_mobile);
    $otp_test   = $otp_info['test_code'] ?? '';
}
?>

<style>
    .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>

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

    <?php if ($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">Enter the code</h2>
            <p class="text-sm text-gray-500 mt-2">
                We sent it to <span class="font-semibold text-gray-800">+91 <?php echo htmlspecialchars(fp_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): ?>
                    This code expires in <span id="otpTimer" class="font-semibold text-gray-600" data-left="<?php echo (int)$otp_info['seconds']; ?>"></span>
                <?php else: ?>
                    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 shadow-md">
                Verify &amp; set a new password
            </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>Use a different number</button>
            </form>
            <form method="POST">
                <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">Resend the code</span>
                </button>
            </form>
        </div>

    <?php else: ?>
        <!-- ================= ASK ================= -->
        <div class="text-center mb-6">
            <img src="<?php echo htmlspecialchars($company_logo); ?>" alt="Logo" class="h-16 w-auto mx-auto mb-4">
            <h2 class="text-2xl font-extrabold text-gray-900">Forgot your password?</h2>
            <p class="mt-2 text-sm text-gray-600">
                <?php if ($OTP_ON && $EMAIL_ON): ?>Choose how you would like to get back in.
                <?php elseif ($OTP_ON): ?>We will text a code to your registered mobile number.
                <?php elseif ($EMAIL_ON): ?>We will email you a link to set a new password.
                <?php else: ?>Password reset is switched off at the moment.<?php endif; ?>
            </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 ($success): ?>
        <div class="mb-5 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-lg text-sm flex items-start">
            <i class="fas fa-circle-check mr-2 mt-0.5"></i><span><?php echo htmlspecialchars($success); ?></span>
        </div>
        <?php endif; ?>

        <?php if (!$OTP_ON && !$EMAIL_ON): ?>
            <div class="bg-amber-50 border border-amber-200 text-amber-800 px-4 py-4 rounded-xl text-sm text-center">
                <i class="fas fa-triangle-exclamation text-xl block mb-2"></i>
                Password reset is not available right now. Please contact support and they will help you.
            </div>
        <?php else: ?>

            <?php if ($OTP_ON && $EMAIL_ON): ?>
            <div class="flex gap-2 p-1 bg-gray-100 rounded-xl mb-6">
                <a href="?mode=mobile" class="flex-1 text-center py-2.5 rounded-lg text-sm font-bold transition-colors <?php echo $mode === 'mobile' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500 hover:text-gray-700'; ?>">
                    <i class="fas fa-mobile-screen mr-1"></i> Mobile OTP
                </a>
                <a href="?mode=email" class="flex-1 text-center py-2.5 rounded-lg text-sm font-bold transition-colors <?php echo $mode === 'email' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500 hover:text-gray-700'; ?>">
                    <i class="fas fa-envelope mr-1"></i> Email link
                </a>
            </div>
            <?php endif; ?>

            <?php if ($mode === 'mobile' && $OTP_ON): ?>
            <form method="POST" class="space-y-5">
                <input type="hidden" name="send_otp" value="1">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Registered mobile number</label>
                    <div class="relative">
                        <span class="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 text-sm font-semibold">+91</span>
                        <input name="mobile" type="tel" required pattern="[0-9]{10}" maxlength="10" value="<?php echo htmlspecialchars($old_mobile); ?>"
                               class="appearance-none rounded-lg block w-full pl-14 pr-4 py-3 border border-gray-300 text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                               placeholder="10 digit mobile number" autofocus>
                    </div>
                    <p class="text-xs text-gray-400 mt-1">The number you signed up with.</p>
                </div>
                <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 shadow-md">
                    Send me the code
                </button>
            </form>
            <?php elseif ($mode === 'email' && $EMAIL_ON): ?>
            <form method="POST" class="space-y-5">
                <input type="hidden" name="send_email" value="1">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Registered email address</label>
                    <input name="email" type="email" required value="<?php echo htmlspecialchars($old_email); ?>"
                           class="appearance-none rounded-lg block w-full px-4 py-3 border border-gray-300 text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                           placeholder="Enter your registered email" autofocus>
                </div>
                <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 shadow-md">
                    Send the reset link
                </button>
            </form>
            <?php endif; ?>
        <?php endif; ?>

        <div class="text-center mt-6">
            <a href="login.php" class="text-sm font-medium text-gray-600 hover:text-blue-500"><i class="fas fa-arrow-left mr-1"></i>Back to login</a>
        </div>
    <?php endif; ?>

    </div>
</div>

<?php if ($step === 'otp'): ?>
<script>
(function () {
    const wrap   = document.getElementById('otpBoxes');
    const boxes  = Array.from(wrap.querySelectorAll('.otp-box'));
    const hidden = document.getElementById('otpValue');
    const form   = document.getElementById('otpForm');
    const 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 d = (e.clipboardData || window.clipboardData).getData('text').replace(/\D/g, '').split('');
            boxes.forEach((b, k) => { b.value = d[k] || ''; });
            collect();
            boxes[Math.min(d.length, boxes.length) - 1]?.focus();
            if (hidden.value.length === boxes.length) { form.requestSubmit ? form.requestSubmit() : form.submit(); }
        });
    });
    form.addEventListener('submit', collect);

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

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

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