<?php
declare(strict_types=1);

require_once __DIR__ . '/../system/bootstrap.php';
require_once __DIR__ . '/../system/auth.php';
require_once __DIR__ . '/../system/response.php';

try {
    $actor = require_auth($pdo);

    if (!in_array($actor['role_key'], [
        'super_admin',
        'platform_admin',
        'rsp_admin'
    ], true)) {
        error_forbidden('Forbidden');
    }

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

    $userId   = (int)($input['user_id'] ?? 0);
    $password = (string)($input['password'] ?? '');

    if ($userId <= 0 || strlen($password) < 8) {
        error_bad_request('Invalid password');
    }

    $hash = password_hash($password, PASSWORD_DEFAULT);

    $pdo->prepare("
        UPDATE users
        SET password_hash = ?
        WHERE id = ? AND deleted_at IS NULL
    ")->execute([$hash, $userId]);

    invalidate_user_sessions($userId);

    auditLog(
        (int)$actor['id'],
        (int)$actor['company_id'],
        'users',
        'password_reset',
        ['user_id' => $userId]
    );

    success('Password reset');
    invalidate_user_sessions($pdo, (int)$userId);

} catch (Throwable $e) {
    error_log('PASSWORD RESET ERROR: ' . $e->getMessage());
    error_server('Password reset failed');
}
