<?php
/**
 * POST /api/auth/forgot_password.php
 * Body: { email }
 *
 * Generates a reset token valid for 1 hour. In production, email the raw
 * token as a link (e.g. https://yourapp.com/reset.html?token=...). We only
 * store its hash in the DB. Wire up an actual mailer (PHPMailer, etc.)
 * where noted below.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/mailer.php';

only_post_allowed();

$input = get_json_input();
$missing = validate_required($input, ['email']);
if ($missing) {
    send_error('Email is required.', 422);
}

$email = trim($input['email']);
$pdo = Database::connect();

$stmt = $pdo->prepare('SELECT id FROM users WHERE email = ? LIMIT 1');
$stmt->execute([$email]);
$user = $stmt->fetch();

// Always return a generic success message, even if the email isn't found,
// so we don't leak which emails are registered.
$rawToken = null;
if ($user) {
    $rawToken  = bin2hex(random_bytes(32));
    $tokenHash = hash('sha256', $rawToken);
    $expiresAt = date('Y-m-d H:i:s', strtotime('+1 hour'));

    $stmt = $pdo->prepare(
        'INSERT INTO password_resets (user_id, token_hash, expires_at) VALUES (?, ?, ?)'
    );
    $stmt->execute([$user['id'], $tokenHash, $expiresAt]);

    // See register.php - APP_URL already points to the public/ web root,
    // no "/public" segment belongs in this link.
    $resetLink = APP_URL . '/reset-password.html?token=' . $rawToken;
    send_email(
        $email,
        'Reset your Ragreen password',
        "We received a request to reset your Ragreen password.\n\nReset it here:\n$resetLink\n\nThis link expires in 1 hour.\n\nIf you didn't request this, you can safely ignore this email - your password won't change."
    );
}

$response = ['message' => 'If that email exists, a reset link has been sent.'];

// Only for local development/testing so you can verify the flow without SMTP set up.
if (APP_ENV === 'local' && $user) {
    $response['dev_token'] = $rawToken;
    $response['dev_reset_link'] = $resetLink;
}

send_json(true, $response['message'], array_diff_key($response, ['message' => '']));
