<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['POST']);
$input = hw_input_json();
$email = hw_sanitize_string($input['email'] ?? '');
if (!hw_validate_email($email)) hw_json(['message' => 'Valid email is required'], 422);

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

    // Always respond success to avoid email enumeration
    $genericResponse = ['message' => 'If an account exists for this email, a reset link has been sent.'];

    if (!$user) {
        hw_json($genericResponse);
    }

    $userId = (int)$user['id'];
    // Create reset token
    $selector = bin2hex(random_bytes(9));
    $token = bin2hex(random_bytes(32));
    $tokenHash = hash('sha256', $token);
    $expires = (new DateTimeImmutable('+1 hour'))->format('Y-m-d H:i:s');

    // Upsert: delete existing, insert new
    $pdo->beginTransaction();
    $pdo->prepare('DELETE FROM password_resets WHERE user_id = ?')->execute([$userId]);
    $pdo->prepare('INSERT INTO password_resets (user_id, selector, token_hash, expires_at, created_at) VALUES (?, ?, ?, ?, NOW())')
        ->execute([$userId, $selector, $tokenHash, $expires]);

    // Audit
    $pdo->prepare('INSERT INTO audit_logs (user_id, action, meta) VALUES (?, ?, JSON_OBJECT("selector", ?, "ip", ?))')
        ->execute([$userId, 'password_reset_requested', $selector, $_SERVER['REMOTE_ADDR'] ?? ''] );
    $pdo->commit();

    // Compose reset link (email integration to be added later)
    $base = rtrim(hw_config()['app']['base_url'] ?: '', '/');
    $resetLink = $base . '/reset.html?selector=' . urlencode($selector) . '&token=' . urlencode($token);

    // In production, send via email/SMS. For now, return hint for testing environments only (omit in prod)
    hw_json($genericResponse + ['testing' => ['reset_link' => $resetLink]]);
} catch (Throwable $e) {
    if ($pdo && $pdo->inTransaction()) $pdo->rollBack();
    hw_json(['message' => 'Server error', 'error' => $e->getMessage()], 500);
}
