<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\Controller\Trait;

use Symfony\Component\HttpFoundation\Request;

/**
 * Tolerant readers for optional, user-supplied query parameters.
 *
 * On Symfony 6.4/7 (Mautic 6/7), Request::query->getInt()/getBoolean() throw a
 * BadRequestException (HTTP 400) when the parameter is PRESENT but an empty or
 * non-numeric string (e.g. "?ownerId="). These helpers use the tolerant plain
 * get() and validate/cast manually, returning null/false instead of throwing.
 */
trait QueryParamTrait
{
    /**
     * Reads an optional integer query param. Returns null when the value is
     * missing, empty, whitespace, non-numeric, or zero (treating 0 the same as
     * "no filter", matching the previous "...getInt($key, 0) ?: null" semantics).
     */
    private function queryNullableInt(Request $request, string $key): ?int
    {
        $raw = $request->query->get($key);
        if (null === $raw) {
            return null;
        }

        $value = filter_var(trim((string) $raw), FILTER_VALIDATE_INT);
        if (false === $value || 0 === $value) {
            return null;
        }

        return $value;
    }

    /**
     * Reads an optional boolean flag query param. Missing/''/'0'/'false' → false;
     * '1'/'true'/'yes'/'on' → true.
     */
    private function queryFlag(Request $request, string $key): bool
    {
        $raw = $request->query->get($key);
        if (null === $raw) {
            return false;
        }

        return filter_var(trim((string) $raw), FILTER_VALIDATE_BOOLEAN);
    }
}
