<?php

namespace App\Traits;

trait DataTable
{
    public static function generate($query)
    {
        $event          = json_decode(request()->lazyEvent);
        $offset         = @$event->first;
        $limit          = @$event->rows;
        $searchable     = @$event->searchable;
        $search         = @$event->filters->global->value;
        $query          = $query->when($searchable && $search,function($q) use($search, $searchable){
            $q->whereAny($searchable,"LIKE","%$search%");
        });
        $state_query    = clone $query;
        $data = $query->take($limit)->offset($offset)->get()->map(function($row){
            $row->created_at = $row->created_at->format('d-m-Y');
            return $row;
        });
        return ['data' => $data, 'total' => $state_query->count()];
    }
}
