<?php


namespace App\Models;


class CollectionModel
{
    /**
     * Generate a data table response.
     *
     * @param array $data The data to be displayed in the table.
     * @param int $recordsTotal The total number of records without filtering.
     * @param int $recordsFiltered The total number of records after filtering.
     * @param string|null $error An optional error message to be included in the response.
     * @return array The data table response containing the draw count, total records, filtered records,
     *               the data, and a CSRF token (in case it is regenerated).
     */
    public static function datatable(array $data, int $recordsTotal, int $recordsFiltered, string $error = null)
    {
        $req = service('request');
        $reqData = $req->getPostGet('data') ?? [];
        $draw = $reqData['draw'] ?? $req->getPostGet('draw') ?? 1;

        $response = [
            'draw' => $draw,
            'recordsTotal' => $recordsTotal,
            'recordsFiltered' => $recordsFiltered,
            'data' => $data,
            'token' => csrf_hash(), // in case the CSRF token is regenerated
        ];

        if (!empty($error)) {
            $response['error'] = $error;
        }

        return $response;
    }
}