<?php
session_start();
header('Cache-Control: no-store');
require_once '../config/database.php';
require_once '../config/password_reset.php';

$cfg = reset_cfg();
$error = "";
$sentTo = "";        // masked destination
$sentChannel = "";
$prefill = htmlspecialchars($_POST['identifier'] ?? ($_GET['u'] ?? ''));

/* which channels are available */
$emailOn = !empty($cfg['email_enabled']);
$waOn    = !empty($cfg['whatsapp_enabled']);

function mask_email($e){ $p=explode('@',$e); if(count($p)!=2) return $e; $n=$p[0]; $m=strlen($n)<=2?$n[0].'*':substr($n,0,2).str_repeat('*',max(1,strlen($n)-2)); return $m.'@'.$p[1]; }
function mask_phone($p){ $d=preg_replace('/\D+/','',$p); return strlen($d)<=4?$d:str_repeat('*',strlen($d)-4).substr($d,-4); }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $identifier = trim($_POST['identifier'] ?? '');
    $channel    = $_POST['channel'] ?? ($emailOn ? 'email' : 'whatsapp');

    if ($identifier === '') {
        $error = "Please enter your username, email, phone, or Pay ID.";
    } else {
        $user = reset_find_user($pdo, $identifier);
        if (!$user) {
            $error = "No active account found with that information.";
        } elseif ($channel === 'email') {
            if (empty($user['email'])) {
                $error = "There is no email on file for this account. Try WhatsApp instead.";
            } else {
                $code = reset_create_code($pdo, $user['user_id'], 'email');
                if (reset_send_email($user['email'], $user['name'], $code)) {
                    $sentChannel = 'email'; $sentTo = mask_email($user['email']);
                } else {
                    $error = "Could not send the email right now. Please try again later.";
                }
            }
        } else { // whatsapp
            if (!$waOn) {
                $error = "WhatsApp is not available yet. Please use email.";
            } elseif (empty($user['phone'])) {
                $error = "There is no phone number on file for this account.";
            } else {
                $code = reset_create_code($pdo, $user['user_id'], 'whatsapp');
                if (reset_send_whatsapp($user['phone'], $code)) {
                    $sentChannel = 'whatsapp'; $sentTo = mask_phone($user['phone']);
                } else {
                    $error = "Could not send the WhatsApp message right now. Please try again later.";
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Forgot password — Seven Digital</title>
<link rel="manifest" href="/seven-credit-system/manifest.json">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<style>
  *{box-sizing:border-box;margin:0;padding:0;font-family:"Noto Sans Lao",Arial,sans-serif}
  body{background:#b91c1c;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:18px}
  .card{background:#fff;width:100%;max-width:420px;border-radius:18px;padding:24px 22px;box-shadow:0 16px 40px rgba(0,0,0,.25)}
  h1{font-size:20px;color:#111827;margin-bottom:6px}
  p.sub{color:#6b7280;font-size:14px;margin-bottom:18px}
  label{display:block;font-size:12px;font-weight:700;color:#374151;text-transform:uppercase;letter-spacing:.4px;margin:14px 0 6px}
  input[type=text]{width:100%;padding:13px 14px;border:1.5px solid #e5e7eb;border-radius:12px;font-size:15px;outline:none}
  input[type=text]:focus{border-color:#b91c1c}
  .channels{display:flex;gap:10px;margin-top:6px}
  .ch{flex:1}
  .ch input{position:absolute;opacity:0}
  .ch label{display:flex;align-items:center;justify-content:center;gap:6px;border:1.5px solid #e5e7eb;border-radius:12px;padding:12px;margin:0;cursor:pointer;font-size:14px;text-transform:none;letter-spacing:0;color:#111827}
  .ch input:checked + label{border-color:#b91c1c;background:#fee2e2;color:#b91c1c}
  .btn{width:100%;margin-top:18px;padding:14px;background:#b91c1c;color:#fff;border:none;border-radius:12px;font-size:16px;font-weight:800;cursor:pointer}
  .btn:active{opacity:.9}
  .msg{padding:12px 14px;border-radius:10px;font-size:14px;margin-bottom:14px}
  .err{background:#fef2f2;border:1px solid #fecaca;color:#991b1b}
  .ok{background:#ecfdf5;border:1px solid #a7f3d0;color:#065f46}
  a.link{display:block;text-align:center;margin-top:16px;color:#b91c1c;font-weight:700;text-decoration:none;font-size:14px}
</style>
</head>
<body>
<div class="card">
  <h1>Forgot your password?</h1>

  <?php if ($sentChannel): ?>
    <p class="sub">Reset your account password.</p>
    <div class="msg ok">
      We sent a <?= $sentChannel === 'email' ? 'reset code by email to' : 'reset code by WhatsApp to' ?>
      <strong><?= htmlspecialchars($sentTo) ?></strong>.
      Enter it on the next screen along with your new password. It expires in <?= (int)$cfg['code_ttl_minutes'] ?> minutes.
    </div>
    <a class="btn" style="display:block;text-align:center;text-decoration:none;line-height:1.2" href="reset_password.php?u=<?= urlencode($_POST['identifier'] ?? '') ?>">Enter code &amp; set new password</a>
    <a class="link" href="login.php">Back to login</a>
  <?php else: ?>
    <p class="sub">Enter your account and we'll send you a reset code.</p>
    <?php if ($error): ?><div class="msg err"><?= htmlspecialchars($error) ?></div><?php endif; ?>
    <form method="POST" autocomplete="off">
      <label>Username / Email / Phone / Pay ID</label>
      <input type="text" name="identifier" value="<?= $prefill ?>" placeholder="e.g. your phone or Pay ID" required>

      <label>Send the code by</label>
      <div class="channels">
        <?php if ($emailOn): ?>
        <div class="ch"><input type="radio" id="ch-email" name="channel" value="email" checked><label for="ch-email">✉️ Email</label></div>
        <?php endif; ?>
        <?php if ($waOn): ?>
        <div class="ch"><input type="radio" id="ch-wa" name="channel" value="whatsapp" <?= $emailOn ? '' : 'checked' ?>><label for="ch-wa">🟢 WhatsApp</label></div>
        <?php endif; ?>
      </div>

      <button class="btn" type="submit">Send reset code</button>
    </form>
    <a class="link" href="login.php">Back to login</a>
  <?php endif; ?>
</div>
</body>
</html>