<?php

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/helpers.php';

if (getMethod() !== 'POST') {
    jsonResponse(false, 'Method not allowed', null, 405);
}

global $pdo;
$config = require __DIR__ . '/../../config/app.php';
$input = getJsonInput();
$email = strtolower(trim($input['email'] ?? ''));

if ($email === '') {
    jsonResponse(false, 'Email is required', null, 422);
}

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

if (!$user) {
    jsonResponse(true, 'If the email exists, reset instructions will be sent');
}

$token = generateToken(32);
$tokenHash = hashToken($token);
$expiresAt = date('Y-m-d H:i:s', strtotime('+' . ((int)$config['auth']['password_reset_ttl_minutes']) . ' minutes'));

$insert = $pdo->prepare('INSERT INTO password_reset_tokens (user_id, token_hash, expires_at, created_at) VALUES (:user_id, :token_hash, :expires_at, NOW())');
$insert->execute([
    'user_id' => $user['id'],
    'token_hash' => $tokenHash,
    'expires_at' => $expiresAt,
]);

jsonResponse(true, 'Password reset token created', [
    'reset_token' => $token,
    'expires_at' => $expiresAt,
]);
