<?php

namespace App\Support;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DataTable
{
    public static function isDataTableRequest(Request $request): bool
    {
        return $request->ajax() || $request->has('draw');
    }

    public static function draw(Request $request): int
    {
        return max(0, (int) $request->input('draw', 0));
    }

    public static function start(Request $request): int
    {
        return max(0, (int) $request->input('start', 0));
    }

    public static function length(Request $request, int $default = 25): int
    {
        $length = (int) $request->input('length', $default);

        return $length > 0 ? $length : $default;
    }

    public static function globalSearch(Request $request): ?string
    {
        return self::normalize($request->input('search.value'));
    }

    public static function columnSearch(Request $request, int $index): ?string
    {
        return self::normalize($request->input("columns.$index.search.value"));
    }

    public static function order(Request $request, int $defaultIndex = 0, string $defaultDir = 'asc'): array
    {
        $index = (int) $request->input('order.0.column', $defaultIndex);
        $dir = strtolower((string) $request->input('order.0.dir', $defaultDir)) === 'desc' ? 'desc' : 'asc';

        return [$index, $dir];
    }

    public static function response(Request $request, int $recordsTotal, int $recordsFiltered, array $data): JsonResponse
    {
        return response()->json([
            'draw' => self::draw($request),
            'recordsTotal' => $recordsTotal,
            'recordsFiltered' => $recordsFiltered,
            'data' => $data,
        ]);
    }

    protected static function normalize(mixed $value): ?string
    {
        if (! is_string($value)) {
            return null;
        }

        $value = trim($value);

        return $value === '' ? null : $value;
    }
}
