<?php
require_once __DIR__ . '/includes/functions.php';
startSecureSession();

if (isLoggedIn()) {
    header('Location: dashboard.php');
    exit;
}

$error = '';
$success = '';
$step = isset($_GET['step']) ? (int)$_GET['step'] : 1;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($step === 1) {
        $login = trim($_POST['login'] ?? '');
        
        if (empty($login)) {
            $error = 'Please enter your username or email.';
        } else {
            $user = getUserByEmail($login);
            if (!$user) {
                $user = getUserByUsername($login);
            }
            
            if (!$user) {
                $error = 'No account found with that username or email.';
            } else {
                $otp = saveOTP($user['email'], 'reset');
                if (!sendOTPEmail($user['email'], $otp, 'reset')) {
                    $error = 'Email bhejne mein problem aa rahi hai. Thodi der baad try karo.';
                } else {
                    $_SESSION['reset_email'] = $user['email'];
                    $_SESSION['reset_user_id'] = $user['id'];
                    $step = 2;
                }
            }
        }
    } elseif ($step === 2) {
        $otp = trim($_POST['otp'] ?? '');
        $email = $_SESSION['reset_email'] ?? '';
        
        if (empty($otp)) {
            $error = 'Please enter the verification code.';
        } elseif (strlen($otp) !== 6) {
            $error = 'Verification code must be 6 digits.';
        } elseif (!verifyOTP($email, $otp, 'reset')) {
            $error = 'Invalid or expired verification code.';
        } else {
            $step = 3;
        }
    } elseif ($step === 3) {
        $password = $_POST['password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        
        if (empty($password) || empty($confirmPassword)) {
            $error = 'Please fill in all fields.';
        } elseif (strlen($password) < 6) {
            $error = 'Password must be at least 6 characters.';
        } elseif ($password !== $confirmPassword) {
            $error = 'Passwords do not match.';
        } else {
            $userId = $_SESSION['reset_user_id'] ?? '';
            $user = getUserById($userId);
            
            if ($user) {
                $user['password_hash'] = password_hash($password, PASSWORD_DEFAULT);
                saveUser($user);
                unset($_SESSION['reset_email'], $_SESSION['reset_user_id']);
                $success = 'Password reset successful! You can now login.';
                $step = 4;
            } else {
                $error = 'Something went wrong. Please try again.';
            }
        }
    }
}

