<?php

namespace App\Http\Middleware;

use App\Helpers\MiscHelper;
use Closure;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;

class CheckMaxPostSizeExceeded
{
    /**
     * The application instance.
     *
     * @var \Illuminate\Foundation\Application
     */
    protected $app;

    protected $exclude = [
        '/admin/photos/analyse/*',
        '/admin/photos/flip/*',
        '/admin/photos/regenerate-thumbnails/*',
        '/admin/photos/rotate/*'
    ];

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Foundation\Application  $app
     * @return void
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    public function handle(Request $request, Closure $next)
    {
        if (
            $this->isRunningInConsole() ||
            $this->isReading($request) ||
            $this->shouldPassThrough($request)
        )
        {
            return $next($request);
        }

        // Check post limit and see if it may have been exceeded
        $postLimit = MiscHelper::convertToBytes(ini_get('post_max_size'));

        if (
            (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > $postLimit) ||
            (empty($_POST) && empty($_REQUEST))
        )
        {
            $request->session()->flash('error', trans('global.post_max_exceeded'));
            return back();
        }

        return $next($request);
    }

    protected function isRunningInConsole()
    {
        return $this->app->runningInConsole();
    }

    /**
     * Determine if the HTTP request uses a ‘read’ verb.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function isReading(Request $request)
    {
        return in_array($request->method(), ['HEAD', 'GET', 'OPTIONS']);
    }

    protected function shouldPassThrough(Request $request)
    {
        foreach ($this->exclude as $exclude)
        {
            if ($exclude !== '/') {
                $exclude = trim($exclude, '/');
            }

            if ($request->is($exclude)) {
                return true;
            }
        }

        return false;
    }
}