<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class Paginate {
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next) {

        $page_size = $request->query("page_size");
        $page_number = $request->query("page_number");

        $response = $next($request);

        if($request->isMethod("GET") && $response instanceof JsonResponse && is_array($response->getData())) {
            $data = [
                "total" => sizeof($response->getData()),
                "page_size" => $page_size,
                "page_number" => $page_number,
                "data" => ($page_number!=null && $page_size!=null) ? array_slice($response->getData(), $page_size*$page_number, $page_size) : $response->getData()
            ];
            $response->setData($data);
        }

        return $response;
    }
}
