<?php

namespace kernel\IGTabel;

use app\helpers\Debug;
use Illuminate\Database\Eloquent\Collection;

class ListJsonTableEloquentCollection
{
    private string|null $jsonStr;
    private array $meta = [];

    /**
     * @param Collection $collection
     * @param array $params
     * @throws \Exception
     */
    public function __construct(Collection $collection, array $params = [])
    {
        if (!isset($params['model'])) {
            throw new \Exception(message: "The parameter model must not be empty");
        }
        $model = new $params['model']();
        $this->meta['columns'] = $params['columns'] ?? $model->labels();
        $this->meta['perPage'] = $params['perPage'] ?? 10;
        $this->meta['currentPage'] = $params['currentPage'] ?? 1;
        $this->meta['baseUrl'] = $params['baseUrl'] ?? $model->table;
        $this->meta['params'] = $params['params'] ?? [];
        $this->meta['actions'] = $params['actions'] ?? [];

        $this->jsonStr = (new JSONCreator($this->meta, $collection->toArray()))->getJson();
    }

    /**
     * @return string|null
     */
    public function getJson(): string|null
    {
        return $this->jsonStr;
    }

}