<?php

class DataTableRequest {
    public static function fromRequest(int $defaultLength = 25, int $maxLength = 100): array {
        $draw = (int)($_REQUEST['draw'] ?? 1);
        $start = max(0, (int)($_REQUEST['start'] ?? 0));
        $length = (int)($_REQUEST['length'] ?? $defaultLength);
        if ($length <= 0) {
            $length = $defaultLength;
        }
        $length = min($length, max(1, $maxLength));
        $search = trim($_REQUEST['search']['value'] ?? '');

        return [
            'draw' => $draw,
            'start' => $start,
            'length' => $length,
            'search' => $search !== '' ? $search : null,
        ];
    }

    public static function respond(int $draw, int $recordsTotal, int $recordsFiltered, array $data): void {
        if (ob_get_level() > 0) {
            ob_clean();
        }
        header('Content-Type: application/json; charset=utf-8');
        $json = json_encode([
            'draw' => $draw,
            'recordsTotal' => $recordsTotal,
            'recordsFiltered' => $recordsFiltered,
            'data' => $data,
        ], JSON_INVALID_UTF8_SUBSTITUTE);
        echo $json !== false
            ? $json
            : '{"draw":1,"recordsTotal":0,"recordsFiltered":0,"data":[],"error":"Unable to encode table data."}';
        exit;
    }
}