$pageTitle = 'Reset Password';
$metaDesc = 'Reset your FamAPI account password securely with email verification.';
include __DIR__ . '/includes/public_header.php';
?>
<style>
.auth-page{min-height:100vh;display:flex;align-items:center;justify-content:center;padding:40px 20px;background:var(--soft)}
.auth-card{width:100%;max-width:420px;background:#fff;border:1px solid var(--line);border-radius:16px;box-shadow:var(--shadow-md);padding:40px 32px}
.auth-header{text-align:center;margin-bottom:32px}
.auth-logo{display:inline-flex;align-items:center;gap:10px;font-weight:800;font-size:22px;color:var(--ink);margin-bottom:16px}
.auth-logo .brand-accent{color:var(--brand)}
.auth-title{font-size:26px;font-weight:800;color:var(--ink);letter-spacing:-.5px;margin-bottom:8px}
.auth-sub{font-size:15px;color:var(--muted)}
.step-indicator{display:flex;justify-content:center;gap:8px;margin-bottom:28px}
.step-dot{width:40px;height:4px;border-radius:2px;background:var(--line);transition:all .3s}
.step-dot.active{background:var(--brand);width:60px}
.step-dot.done{background:var(--green)}
.auth-form{display:flex;flex-direction:column;gap:20px}
.form-group{display:flex;flex-direction:column;gap:6px}
.form-label{font-size:13px;font-weight:600;color:var(--ink)}
.form-input{padding:12px 14px;border:1.5px solid var(--line);border-radius:10px;font-size:15px;font-family:inherit;color:var(--ink);background:#fff;transition:all .2s ease;outline:none}
.form-input:focus{border-color:var(--brand);box-shadow:0 0 0 3px rgba(163,112,252,.15)}
.form-input::placeholder{color:var(--muted-soft)}
.btn-submit{padding:14px 24px;font-size:15px;font-weight:700;border-radius:10px;margin-top:8px}
.otp-inputs{display:flex;gap:8px;justify-content:center}
.otp-inputs input{width:48px;height:56px;text-align:center;font-size:22px;font-weight:700;border:2px solid var(--line);border-radius:12px;background:var(--soft);color:var(--ink);transition:border-color .2s}
.otp-inputs input:focus{border-color:var(--brand);outline:none}
.alert{padding:12px 14px;border-radius:10px;font-size:13.5px;font-weight:500;margin-bottom:20px}
.alert-error{background:#fef2f2;border:1px solid #fecaca;color:#dc2626}
.success-state{text-align:center;padding:20px 0}
.success-icon{width:80px;height:80px;border-radius:50%;background:rgba(16,185,129,.12);display:flex;align-items:center;justify-content:center;margin:0 auto 20px}
.success-icon svg{width:40px;height:40px;color:#10b981}
.success-title{font-size:26px;font-weight:800;color:var(--ink);margin-bottom:8px}
.success-sub{font-size:15px;color:var(--muted);margin-bottom:24px}
.auth-back{text-align:center;margin-top:24px;font-size:14px;color:var(--muted)}
.auth-back a{color:var(--brand);font-weight:600;text-decoration:none}
.auth-back a:hover{text-decoration:underline}
</style>

<div class="auth-page">
  <div class="auth-card">
    <?php if ($step < 4): ?>
    <div class="auth-header">
      <a href="index.php" class="auth-logo">
        <svg width="32" height="32" viewBox="0 0 32 32" fill="none"><rect width="32" height="32" rx="8" fill="#a370fc"/><path d="M8 12l-3 3 3 3M24 12l3 3-3 3M21 8l-2 12" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
        Fam<span class="brand-accent">API</span>
      </a>
      <h1 class="auth-title">
        <?= $step === 1 ? 'Reset password' : ($step === 2 ? 'Enter verification code' : 'Set new password') ?>
      </h1>
      <p class="auth-sub">
        <?= $step === 1 ? 'Enter your username or email to receive a verification code.' : ($step === 2 ? 'We sent a 6-digit code to <strong>' . htmlspecialchars($_SESSION['reset_email'] ?? '') . '</strong>' : 'Enter your new password below.') ?>
      </p>
    </div>

    <div class="step-indicator">
      <div class="step-dot <?= $step >= 1 ? ($step > 1 ? 'done' : 'active') : '' ?>"></div>
      <div class="step-dot <?= $step >= 2 ? ($step > 2 ? 'done' : 'active') : '' ?>"></div>
      <div class="step-dot <?= $step >= 3 ? 'active' : '' ?>"></div>
    </div>

    <?php if ($error): ?>
      <div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <form method="POST" action="forgot-password.php?step=<?= $step ?>" class="auth-form">
      <?php if ($step === 1): ?>
        <div class="form-group">
          <label class="form-label" for="login">Username or Email</label>
          <input class="form-input" type="text" id="login" name="login" placeholder="Enter username or email" required autofocus>
        </div>
        <button type="submit" class="btn btn-primary btn-block btn-submit">Send Verification Code</button>

      <?php elseif ($step === 2): ?>
        <div class="otp-inputs">
          <input type="text" maxlength="1" class="otp-digit" data-index="0" required autofocus>
          <input type="text" maxlength="1" class="otp-digit" data-index="1" required>
          <input type="text" maxlength="1" class="otp-digit" data-index="2" required>
          <input type="text" maxlength="1" class="otp-digit" data-index="3" required>
          <input type="text" maxlength="1" class="otp-digit" data-index="4" required>
          <input type="text" maxlength="1" class="otp-digit" data-index="5" required>
        </div>
        <input type="hidden" name="otp" id="otpHidden">
        <button type="submit" class="btn btn-primary btn-block btn-submit">Verify Code</button>
        <p style="text-align:center;margin-top:16px;font-size:13px;color:var(--muted);">
          Didn't receive code? <a href="forgot-password.php?step=1" style="font-weight:600;">Try again</a>
        </p>

      <?php elseif ($step === 3): ?>
        <div class="form-group">
          <label class="form-label" for="password">New Password</label>
          <input class="form-input" type="password" id="password" name="password" placeholder="At least 6 characters" required>
        </div>
        <div class="form-group">
          <label class="form-label" for="confirm_password">Confirm Password</label>
          <input class="form-input" type="password" id="confirm_password" name="confirm_password" placeholder="Re-enter password" required>
        </div>
        <button type="submit" class="btn btn-primary btn-block btn-submit">Reset Password</button>
      <?php endif; ?>
    </form>

    <div class="auth-back">
      <a href="login.php">← Back to login</a>
    </div>

    <?php elseif ($step === 4): ?>
    <div class="success-state">
      <div class="success-icon">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
      </div>
      <h1 class="success-title">Password Reset!</h1>
      <p class="success-sub">Your password has been successfully reset.</p>
      <a href="login.php" class="btn btn-primary btn-block btn-submit">Sign In Now</a>
    </div>
    <?php endif; ?>
  </div>
</div>

<script>
document.querySelectorAll('.otp-digit').forEach((input, index, inputs) => {
  input.addEventListener('input', (e) => {
    if (e.target.value.length === 1 && index < inputs.length - 1) {
      inputs[index + 1].focus();
    }
    updateOTP();
  });
  input.addEventListener('keydown', (e) => {
    if (e.key === 'Backspace' && !e.target.value && index > 0) {
      inputs[index - 1].focus();
    }
  });
  input.addEventListener('paste', (e) => {
    e.preventDefault();
    const paste = (e.clipboardData || window.clipboardData).getData('text').trim();
    if (/^\d{6}$/.test(paste)) {
      inputs.forEach((inp, i) => inp.value = paste[i]);
      inputs[5].focus();
      updateOTP();
    }
  });
});
function updateOTP() {
  const digits = Array.from(document.querySelectorAll('.otp-digit')).map(i => i.value).join('');
  document.getElementById('otpHidden').value = digits;
}
</script>

<?php include __DIR__ . '/includes/public_footer.php'; ?>