<?php
/* ============================================================================
   WBMCZ — SET A NEW PASSWORD
   ----------------------------------------------------------------------------
   Two ways to get here, and both end on the same screen:

     ?token=…      the one-time link from the reset email
     mobile OTP    forgot-password.php confirmed the code and left a short-lived
                   pass in the session (fifteen minutes, then it lapses)

   Whichever way, the password is hashed, every outstanding reset link for that
   account is thrown away, and a text goes out to say the password changed.
   ============================================================================ */
require_once __DIR__ . '/header.php';
require_once __DIR__ . '/includes/sms.php';

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

$error   = '';
$allowed = false;
$via     = '';          // token | otp
$email_to_reset = '';
$user_id_to_reset = 0;
$who = '';

/* ---------------------------------------------------------------------------
   1. the email link
   --------------------------------------------------------------------------- */
if (isset($_GET['token']) || isset($_POST['token'])) {
    $token = sanitize($_GET['token'] ?? $_POST['token'] ?? '');
    $r = $db->select(
        "SELECT * FROM password_resets WHERE token = ? AND created_at >= NOW() - INTERVAL 1 DAY ORDER BY created_at DESC LIMIT 1",
        [$token]);
    if (!empty($r)) {
        $allowed = true; $via = 'token';
        $email_to_reset = $r[0]['email'];
        $u = $db->select("SELECT id, name, mobile FROM users WHERE email = ? LIMIT 1", [$email_to_reset]);
        if (!empty($u)) { $user_id_to_reset = (int)$u[0]['id']; $who = $u[0]['name']; }
    } else {
        $error = 'That reset link has expired or has already been used. Please ask for a new one.';
    }
}

/* ---------------------------------------------------------------------------
   2. the confirmed mobile code
   --------------------------------------------------------------------------- */
elseif (!empty($_SESSION['pwd_reset']['user_id'])) {
    $pass = $_SESSION['pwd_reset'];
    if ((time() - (int)($pass['at'] ?? 0)) > 900) {          // fifteen minutes
        unset($_SESSION['pwd_reset']);
        $error = 'That took a little too long. Please ask for a new code.';
    } else {
        $u = $db->select("SELECT id, name, email, mobile FROM users WHERE id = ? LIMIT 1", [(int)$pass['user_id']]);
        if (empty($u)) {
            unset($_SESSION['pwd_reset']);
            $error = 'That account could not be found. Please start again.';
        } else {
            $allowed = true; $via = 'otp';
            $user_id_to_reset = (int)$u[0]['id'];
            $email_to_reset   = (string)$u[0]['email'];
            $who              = (string)$u[0]['name'];
        }
    }
}

else {
    redirect('forgot-password.php');
}

/* ---------------------------------------------------------------------------
   Save the new password
   --------------------------------------------------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $allowed && isset($_POST['save_password'])) {
    $password = (string)($_POST['password'] ?? '');
    $confirm  = (string)($_POST['confirm_password'] ?? '');

    if ($password === '' || $confirm === '') {
        $error = 'Please fill both boxes.';
    } elseif (strlen($password) < 6) {
        $error = 'The password needs at least 6 characters.';
    } elseif ($password !== $confirm) {
        $error = 'The two passwords do not match.';
    } else {
        $hash = password_hash($password, PASSWORD_DEFAULT);

        if ($user_id_to_reset > 0) {
            $db->insert("UPDATE users SET password = ? WHERE id = ?", [$hash, $user_id_to_reset]);
        } else {
            $db->insert("UPDATE users SET password = ? WHERE email = ?", [$hash, $email_to_reset]);
        }

        /* any link still floating about is now useless */
        if ($email_to_reset !== '') {
            try { $db->insert("DELETE FROM password_resets WHERE email = ?", [$email_to_reset]); } catch (\Throwable $e) {}
        }
        unset($_SESSION['pwd_reset']);

        $_SESSION['flash_success'] = 'Your password has been changed. You can log in with it now.';
        redirect('login.php');
    }
}
?>

<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">
        <div class="text-center mb-6">
            <?php if ($allowed): ?>
                <div class="w-16 h-16 rounded-2xl bg-emerald-50 text-emerald-600 flex items-center justify-center text-2xl mx-auto mb-4">
                    <i class="fas fa-lock-open"></i>
                </div>
            <?php else: ?>
                <img src="<?php echo htmlspecialchars($company_logo); ?>" alt="Logo" class="h-16 w-auto mx-auto mb-4">
            <?php endif; ?>
            <h2 class="text-2xl font-extrabold text-gray-900">Create a new password</h2>
            <p class="mt-2 text-sm text-gray-600">
                <?php if ($allowed && $who !== ''): ?>
                    Welcome back, <span class="font-semibold text-gray-800"><?php echo htmlspecialchars($who); ?></span> — choose something only you would know.
                <?php elseif ($allowed): ?>
                    Choose something only you would know.
                <?php else: ?>
                    We could not open this page for you.
                <?php endif; ?>
            </p>
            <?php if ($allowed && $via === 'otp'): ?>
                <p class="inline-flex items-center gap-1.5 mt-3 text-[11px] font-bold text-emerald-700 bg-emerald-50 border border-emerald-200 px-3 py-1 rounded-full">
                    <i class="fas fa-circle-check"></i> Mobile number confirmed
                </p>
            <?php endif; ?>
        </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 ($allowed): ?>
        <form method="POST" class="space-y-5">
            <input type="hidden" name="save_password" value="1">
            <?php if ($via === 'token'): ?>
                <input type="hidden" name="token" value="<?php echo htmlspecialchars(sanitize($_GET['token'] ?? $_POST['token'] ?? '')); ?>">
            <?php endif; ?>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">New password</label>
                <input name="password" type="password" required minlength="6" autofocus
                       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="At least 6 characters">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Type it once more</label>
                <input name="confirm_password" type="password" required minlength="6"
                       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="Confirm new password">
            </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">
                Save my new password
            </button>
        </form>
        <?php else: ?>
        <div class="text-center">
            <a href="forgot-password.php" class="inline-block w-full py-3.5 px-4 text-sm font-bold rounded-lg text-white bg-blue-600 hover:bg-blue-700 shadow-md">
                Start again
            </a>
        </div>
        <?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>
    </div>
</div>

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