<?php

namespace App\Http\Responses;

class ReportOutputData
{
    /**
     * Executing the query and getting the output data.
     *
     * @param mixed  $data   Query
     * @param array $orderBy  Column to order the results by
     * @param int    $count    Number of records to fetch
     * @return mixed
     */
    public function getOutputData($data, $orderBy = ['created_at' => 'desc'], $count = '0')
    {
        $start = request('start');
        $limit = request('length');

        if ($limit != -1) {
            $data = $data->skip($start)->take($limit);
        }

        if ($count != 0) {
            $data = $data->take($count);
        }

        // Convert the associative order by array into a string
        $orderByString = implode(', ', array_map(function ($column, $direction) {
            return $column . ' ' . $direction;
        }, array_keys($orderBy), $orderBy));

        $data = $data->orderByRaw($orderByString);

        return $data->get();
    }

    /**
     * Applies pagination to the assets query and returns the paginated results along with the total count.
     *
     * @param \Illuminate\Database\Eloquent\Builder $assets The assets query to be paginated.
     * @return array An array containing the paginated assets and the total count of assets.
     */
    public function applyPagination($assets)
    {
        // Pagination
        $start = request('start', 0);
        $limit = request('length', -1);
        $count = $assets->count();

        if ($limit != -1) {
            $assets = $assets->offset($start)->limit($limit)->get();
        }

        return compact('assets', 'count');
    }
}
