<?php
require_once 'config.php';

if (!empty($_SESSION['patient_id'])) {
    header('Location: ' . SITE_URL . '/patient/dashboard.php');
    exit;
}

// Ensure reset token column exists
$conn->query("ALTER TABLE patients ADD COLUMN IF NOT EXISTS reset_token VARCHAR(64) NULL");
$conn->query("ALTER TABLE patients ADD COLUMN IF NOT EXISTS reset_expires DATETIME NULL");

$step    = 'request'; // request | sent
$errors  = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = clean($_POST['email'] ?? '');
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please enter a valid email address.';
    } else {
        $stmt = $conn->prepare("SELECT id, full_name FROM patients WHERE email = ?");
        $stmt->bind_param('s', $email);
        $stmt->execute();
        $patient = $stmt->get_result()->fetch_assoc();

        if ($patient) {
            $token   = bin2hex(random_bytes(32));
            $expires = date('Y-m-d H:i:s', strtotime('+1 hour'));
            $conn->prepare("UPDATE patients SET reset_token=?, reset_expires=? WHERE id=?")
                 ->execute() ?: null;
            $upd = $conn->prepare("UPDATE patients SET reset_token=?, reset_expires=? WHERE id=?");
            $upd->bind_param('ssi', $token, $expires, $patient['id']);
            $upd->execute();

            $reset_link = SITE_URL . '/reset-password.php?token=' . $token;
            $step = 'sent';
            // In production: send email. For now show link directly.
            $_SESSION['reset_link'] = $reset_link;
            $_SESSION['reset_name'] = $patient['full_name'];
        } else {
            // Don't reveal if email exists
            $step = 'sent';
            $_SESSION['reset_link'] = null;
            $_SESSION['reset_name'] = '';
        }
    }
}

$show_link = $_SESSION['reset_link'] ?? null;
$show_name = $_SESSION['reset_name'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Forgot Password - HealthLink</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
  <style>
    body { background: linear-gradient(135deg,#e6f5f3,#f0f9ff); min-height: 100vh; font-family: 'Segoe UI',sans-serif; display: flex; align-items: center; justify-content: center; }
    .auth-card { background: white; border-radius: 20px; padding: 40px; max-width: 440px; width: 100%; box-shadow: 0 8px 40px rgba(11,123,110,0.12); }
    .brand { text-align: center; margin-bottom: 28px; }
    .brand-icon { width: 60px; height: 60px; border-radius: 16px; background: linear-gradient(135deg,#0B7B6E,#13A898); display: flex; align-items: center; justify-content: center; margin: 0 auto 12px; font-size: 1.8rem; color: white; }
    .brand h4 { font-weight: 800; color: #0D2340; margin: 0; }
    .brand p { color: #718096; font-size: 0.88rem; margin: 4px 0 0; }
  </style>
</head>
<body>
<div class="auth-card">
  <div class="brand">
    <div class="brand-icon">🔑</div>
    <h4>Forgot Password</h4>
    <p>We'll help you reset it</p>
  </div>

  <?php if ($step === 'sent'): ?>
    <?php if ($show_link): ?>
      <div class="alert alert-success">
        <i class="fas fa-check-circle me-2"></i>
        Hello <strong><?= htmlspecialchars($show_name) ?></strong>! Click the link below to reset your password.<br>
        <small class="text-muted">(In production this would be sent via email)</small>
      </div>
      <div class="alert alert-warning">
        <strong>Your Reset Link:</strong><br>
        <a href="<?= htmlspecialchars($show_link) ?>" style="word-break:break-all;font-size:0.82rem;"><?= htmlspecialchars($show_link) ?></a><br>
        <small class="text-muted">Expires in 1 hour</small>
      </div>
      <a href="<?= htmlspecialchars($show_link) ?>" class="btn btn-success w-100">
        <i class="fas fa-key me-1"></i> Reset My Password
      </a>
    <?php else: ?>
      <div class="alert alert-info">
        <i class="fas fa-info-circle me-2"></i>
        If that email is registered, a reset link has been sent.
      </div>
    <?php endif; ?>
    <div class="text-center mt-3">
      <a href="<?= SITE_URL ?>/patient-login.php">← Back to Login</a>
    </div>
    <?php unset($_SESSION['reset_link'], $_SESSION['reset_name']); ?>
  <?php else: ?>
    <?php if (!empty($errors)): ?>
      <div class="alert alert-danger"><?= htmlspecialchars($errors[0]) ?></div>
    <?php endif; ?>
    <form method="POST">
      <div class="mb-3">
        <label class="form-label fw-600">Registered Email Address</label>
        <input type="email" name="email" class="form-control form-control-lg" placeholder="you@example.com" required autofocus>
      </div>
      <button type="submit" class="btn btn-success w-100 btn-lg">
        <i class="fas fa-paper-plane me-1"></i> Send Reset Link
      </button>
    </form>
    <div class="text-center mt-3">
      <a href="<?= SITE_URL ?>/patient-login.php">← Back to Login</a>
    </div>
  <?php endif; ?>
</div>
</body>
</html>
