<?php

require_once __DIR__ . '/../../core/api_bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(false, 'Invalid request method.');
}

$input = json_decode(file_get_contents('php://input'), true);

if (
    empty($input['email']) ||
    empty($input['new_password'])
) {
    json_response(false, 'Email and new password required.');
}

$email = trim($input['email']);
$newPassword = password_hash($input['new_password'], PASSWORD_DEFAULT);

/* ---------------------------------------------------------
   CHECK USER EXISTS
---------------------------------------------------------- */

$stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
$stmt->execute([$email]);

$user = $stmt->fetch();

if (!$user) {
    json_response(false, 'User not found.');
}

/* ---------------------------------------------------------
   UPDATE PASSWORD
---------------------------------------------------------- */

$stmt = $pdo->prepare("
    UPDATE users
    SET password_hash = ?
    WHERE email = ?
");

$stmt->execute([$newPassword, $email]);

json_response(true, 'Password reset successful.');