<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/mailer.php';

apply_cors();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    send_error('Method not allowed.', 405);
}

$input = get_json_input();
require_fields($input, ['email']);
$email = strtolower(clean_str($input['email']));

$pdo = getDbConnection();

$user = $pdo->prepare("SELECT id, full_name FROM users WHERE email = :email AND role = 'USER'");
$user->execute([':email' => $email]);
$row = $user->fetch();

// Always respond success even if the email doesn't exist — prevents
// account enumeration. The OTP is only actually created/sent when the
// account is real.
if ($row) {
    $rateCheck = $pdo->prepare(
        'SELECT COUNT(*) FROM password_resets WHERE email = :email AND created_at > (NOW() - INTERVAL 15 MINUTE)'
    );
    $rateCheck->execute([':email' => $email]);
    if ((int) $rateCheck->fetchColumn() < 5) {
        $otp = generate_otp(6);
        $expiresAt = date('Y-m-d H:i:s', time() + 600);

        $stmt = $pdo->prepare(
            'INSERT INTO password_resets (email, otp, expires_at) VALUES (:email, :otp, :expires_at)'
        );
        $stmt->execute([':email' => $email, ':otp' => $otp, ':expires_at' => $expiresAt]);

        $html = '<div style="font-family:sans-serif;padding:24px;">'
            . '<h2>Reset your password</h2>'
            . '<p>Your password reset code is:</p>'
            . '<div style="font-size:28px;font-weight:700;letter-spacing:6px;margin:16px 0;">' . $otp . '</div>'
            . '<p style="color:#888;font-size:13px;">This code expires in 10 minutes. If you did not request this, ignore this email.</p>'
            . '</div>';
        [$sent, ] = send_mail_via_settings($email, $row['full_name'] ?? '', 'Password reset code', $html);
        if (!$sent) {
            error_log('Password reset email failed for ' . $email);
        }
    }
}

send_success(null, 'If an account exists with this email, a reset code has been sent.');
