<?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';

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.
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]);

    // TODO: send $rawToken via email instead of returning it.
    // e.g. mail($email, 'Reset your Ragreen password', "Reset link: " . APP_URL . "/reset.html?token=$rawToken");
}

$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;
}

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