<?php

namespace App\Http\Controllers;

use App\Helpers\Frontend;
use App\Models\Admin_user;
use App\Models\Otpsession;
use App\Models\User;
use App\Models\Sessionotp;
use App\Helpers\LogActivity;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Carbon;

class AuthController extends Controller
{
    // Login
    public function login()
    {
        return view('login');
    }
    // Login Post
    /*public function makeLogin(Request $Request)
    {
       // return $Request->all();
       
        $validator = Validator::make($Request->all(), [
            'password' => "required",
            'email' => "required|exists:users,email",
            "i_agree"=> "required"
        ]);
        if ($validator->fails()) {
            return back()
                ->withErrors($validator)
                ->withInput();
        }
        $data = array(
            'email' => $Request->email,
            'password' => $Request->password
        );
        
        
        if (Auth::guard('web')->attempt($data)) 
        {
            $res = User::where(['email' => $Request->email])->first();

           
                $data = ['id' => $res->id, 'profile_pics' => $res->profile_pics, 'username' => $res->name, 'email' => $res->email, 'phone' => $res->mobile, 'admin_id' => $res->admin_id, 'user_type' => $res->type];
                
                // dd($data);
                // Log Activity
                
                $logMessage = "user logged in";
               
                LogActivity::addToLog($logMessage);
                //return $logMessage;

                
                $Request->session()->put('loggedIn', $data);
                
                $res["mainSuperAdminMenu"] = "dashboard";
                $res["superadminSubMenu"] = "dashboard";
            
                return redirect()->route('dashboard');
            

            
        } else {
            return back()->with('error', 'invalid Email Or Password!');
        }
    }  */

