<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Session;

class FileMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(!empty($_FILES)){
            foreach($_FILES as $fileInfo){
                if(is_array($fileInfo['name'])){
                    foreach($fileInfo['name'] as $fileName){
                        if(isset($fileName[0]) && $fileName[0] != ''){
                            $fileNamef = explode('.',$fileName[0]);
                            $arraySize = count($fileNamef);
                            $dName = $fileNamef[$arraySize-1];
                            if(!in_array($dName,['xls','xlsx','jpg','jpeg','png','pdf','doc','docx','odt','mp3','mp4','gif','tif','tiff','bmp','svg','webm'])){
                                Session::flash('error', 'Document extension does not supported... Check document type before uploading');
                                return redirect()->back()->withErrors(['message' => 'Document extension does not supported for '.$fileName[0]]);
                            }
                        }
                    }
                    foreach($fileInfo['size'] as $fileSize){
                        if(isset($fileSize[0]) && $fileSize[0] != ''){
                            if($fileSize[0] > 20971520){
                                Session::flash('error', 'Document size does not supported... Check document size before uploading');
                                return redirect()->back()->withErrors(['message' => 'Document size does not supported for '.$fileName[0]]);
                            }
                        }
                    }
                }else{
                    if($fileInfo['name'] != ''){
                        $fileName = explode('.',$fileInfo['name']);
                        $arrayCount = count($fileName);
                        $name = $fileName[$arrayCount-1];
                        if(!in_array($name,['xls','xlsx','jpg','jpeg','png','pdf','doc','docx','odt','mp3','mp4','gif','tif','tiff','bmp','svg','webm'])){
                            Session::flash('error', 'Document extension does not supported... Check document type before uploading');
                            return redirect()->back();
                        }
                        if($fileInfo['size'] > 20971520){
                            Session::flash('error', 'Document size does not supported... Check document size before uploading');
                            return redirect()->back();
                        }
                    }
                }
            }
        }
        return $next($request);
    }
}
