<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Input;

class XssSanitizer
{
    protected $longNumber = "false";
    protected $negativeNumber = "false";
    protected $emailFormat = "false";

    protected $lnkeys = "";
    protected $nnkeys = "";
    protected $efkeys = "";

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $input = $request->all();
        $path  = $request->path();
        array_walk_recursive($input, function(&$input, $key) use($path){
            if(!is_array($input)){
                if(in_array($key, ['approved_reason_list','exception_doc_list','having_list']) ){
                    $this->longNumber = "false";
                } else {
                    if (!in_array($key, ['docContent','data'])){
                        $input = trim(htmlspecialchars(strip_tags($input)));
                        if(strpos($key,'email') !== false && !in_array($path,['api/application-comment-update'])){
                            $regxEmail = '/^([A-Za-z0-9_\-\.+])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/';
                            if($input != ''){
                                if(!preg_match($regxEmail,$input)){
                                    $this->emailFormat = "true";
                                    $this->efkeys .= str_replace('_', ' ', $key)." ,";
                                }
                            }
                        } else if(!empty($input) && !is_numeric($input)){
                            if((strpos($key,'address') !== false || strpos($key,'notes') !== false || strpos($key,'description') !== false || strpos($key,'comment') !== false || strpos($key,'remarks') !== false || strpos($key,'permanentAddress') !== false || in_array($key, ['job_desc','roles_responsibiltes','req_skills','reason'])) && strlen($input) > 500){
                                $this->longNumber = "true";
                                $this->lnkeys .= str_replace('_', ' ', $key)." ,";
                            } else if(strpos($key,'message') !== false && strlen($input) > 1000){
                                $this->longNumber = "true";
                                $this->lnkeys .= str_replace('_', ' ', $key)." ,";
                            } else if(strlen($input) > 100 && strpos(strtolower($key),'address') === false){
                                $this->longNumber = "true";
                                $this->lnkeys .= str_replace('_', ' ', $key)." ,";
                                if (in_array($key, ['docContent','callback_url', 'curl'])){
                                    $this->longNumber = "false";
                                }
                            }
                        } else if(!empty($input) && is_numeric($input)){
                            if($input < 0 && !in_array($key, ['creditScore'])){
                                $this->negativeNumber = "true";
                                $this->nnkeys .= str_replace('_', ' ', $key)." ,";
                            }
                            if(!in_array($path,['api/check-status/mp','api/check-status/otp']) && !in_array($key,['created_at','updated_at','expire_by','aadhar','aadhaar','aadhaar_card','phone','contact','Mobile','alt_contact_number','contact_number','mobile_number','phone_number','co_applicant_mobile_number','co_applicant_aadhaar_card','phoneNumber','account_number','accountNumber','coApplicantPhoneNumber','coApplicantAadhar','txnUTR']) && $input > 10000000){
                                $this->longNumber = "true";
                                $this->lnkeys .= str_replace('_', ' ', $key)." ,";
                                $input = abs($input);
                            }
                        } else {
                            if($input == '0'){
                                $input = 0;
                            } else {
                                $input = NULL;
                            }
                        }
                    }
                }
            }
        });
        $request->merge($input);

        $this->lnkeys = rtrim($this->lnkeys, ',');
        $this->nnkeys = rtrim($this->nnkeys, ',');
        $this->efkeys = rtrim($this->efkeys, ',');

        if($this->longNumber == "true"){
            if($request->ajax() or $request->is('api/*')){
                return response()->json(['status' => "FAIL", 'error' => 'Bad input', 'message' => 'Input size exceeds for '.$this->lnkeys], 200);
            }
            return redirect()->back()->withErrors(['message' => 'Input size exceeds for '.$this->lnkeys])->withInput(Input::all());
        }else if($this->negativeNumber == "true"){
            if($request->ajax() or $request->is('api/*')){
                return response()->json(['status' => "FAIL", 'error' => 'Bad input', 'message' => 'Input value should be greater than 0 for '.$this->nnkeys], 200);
            }
            return redirect()->back()->withErrors(['message' => 'Input value should be greater than 0 for '.$this->nnkeys])->withInput(Input::all());
        }else if($this->emailFormat == "true"){
            if($request->ajax() or $request->is('api/*')){
                return response()->json(['status' => "FAIL", 'error' => 'Bad input', 'message' => 'Email format error in '.$this->efkeys], 200);
            }
            return redirect()->back()->withErrors(['message' => 'Email format error in '.$this->efkeys])->withInput(Input::all());
        } else {
            return $next($request);
        }
    }
}