    public function makeLogin(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'password' => 'required',
            'email' => 'required', // This will be either email or mobile number
            'i_agree' => 'required',
        ]);

        if ($validator->fails()) 
        {
            return back()
                ->withErrors($validator)
                ->withInput();
        }

        // Check if the login identifier is an email or a mobile number
        $loginIdentifier = $request->input('email');
        $loginType = filter_var($loginIdentifier, FILTER_VALIDATE_EMAIL) ? 'email' : 'mobile';

        $data = [
            $loginType => $loginIdentifier,
            'password' => $request->password,
        ];

        if (Auth::attempt($data)) {
            $user = Auth::user();

            // Log Activity
            $logMessage = "User logged in";
            LogActivity::addToLog($logMessage);

            // Store user's information in the session
            $userData = [
                'id' => $user->id,
                'profile_pics' => $user->profile_pics,
                'username' => $user->name,
                'email' => $user->email,
                'phone' => $user->mobile,
                'admin_id' => $user->admin_id,
                'user_type' => $user->user_type,
            ];
            $request->session()->put('loggedIn', $userData);

            // Redirect to dashboard
            return redirect()->route('dashboard');
        } 
        else 
        {
            return back()->with('error', 'Invalid Email or Password!');
        }
    }

    public function visitorOtp(Request $request)
    {
       
        $this->validator = Validator::make($request->all(),[
            "email"=>"required"
        ]);

        if ($this->validator->fails()) 
        {
            return back()->withErrors($this->validator)->withInput();
        }
        else{

        
            $user = User::where('email',$request->email)->orWhere('mobile',$request->email)->first();
            if($user)
            {
                if (filter_var($request->email, FILTER_VALIDATE_EMAIL)) 
                {
                        $otp = rand(1111, 9999); 
                
                        $html = "<div style='border:5px groove blue;text-align:center'><h1>Your opt is : <strong>".$otp."</strong></h1></div>";
                        $resMail = Frontend::sendMailPostal($request->email,"VisitorKrypt Verification OTP",$html);

                        if($resMail)
                        {
                            if (!empty($resMail->message_id))
                            {
                                Sessionotp::create(['message_id'=>$resMail->message_id,'email'=>$request->email,'otp'=>$otp]);
                                return response()->json([
                                    
                                    "message"=>"success",
                                    "email"=>$request->email,
                                    "message_id"=>$resMail->message_id
                                ],200);
                            }
                        }
                        else
                        {
                            return response()->json([
                                "message"=>"failed"
                            ],409);
                        }
                
                } 
                if(preg_match('/^\d{10}$/', $request->email)) 
                {
                        $mobile = $request->email;

                        $KEY = "lJzKBMz0KhRPlmGk";
                        $TMPID = "1207162141508403142";
                        $OTP = rand(1111,9999);
                        $MSG = urlencode("Dear Student, use OTP code $OTP to verify your account, Edukrypt APP");
    
                        $smsLoad = array(
                            "username" => "amitpopli",
                            "password" => "amitpopli",
                            "from" => "EDUKYT",
                            "pe_id"=> "1201160957975132087",
                            "template_id"=> "1207162141508403142",
                            "to" => ["$mobile"],
                            "text" => $MSG,
                            "coding" => "0"
                        );
    
                        $curl = curl_init();
                        curl_setopt_array($curl, array(
                        CURLOPT_URL => 'https://49.50.67.32/smsapi/jsonapi.jsp',
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_ENCODING => '',
                        CURLOPT_MAXREDIRS => 10,
                        CURLOPT_TIMEOUT => 0,
                        CURLOPT_FOLLOWLOCATION => true,
                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                        CURLOPT_CUSTOMREQUEST => 'POST',
                        CURLOPT_POSTFIELDS =>json_encode($smsLoad),
                        CURLOPT_HTTPHEADER => array(
                            'Content-Type: application/json'
                        ),
                        ));
    
                        $response = curl_exec($curl);
        
                        curl_close($curl);
                        $header = json_decode($response);
        
                        // END API
    
                        if (isset($header->Error->ErrorCode)) 
                        {
                                    $resPonse = array(
                                        "status" => 0,
                                        "code" => 204,
                                        "message" => "Something went wrong, please try again!",
                                    );
                                    echo json_encode($resPonse);
                                    exit;
                        }
                        else
                        {
                            //return ($header);
                            $message_id = $header->data->msgid;
                            
                
                            $dataOTP = array(
                                'message_id'	=> 	$message_id,
                                'mobile'		=> 	$mobile,
                                'otp'			=>	$OTP
                            );
                            //$this->db->insert('otp_session',$dataOTP);
                            $res = Sessionotp::create($dataOTP);
                            if($res)
                            {
                                
                                return response()->json([                                   
                                    "message"=>"success",
                                    "email"=>$request->email,
                                    "message_id" =>$message_id
                                ],200);
                            }
                            else
                            {
                                return response()->json([                                    
                                    "message"=>"failed ! Try later"
                                ],404);
                            }
                        }
                    
                }
            }
            else
            {
                return response()->json(["message"=>"failed"],404);
            }
        }
    }

    public function visitorOtpVerify(Request $request)
    {
         
        $this->allData = $request->all();
        
        //return $this->allData;
        $validator = Validator::make($this->allData, [
            'message_id' => 'required',
            'email' => 'required',
            'otp' => 'required'           
        ]);

        if($validator->fails())
        {
            return back()->withErrors($this->validator)->withInput();
        }
        else
        {

            if (filter_var($request->email, FILTER_VALIDATE_EMAIL))
            {
                $this->res = Sessionotp::where([
                    ['message_id','=',$request->message_id],
                    ['otp','=',$request->otp]
                ])->first();
                if($this->res)
                {
                    $otpCreatedAt = Carbon::parse($this->res->created_at);

                    // Add two minutes to the created_at timestamp
                    $twoMinuts = $otpCreatedAt->addMinutes(1);
                    
                    // Get the current date and time
                    $currentDateTime = Carbon::now();
                    if ($twoMinuts->gt($currentDateTime))
                    {
                        
                        return response()->json([
                            "status"=>1,
                            "message"=>"success",
                            "email"=>$request->email
                        ],200);   
                    }
                    else
                    {
                        return response()->json([
                            "status"=>0,
                            "message"=>"OTP expired !"
                        ],200);
                    }
                }
                else
                {
                    return response()->json([
                        "status"=>0,
                        "message"=>"OTP expired !"
                    ],200);
                }
            }
            if(preg_match('/^\d{10}$/', $request->email))
            {
                $this->res = Sessionotp::where([
                    ['message_id','=',$request->message_id],
                    ['otp','=',$request->otp]
                ])->first();
                if($this->res)
                {
                    $otpCreatedAt = Carbon::parse($this->res->created_at);

                    // Add two minutes to the created_at timestamp
                    $twoMinuts = $otpCreatedAt->addMinutes(1);
                    
                    // Get the current date and time
                    $currentDateTime = Carbon::now();
                    if ($twoMinuts->gt($currentDateTime))
                    {
                        return response()->json([
                            "status"=>1,
                            "message"=>"success",
                            "email"=>$request->email
                        ],200);  
                        
                    }
                    else
                    {
                        return response()->json([
                            "status"=>0,
                            "message"=>"OTP expired !"
                        ],200);
                    }
                }
                else
                {
                    return response()->json([
                        "status"=>0,
                        "message"=>"OTP expired !"
                    ],200);
                }
               
            }
           
                
        }   
    }

    public function visitorResetPassword(Request $request)
    {
        $this->allData = $request->all();

        //return $this->allData;

        $this->validator = Validator::make($request->all(), [
            'email' => "required",           
            "password" => 'required|min:6',
            'c_password' => "required|same:password"
        ],
            [
            "c_password.same" => "The password confirmation does not match",
            ]
        );
        
        if ($this->validator->fails()) 
        {
            return back()->withErrors($this->validator)->withInput();
        }
        else
        {
            $password = Hash::make($request->password);
            $this->res = User::where("email",$request->email)->orWhere("mobile",$request->email)->update(["password"=>$password]);
            if($this->res)
            {
                return back()->with("success","Password reset successfully please Login !");
            }
            else
            {
                return back()->with("error","failed !");
            }
        }
    }
    
    
    public function logout(Request $req)
    {
        // Log Activity
        $logMessage = "user logout";
        LogActivity::addToLog($logMessage);
        Auth::logout();
        $req->session()->invalidate();
        $req->session()->regenerateToken();
        return redirect('login');
    }


}
