<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use App\Models\UserIp;
use App\Models\OtpLog;
use App\Models\LoginLog;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Session;
use App\Models\User;
use Symfony\Component\Process\Process;


class Login extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('Front/login');
    }

    public function verifyUserAuth(Request $request)  {
        
        $credentials = $request->validate([
            'mobile' => 'required|regex:/[0-9]{10}/|digits:10',
            'password' => 'required',
        ]);
        Session::start();
        if (Auth::attempt($credentials)) {

            // include(base_path('macpackage.php'));
            // echo $macAddress = getMacAddress();die;
            
            $request->session()->regenerate();
            $user = Auth::user();

            LoginLog::create([
                "userId"=> $user->id,
                "mobileNumber"=> $request->mobile,
                "otp"=> $request->password,
                "type"=>"LOGIN_SUCCESS",
                "ipAddress"=>$request->ip()
            ]);

            if($user->user_type == 0 ||$user->user_type == 4){
                
                    // Password is valid
                Session::put('checkLoginStatus', "");
           
                //return redirect()->intended('admin/dashboard');
                return redirect()->intended('verify-otp');                
            }
            if($user->user_type == 1){
                return redirect()->intended('user/dashboard');
            }
            if($user->user_type == 3){
                return redirect()->intended('agent/dashboard');
            }
            if($user->user_type == 2){
                $ipAddress = $request->ip();
                $checkIp = UserIp::where(['userId'=>$user->id,'ipAddress'=>$ipAddress])->first();
                if(empty($checkIp)){
                    auth()->logout();
                    return back()->withErrors([
                        'mobile' => 'Your Ip is not whitelisted '.$ipAddress,
                    ])->onlyInput('mobile');
                }
                return redirect()->intended('verify-otp');  
                //return redirect()->intended('staff/dashboard');
            }
            
        }

        LoginLog::create([
            "userId"=> 0,
            "mobileNumber"=> $request->mobile,
            "otp"=> $request->password,
            "type"=>"LOGIN_FAILED",
            "ipAddress"=>$request->ip()
        ]);
 
        return back()->withErrors([
            'mobile' => 'The provided credentials do not match our records.',
        ])->onlyInput('mobile');
    }

    public function logout()
    {
        Session::flush();
        auth()->logout();        
        return redirect('/login');
    }

    public function verifyOtp(Request $request)
    {
        if($_POST)
        {
            $otp = $request['otp'];
            $pintype = $request['pintype'];
            
            $user = Auth::user();
            //echo Hash::make($otp);die;
            //echo $user->lpin; die;
            // $this->getPhysicalAddress();
            // print_r($output);die;

            if($pintype == "PIN")
            {
                if (Hash::check($otp, $user->mpin)) {
                // if ($otp==$user->mpin) {
                    Session::start();
                    Session::put('checkLoginStatus', "pass");
                } else {

                    LoginLog::create([
                        "userId"=> $user->id,
                        "mobileNumber"=> $user->mobile,
                        "otp"=> $otp,
                        "type"=>"PIN_FAILED",
                        "ipAddress"=>$request->ip()
                    ]);
                    auth()->logout();
                    return redirect()->route('login')->with('success','Invalid login pin.');
                    die;
                }                
            }

            if($pintype == "OTP")
            {
                $user = Auth::user();
                $userId = $user->id;
                $getData = OtpLog::latest()->where("userId",$userId)->first();
                if (Hash::check($otp, $getData->otp)) {
                    Session::start();
                    Session::put('checkLoginStatus', "pass");
                } else {
                    LoginLog::create([
                        "userId"=> $user->id,
                        "mobileNumber"=> $user->mobile,
                        "otp"=> $otp,
                        "type"=>"OTP_FAILED",
                        "ipAddress"=>$request->ip()
                    ]);
                    auth()->logout();
                    return redirect()->route('login')->with('success','Invalid Otp.');
                    die;
                }                
            }

            if($user->user_type == 0){
                return redirect()->intended('admin/dashboard');              
            }
            if($user->user_type == 1){
                return redirect()->intended('user/dashboard');
            }
            if($user->user_type == 3){
                return redirect()->intended('agent/dashboard');
            }
            if($user->user_type == 2){                 
                return redirect()->intended('staff/dashboard');
            }
            if($user->user_type == 4){                 
                return redirect()->intended('sub-admin/dashboard');
            }
            die;

        }
        return view('Front/verifyotp');
    }

    public function generateMpin($id)
    {
        
        $user = User::find($id);

    if ($user) {
    $mpin = rand(10000000, 99999999); 
      $lpin = rand(100000, 999999); 

    
    echo "LPIN: " . $lpin;
    echo "------";
    echo "MPIN: " . $mpin;
    echo "------";

    $hashedLpin = Hash::make($lpin);
    $hashedMpin = Hash::make($mpin);

  
    $data = [
        'lpin' => $hashedLpin,
        'mpin' => $hashedMpin
    ];

   
    $user->update($data);

    echo "LPIN and MPIN updated successfully!";
} else {
    echo "User not found!";
}
         
         
        //$mobile = $request['mobile'];
        //$user = User::findOrFail($id);
        //$mobile = "+91".$user->mobile;

        // $lpin = rand(100000, 999999);
        // echo $mpin = rand(10000000, 99999999);
        // echo "------";
        // echo Hash::make($mpin);die;
        // $data = ['lpin'=>Hash::make($mpin),'mpin'=>Hash::make($lpin)];
        
        // $user->update($data);        

        // echo $message = "Hi, your login pin is ".$lpin." and your Mpin is ".$mpin;
        // $sendData = ["mobile"=>$mobile,"message"=>$message];

        // $curl = curl_init();

        // curl_setopt_array($curl, array(
        // CURLOPT_URL => 'http://crm.seospay.in/api/v1/whatsapp/sendmessage',
        // 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 => $sendData,
        // ));

        // $response = curl_exec($curl);

        // curl_close($curl);
        // //echo $response;

        // echo "otp send successfully";

    }

    public function sendOtpLogin(Request $request)
    {
        $user = Auth::user();
        $userId = $user->id;
        $mobile = "+91".$user->mobile;

        $otp = rand(100000, 999999);
        // $message = "Thanks for login Your login otp is ".$otp;
        // $sendData = ["mobile"=>$mobile,"message"=>$message];

        OtpLog::create([
            "userId"=> $userId,
            "mobileNumber"=> $mobile,
            "otp"=> Hash::make($otp),
            "type"=>"LOGIN"
        ]);
       // die($message);
            
        $msgText = "Dear $otp your OTP for validate your login is $otp. Don't share this with anyone.";
    $encodedMsgText = urlencode($msgText);

    $smsURL = "http://www.smsfortius.in/api/mt/SendSMS?APIKey=6KqmwttL602PoJSbqBo16Q&senderid=PAYNIM&channel=Trans&DCS=0&flashsms=0&number=$mobile&text=$encodedMsgText&route=14";

    $postData = array(
        'text' => $msgText,
        'number' => $mobile
    );

    $postDataString = http_build_query($postData);

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $smsURL,
        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 => $postDataString, // Send POST data
        CURLOPT_HTTPHEADER => array(
            'Content-Length: ' . strlen($postDataString), // Include Content-Length header
            'Content-Type: application/x-www-form-urlencoded' // Set Content-Type header if needed
        ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

        echo $response;

       // echo "otp send successfully";
    }
    
}
