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

hw_require_method(['POST']);
$input = hw_input_json();
$selector = hw_sanitize_string($input['selector'] ?? '');
$token = hw_sanitize_string($input['token'] ?? '');
$newPassword = (string)($input['password'] ?? '');

if (!$selector || !$token) hw_json(['message' => 'Invalid reset link'], 422);
if (strlen($newPassword) < 8) hw_json(['message' => 'Password must be at least 8 characters'], 422);

try {
    $pdo = hw_db();
    $stmt = $pdo->prepare('SELECT pr.user_id, pr.token_hash, pr.expires_at, u.email FROM password_resets pr JOIN users u ON u.id = pr.user_id WHERE pr.selector = ? LIMIT 1');
    $stmt->execute([$selector]);
    $row = $stmt->fetch();

    if (!$row) hw_json(['message' => 'Invalid or expired link'], 400);
    if (strtotime($row['expires_at']) < time()) hw_json(['message' => 'Reset link has expired'], 400);

    $calcHash = hash('sha256', $token);
    if (!hash_equals($row['token_hash'], $calcHash)) hw_json(['message' => 'Invalid token'], 400);

    $pdo->beginTransaction();
    // Update password
    $pdo->prepare('UPDATE users SET password_hash = ?, updated_at = NOW() WHERE id = ?')
        ->execute([hw_hash_password($newPassword), (int)$row['user_id']]);

    // Delete used token
    $pdo->prepare('DELETE FROM password_resets WHERE user_id = ?')
        ->execute([(int)$row['user_id']]);

    // Audit
    $pdo->prepare('INSERT INTO audit_logs (user_id, action, meta) VALUES (?, ?, JSON_OBJECT("email", ?, "selector", ?))')
        ->execute([(int)$row['user_id'], 'password_reset_completed', $row['email'], $selector]);

    $pdo->commit();

    hw_json(['message' => 'Password has been reset successfully']);
} catch (Throwable $e) {
    if ($pdo && $pdo->inTransaction()) $pdo->rollBack();
    hw_json(['message' => 'Server error', 'error' => $e->getMessage()], 500);
}
