<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Validator;

trait ApiResponser 
{
    private function successResponse($data, $code)
    {
        return response()->json($data, $code);
    }

    protected function errorResponse($message, $code)
    {
        return response()->json(['error' => $message, 'code' => $code], $code);
    }

    protected function showAll(Collection $collection, $code = 200)
    {
        $collection = $this->paginate($collection);

        return $this->successResponse([
            'data' => $collection['items'], 
            'pagination' => $collection['pagination']
        ], $code);
    }

    protected function showOne(Model $instance, $code = 200)
    {
        return response()->json(['data' => $instance], $code);
    }

    protected function paginate(Collection $collection)
    {
        $reglas = [
            'per_page' => 'integer|min:2|max:30'
        ];
        
        Validator::validate(request()->all(), $reglas);

        $page = LengthAwarePaginator::resolveCurrentPage();

        $perPage = request()->has('per_page') ? (int) request()->per_page : 5;

        $results = $collection->slice(($page - 1) * $perPage, $perPage)->values();

        $paginated = new LengthAwarePaginator($results, $collection->count(), $perPage, $page, [
            'path' => LengthAwarePaginator::resolveCurrentPath(),
        ]);
        
        $paginated->appends(request()->all());

        $info = $paginated->toArray();
        unset($info["data"]);

        return [
            'items' => $paginated->items(),
            'pagination' => $info
        ];
    }
}