<?php
/**
 * POST /api/auth/reset_password.php
 * Body: { token, password }
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';

only_post_allowed();

$input = get_json_input();
$missing = validate_required($input, ['token', 'password']);
if ($missing) {
    send_error('Token and new password are required.', 422);
}

if (strlen($input['password']) < 8) {
    send_error('Password must be at least 8 characters.', 422);
}

$tokenHash = hash('sha256', $input['token']);
$pdo = Database::connect();

$stmt = $pdo->prepare(
    'SELECT id, user_id FROM password_resets
     WHERE token_hash = ? AND used_at IS NULL AND expires_at > NOW()
     LIMIT 1'
);
$stmt->execute([$tokenHash]);
$reset = $stmt->fetch();

if (!$reset) {
    send_error('This reset link is invalid or has expired.', 400);
}

$passwordHash = password_hash($input['password'], PASSWORD_BCRYPT);

$pdo->beginTransaction();
try {
    $stmt = $pdo->prepare('UPDATE users SET password_hash = ? WHERE id = ?');
    $stmt->execute([$passwordHash, $reset['user_id']]);

    $stmt = $pdo->prepare('UPDATE password_resets SET used_at = NOW() WHERE id = ?');
    $stmt->execute([$reset['id']]);

    $pdo->commit();
} catch (Throwable $e) {
    $pdo->rollBack();
    send_error('Could not reset password. Please try again.', 500);
}

send_json(true, 'Your password has been reset. You can now log in.');
