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

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrfVerify();
    $email = trim($_POST['email'] ?? '');
    $turnstileResponse = $_POST['cf-turnstile-response'] ?? '';

    if (!verifyTurnstile($turnstileResponse)) {
        $error = 'Please complete the security check.';
    }

    if (!$error) {
        $ip       = md5($_SERVER['REMOTE_ADDR'] ?? 'unknown');
        $rateFile = __DIR__ . '/data/fam_reset_rate_' . $ip;
        $hits     = file_exists($rateFile) ? (json_decode(file_get_contents($rateFile), true) ?: []) : [];
        $now      = time();
        $hits     = array_filter($hits, fn($t) => ($now - $t) < 60);
        if (count($hits) >= 3) {
        $error = 'Too many requests. Please wait a minute and try again.';
    } else {
        $hits[] = $now;
        file_put_contents($rateFile, json_encode(array_values($hits)));

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Please enter a valid email address.';
        } else {
            $user = getUserByEmail($email);
            if (!$user) {
                $error = "No account found with that email address.";
            } elseif ($user['status'] === 'banned') {
                $error = "This account has been suspended. Please contact support.";
            } else {
                $resetToken = bin2hex(random_bytes(32));
                $user['reset_token'] = password_hash($resetToken, PASSWORD_DEFAULT);
                $user['reset_expires'] = time() + 3600; // 1 hour
                saveUser($user);

                $resetTpl = getEmailTemplate('password_reset');
                if ($resetTpl) {
                    $resetUrl = "https://famgateway.in/reset-password.php?token=" . urlencode($resetToken) . "&u=" . urlencode($user['id']);
                    $body = str_replace(
                        ['{name}', '{email}', '{reset_url}'],
                        [htmlspecialchars($user['name']), htmlspecialchars($user['email']), $resetUrl],
                        $resetTpl['body']
                    );
                    $subject = str_replace(
                        ['{name}', '{email}'],
                        [$user['name'], $user['email']],
                        $resetTpl['subject']
                    );
                    sendSMTPMail($user['email'], $subject, $body, true);
                }
                
                $success = "A password reset link has been sent to your email.";
            }
            
            if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) {
                if ($error) {
                    echo json_encode(['status'=>'error', 'message'=>$error]); exit;
                } else {
                    echo json_encode(['status'=>'success', 'message'=>$success]); exit;
                }
            }
            }
        }
    }

    if ($error && isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) {
        echo json_encode(['status'=>'error', 'message'=>$error]);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php $pageTitle = "Forgot Password — FamGateway"; include 'includes/header.php'; ?>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
<style>
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body { display: flex; min-height: 100vh; background: #f6f8fb; color: #0f172a; font-family: 'Poppins', sans-serif; }

  .auth-left {
    display: none;
    flex: 0 0 460px;
    background: linear-gradient(160deg, #0f172a 0%, #1e3a8a 60%, #1d4ed8 100%);
    position: relative; overflow: hidden;
    padding: 48px 52px;
    flex-direction: column; justify-content: space-between;
  }
  @media (min-width: 900px) { .auth-left { display: flex; } }
  .auth-left-bg {
    position: absolute; inset: 0;
    background: radial-gradient(ellipse at 30% 20%, rgba(59,130,246,0.25) 0%, transparent 55%),
                radial-gradient(ellipse at 80% 80%, rgba(16,185,129,0.15) 0%, transparent 50%);
  }
  .auth-left-grid {
    position: absolute; inset: 0;
    background-image: linear-gradient(rgba(255,255,255,0.03) 1px, transparent 1px),
                      linear-gradient(90deg, rgba(255,255,255,0.03) 1px, transparent 1px);
    background-size: 40px 40px;
  }
  .auth-left-content { position: relative; z-index: 1; }
  .auth-left-brand { display: flex; align-items: center; gap: 12px; margin-bottom: 52px; }
  .auth-left-heading { font-size: 36px; font-weight: 800; line-height: 1.2; letter-spacing: -1px; color: #fff; margin-bottom: 18px; }
  .auth-left-heading span { background: linear-gradient(90deg, #60a5fa, #34d399); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; }
  .auth-left-desc { font-size: 15px; color: #94a3b8; line-height: 1.65; margin-bottom: 40px; }
  .auth-left-footer { position: relative; z-index: 1; font-size: 12px; color: #475569; }

  .auth-right {
    flex: 1; display: flex; flex-direction: column;
    justify-content: center; align-items: center;
    padding: 40px 24px; background: #f6f8fb; position: relative; overflow-y: auto;
  }
  .auth-back {
    position: absolute; top: 24px; left: 24px;
    display: flex; align-items: center; gap: 6px;
    font-size: 13px; font-weight: 500; color: #64748b;
    text-decoration: none; transition: color 0.15s;
    padding: 7px 12px; border-radius: 9px;
    border: 1px solid #e2e8f0; background: #ffffff;
    box-shadow: 0 1px 2px rgba(0,0,0,0.04);
  }
  .auth-back:hover { color: #0f172a; background: #f1f5f9; }
  .auth-form-card {
    width: 100%; max-width: 420px;
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 20px;
    padding: 38px 34px;
    box-shadow: 0 12px 32px -4px rgba(15, 23, 42, 0.08), 0 4px 12px -2px rgba(15, 23, 42, 0.04);
  }
  @media (max-width: 600px) {
    .auth-form-card { padding: 28px 20px; border-radius: 16px; }
  }
  .auth-form-header { margin-bottom: 28px; text-align: center; }
  .auth-form-logo {
    width: 42px; height: 42px; border-radius: 12px;
    background: linear-gradient(135deg, #2563eb, #1e40af);
    display: flex; align-items: center; justify-content: center;
    margin: 0 auto 20px auto; box-shadow: 0 4px 14px rgba(37,99,235,0.35);
  }
  .auth-form-title { font-size: 24px; font-weight: 800; letter-spacing: -0.6px; color: #0f172a; margin-bottom: 6px; }
  .auth-form-subtitle { font-size: 14px; color: #64748b; }
  .form-group { margin-bottom: 16px; }
  .form-label { display: block; font-size: 13px; font-weight: 500; color: #334155; margin-bottom: 6px; }
  .form-input {
    width: 100%; padding: 11px 14px;
    border: 1px solid #e2e8f0; border-radius: 10px;
    font-size: 14px; color: #0f172a; background: #f8fafc;
    transition: all 0.15s; outline: none; font-family: 'Poppins', sans-serif;
  }
  .form-input:focus { border-color: #2563eb; background: #fff; box-shadow: 0 0 0 3px rgba(37,99,235,0.12); }
  .btn-auth {
    width: 100%; padding: 13px; background: #2563eb; color: #fff;
    border: none; border-radius: 12px; font-size: 15px; font-weight: 600;
    cursor: pointer; transition: all 0.15s; box-shadow: 0 2px 8px rgba(37,99,235,0.3);
    margin-top: 6px; font-family: 'Poppins', sans-serif;
  }
  .btn-auth:hover { background: #1d4ed8; transform: translateY(-1px); box-shadow: 0 4px 16px rgba(37,99,235,0.4); }
  .auth-switch { text-align: center; margin-top: 24px; font-size: 14px; color: #64748b; }
  .auth-switch a { color: #2563eb; font-weight: 600; text-decoration: none; }
  .auth-switch a:hover { text-decoration: underline; }
  .alert-error {
    background: #fee2e2; border: 1px solid #fca5a5; color: #dc2626;
    padding: 12px 14px; border-radius: 10px; font-size: 13px; margin-bottom: 20px;
    display: flex; align-items: center; gap: 8px;
  }
  .alert-success {
    background: #dcfce7; border: 1px solid #86efac; color: #166534;
    padding: 12px 14px; border-radius: 10px; font-size: 13px; margin-bottom: 20px;
    display: flex; align-items: center; gap: 8px; line-height: 1.5;
  }
</style>
</head>
<body>

<div class="auth-left">
  <div class="auth-left-bg"></div>
  <div class="auth-left-grid"></div>
  <div class="auth-left-content dash-anim-in" style="opacity:1; animation: dashFadeIn 0.8s ease forwards;">
    <div class="auth-left-brand">
      <img src="assets/img/logo-navbar-bright.png" alt="FamGateway" style="height:30px;width:auto;display:block;object-fit:contain;">
    </div>
    <h1 class="auth-left-heading">Reset your<br><span>password.</span></h1>
    <p class="auth-left-desc">Don't worry, we'll send you a secure link to get back into your account securely.</p>
  </div>
  <div class="auth-left-footer">© <?= date('Y') ?> Aryanispe FamGateway</div>
</div>

<div class="auth-right">
  <a href="login.php" class="auth-back">
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
    Back to Login
  </a>
  <div class="auth-form-card dash-anim-up" style="opacity:1; animation: dashFadeUp 0.6s cubic-bezier(.22,1,.36,1) forwards;">
    <div class="auth-form-header">
      <div class="auth-form-logo" style="background:none;box-shadow:none;width:auto;height:auto;">
        <img src="assets/img/logo-navbar-bright.png" alt="FamGateway" style="height:28px;width:auto;display:block;object-fit:contain;filter:invert(1) hue-rotate(180deg);">
      </div>
      <h2 class="auth-form-title">Forgot Password</h2>
      <p class="auth-form-subtitle">Enter your email to receive a reset link</p>
    </div>

    <?php if ($error): ?>
    <div class="alert-error">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
      <?= htmlspecialchars($error) ?>
    </div>
    <?php endif; ?>

    <?php if ($success): ?>
    <div class="alert-success">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>
      <?= htmlspecialchars($success) ?>
    </div>
    <?php else: ?>
    <form method="POST" action="forgot-password.php" id="forgotForm">
      <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
      <div class="form-group">
        <label class="form-label">Email address</label>
        <input type="email" name="email" class="form-input" placeholder="you@example.com" required autofocus autocomplete="email">
      </div>
      <?php if (defined('TURNSTILE_SITE_KEY') && TURNSTILE_SITE_KEY): ?>
      <div class="cf-turnstile" data-sitekey="<?= TURNSTILE_SITE_KEY ?>" style="margin-bottom: 14px; display: flex; justify-content: center;"></div>
      <?php endif; ?>
      <button type="submit" class="btn-auth" id="forgotBtn">Send Reset Link →</button>
    </form>
    <?php endif; ?>
    
    <p class="auth-switch">Remembered it? <a href="login.php">Sign in</a></p>
  </div>
</div>

<script>
if (window.lucide) { lucide.createIcons(); }

document.getElementById('forgotForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    const form = this;
    const btn = document.getElementById('forgotBtn');
    const originalText = btn.innerHTML;
    
    btn.innerHTML = '<svg class="spin-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg> Sending...';
    btn.style.opacity = '0.8';
    btn.disabled = true;

    try {
        const formData = new FormData(form);
        const [res] = await Promise.all([
            fetch(form.action, {
                method: 'POST',
                body: formData,
                headers: { 'Accept': 'application/json' }
            }),
            new Promise(r => setTimeout(r, 800))
        ]);
        
        const data = await res.json();

        if (data.status === 'success') {
            const successDiv = document.createElement('div');
            successDiv.className = 'alert-success dash-anim-up';
            successDiv.style.animation = 'dashFadeUp 0.4s ease forwards';
            successDiv.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg> ' + data.message;
            
            const oldErr = form.parentElement.querySelector('.alert-error');
            if (oldErr) oldErr.remove();
            
            form.parentNode.insertBefore(successDiv, form);
            form.style.display = 'none';
        } else {
            const errDiv = document.createElement('div');
            errDiv.className = 'alert-error';
            errDiv.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg> ' + (data.message || 'Error occurred');
            
            const oldErr = form.parentElement.querySelector('.alert-error');
            if (oldErr) oldErr.remove();
            
            form.parentNode.insertBefore(errDiv, form);
            if (typeof turnstile !== 'undefined') turnstile.reset();
            btn.innerHTML = originalText;
            btn.disabled = false;
            btn.style.opacity = '1';
        }
    } catch(err) {
        alert("Network Error. Please try again.");
        if (typeof turnstile !== 'undefined') turnstile.reset();
        btn.innerHTML = originalText;
        btn.disabled = false;
        btn.style.opacity = '1';
    }
});
</script>
</body>
</html>
