<?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;
$input = getJsonInput();
$token = (string)($input['token'] ?? '');
$newPassword = (string)($input['new_password'] ?? '');

if ($token === '' || $newPassword === '') {
    jsonResponse(false, 'Token and new password are required', null, 422);
}

$tokenHash = hashToken($token);
$stmt = $pdo->prepare('SELECT * FROM password_reset_tokens WHERE token_hash = :token_hash AND used_at IS NULL LIMIT 1');
$stmt->execute(['token_hash' => $tokenHash]);
$reset = $stmt->fetch();

if (!$reset) {
    jsonResponse(false, 'Invalid reset token', null, 401);
}

if (strtotime((string)$reset['expires_at']) < time()) {
    jsonResponse(false, 'Reset token expired', null, 401);
}

$hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
$updateUser = $pdo->prepare('UPDATE users SET password = :password, updated_at = NOW() WHERE id = :id');
$updateUser->execute([
    'password' => $hashedPassword,
    'id' => $reset['user_id'],
]);

$markUsed = $pdo->prepare('UPDATE password_reset_tokens SET used_at = NOW() WHERE id = :id');
$markUsed->execute(['id' => $reset['id']]);

jsonResponse(true, 'Password reset successfully');
