<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Log;
use Session;
use App\Helper\Helper;
use Illuminate\Http\Request;
use Socialite;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Facades\Mail;
use Carbon\Carbon;// Add this

class ApiLoginController extends Controller
{
    public function Six(Request $request){
    $otp_id = $request->query('otp_id'); // or $request->get('otp_id')
    $mobile = $request->query('mobile'); // or $request->get('mobile')
        return view ('login.six-digit-mobile-otp',compact('otp_id','mobile'));
    }


    public function index(Request $request)
    {

        Session::forget('userMenu');
        Session::forget('permissions');
        return view('login.login');
    }
    public function index1(){
        return view('login.login1');
    }
    public function register(){
        return view('login.register');
    }



    public function store(Request $request)
    {
        try
        {
            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'company_name' => 'required|string|max:255',
                'email' => 'required|email|max:255',
                'password' => 'required|min:6|confirmed',
                'g-recaptcha-response' => app()->environment('production') ? 'nullable|captcha' : '',
            ], [
                'g-recaptcha-response.required' => 'Please complete the reCAPTCHA verification.',
                'g-recaptcha-response.captcha' => 'reCAPTCHA verification failed. Please try again.',
            ]);


            $url = env('API_URL') . 'prospect/register';

            $body = [
                'name'         => trim($request->name),
                'email'        => trim($request->email),
                'company_name' => trim($request->company_name),
                'password'     => $request->password,
            ];


            Log::info('register body', ['body' => $body]);
            $response = Helper::PostApi($url, $body);

            Log::info('register response', ['response' => $response]);

            Session::put('verification_code', $response->data->verification_code ?? null);
            Session::put('otp_generated_at', Carbon::now());
            Session::put( 'email', $request->email);
            Session::put('name', $request->name);
            Session::put('company_name', $request->company_name);
            Session::put('plainPassword', $request->password);

            if (isset($response->success) && $response->success)
            {
                return response()->json([
                    'success' => true,
                    'message' => $response->message ?? 'Registered successfully!',
                    //'redirect_url' => route('otp.verify') // ✅ optional, if you want to redirect via JS
                ]);
            }
            else if (isset($response->errors) && !empty($response->errors))
            {
                return response()->json([
                    'success' => false,
                    'message' => $response->errors['email'][0] ?? 'Validation failed.',
                    'errors'  => $response->errors
                ], 422);
            }

            else
            {
                return response()->json([
                    'success' => false,
                    'message' => $response->message ?? 'Registration failed.'
                ], 400);
            }
        }
        catch (\Illuminate\Validation\ValidationException $e)
        {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors(),
            ], 422);
        }
        catch (\Throwable $e)
        {
            return response()->json([
                'success' => false,
                'message' => 'Server error: '.$e->getMessage(),
            ], 500);
        }
    }


public function Google(Request $request)
{
    $email = Session::get('email');
    $otp_verified = Session::get('otp_verified');
//dd($otp_verified);
    // ✅ If already verified, don't come back to OTP page
    if (Session('otp_verified') === true) {
        return redirect()->route('login')->with('success', 'Email already verified!');
    }


    // ✅ Default: GET → Show OTP page
    return view('login.google-otp', [
        'email'             => $email,
        'verification_code' => session('verification_code'),
    ]);
}
public function verifyGoogleOtp(Request $request)
{
    if ($request->action === 'verify') {
        $otp = $request->otp; // use otp directly from ajax
        $email = $request->email ?? Session::get('email');
        $password = $request->password ?? Session::get('password');

        Log::info('email generatedd',['email'=>$email]);

        $url  = env('API_URL') . 'prospect/verify';
        $body = [
            'email'        => $email,
            'otp'          => $otp,
            'name'   => Session::get('name'),
            'company_name' => Session::get('company_name'),

        ];


        try {
            $response = Helper::PostApi($url, $body);
            $data     = is_object($response) ? (array) $response : $response;
Log::info("data reached",['data'=>$data]);

            if (!empty($data['status']) && $data['status'] == 1) {
                Session::forget('verification_code');
                Session::forget('otp_generated_at');
                Session::put('otp_verified', true);
                Session::put('email_otp_id', $data['email_otp_id']);
//Log::info("email_otp_id reached", ['email_otp_id' => $data['email_otp_id']]);
                if ($request->ajax()) {
                    return response()->json([
                        'success' => true,
                        'message' => $data['message'] ?? 'Email verified successfully!',
                        'redirect_url' => route('login')
                    ]);
                }

                return redirect()->route('login')
                                 ->with('success', $data['message'] ?? 'Email verified successfully!');
            } else {
                return response()->json([
                    'success' => false,
                    'message' => $data['message'] ?? 'Invalid OTP'
                ], 422);
            }
        } catch (\Exception $ex) {
            return response()->json([
                'success' => false,
                'message' => $ex->getMessage()
            ], 500);
        }
    }


   if ($request->action === 'resend') {
    $url = env('API_URL') . 'prospect/resend';
    $body = ['email' => $request->email ?? Session::get('email')];

    try {
        $response = Helper::PostApi($url, $body);
        $data     = is_object($response) ? (array) $response : $response;

        Log::info('verified response', ['response' => $data]);

        if (!empty($data['success']) && $data['success']) {
            Session::put('verification_code', $data['data']->verification_code ?? null);
            Session::put('otp_generated_at', \Carbon\Carbon::now());

            return response()->json([
                'success' => true,
                'message' => $data['message'] ?? 'OTP resent successfully!'
            ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => $data['message'] ?? 'Resend failed.'
            ], 422);
        }
    } catch (\Throwable $e) {
        return response()->json([
            'success' => false,
            'message' => 'Server error: ' . $e->getMessage()
        ], 500);
    }
}


    return response()->json(['success' => false, 'message' => 'Invalid action'], 400);
}




    function apilogin(Request $request)
    {
        $username = $request->email;
        $password = $request->password;
        $url = env('API_URL') . 'authentication';
        // Build validation rules conditionally.
        $rules = [
            'email'    => 'required|string|max:255',
            'password' => 'required|string|max:255',
        ];

        // Only require captcha when this is NOT an auto-login internal request
         if (! $request->has('auto_login') || $request->auto_login != true) {
             $rules['g-recaptcha-response'] = app()->environment('production') ? 'nullable|captcha' : 'nullable|captcha';
         }
         // Custom messages (captcha messages will only be used when rule applied)
         $messages = [
             'g-recaptcha-response.required' => 'Please complete the reCAPTCHA verification.',
             'g-recaptcha-response.captcha'  => 'reCAPTCHA verification failed. Please try again.',
         ];

        // Validate (will throw ValidationException on failure)
        $validated = $request->validate($rules, $messages);
        $body = array(
            'email' => $username,
            'password' => $password,
            'userAgent' => $request->userAgent(),
            'clientIp' => $request->ip(),
            'device'   => 'desktop_app'
        );

        $result = Helper::PostApi($url, $body);


        try {
            $result = Helper::PostApi($url, $body);
            // echo "<pre>";print_r($result);die;
            if ($result->success) {
                $url = env('API_URL') . "/user-logout";
                $body_logout = array('logout_all' => 1);
                try {
                    $logout = Helper::PostApi($url, $body_logout);
                } catch (\Exception $exception) {
                }

                if ($result->data->enable_2fa == 1) {
                    Session::put('userTokenAllSession', $result);
                    return redirect('/otp');
                }
               if ($result->data->allow_google_authenticator == 1) {
                    Session::put('userTokenAllSession', $result);
                    return redirect('/allow-google-auth');
                }
                Session::put('tokenId', $result->data->token);
                Session::put('parentId', $result->data->parent_id);  //parent id is roleid
                Session::put('id', $result->data->id);
                Session::put('extension', $result->data->extension);
                Session::put('dialer_mode', $result->data->dialer_mode);
                Session::put('role', $result->data->role);
                Session::put('emailId', $result->data->email);
                Session::put('vm_drop', $result->data->vm_drop);
                Session::put('level', $result->data->level);
                Session::put('permissions', (array)$result->data->permissions);
                Session::put('showQuestion', TRUE);

                Session::put('display_name', $result->data->first_name . ' ' . $result->data->last_name);
                Session::put('private_identity', $result->data->alt_extension);
                Session::put('password', $result->data->secret);
                Session::put('realm', $result->data->domain);
                Session::put('public_identity', "sip:" . $result->data->alt_extension . "@" . $result->data->domain);
                Session::put('websocket_server_url', "wss://" . $result->data->domain . ":8089/ws");
                Session::put('ice_servers', "{ url:'turn:" . env('ICE_SERVER_USER') . "@" . $result->data->domain . "', credential:'" . env('ICE_SERVER_PASSWORD') . "'}");
                Session::put('timezone_session', 0);
                Session::put('affilaite_link_token', $result->data->affiliate_link);
                Session::put('currency', $result->data->currency ?? '');

                return redirect('/dialer-new');
                //return redirect('/dashboard');


            } else {
                $message = $result->message;
                if (isset($result->errors)) {
                    foreach ($result->errors as $error) {
                        $message .= " $error";
                    }
                }
                return redirect()->route('login')->with('message', $message);
            }
        } catch (\Exception $exception) {
            Log::error($exception->getMessage(), [
                "url" => $url,
                "email" => $username
            ]);
            return redirect()->route('login')->with('message', 'Error code - (authentication): Oops something went wrong :( Please contact your administrator.)');
        }
    }

    public function switchClient($clientId)
    {
        $url = env('API_URL') . "/switch-client/$clientId";
        $response = Helper::PostApi($url, null, null);
        if ($response->success) {
            Session::put('parentId', $response->data->parent_id);
            $permissions = Session::get('permissions');
            $permission = $permissions[$response->data->role];
            Session::put('role', $permission->roleName);
        }
        return response()->json($response);
    }

    function dashboard()
    {
        return view('dashboard.dashboard');
    }

    function otp(Request $request)
    {
        $mobile = '';
        $sessions = Session::all();
        $result = $sessions['userTokenAllSession'];
        //echo "<pre>";print_r($result);die;

        $errors = new MessageBag();

        if ($request->isMethod('POST')) {
            try {
                $url = env('API_URL') . 'validate-otp';
                // In your controller
                $otp = $request->digit1 . $request->digit2 . $request->digit3 . $request->digit4 . $request->digit5 . $request->digit6;



                $body = array(
                    'type' => 'phone',
                    'otpId' => $result->data->otpId,
                    'id' => $result->data->id,
                    'code' => $otp,
                );
                $response = Helper::PostApi($url, $body);

                if ($response->success) {
                    //


                    Session::put('tokenId', $result->data->token);
                    Session::put('parentId', $result->data->parent_id);  //parent id is roleid
                    Session::put('id', $result->data->id);
                    Session::put('extension', $result->data->extension);
                    Session::put('dialer_mode', $result->data->dialer_mode);
                    Session::put('role', $result->data->role);
                    Session::put('emailId', $result->data->email);
                    Session::put('vm_drop', $result->data->vm_drop);
                    Session::put('level', $result->data->level);
                    Session::put('permissions', (array) $result->data->permissions);
                    Session::put('showQuestion', TRUE);
                    Session::put('display_name', $result->data->first_name . ' ' . $result->data->last_name);
                    Session::put('private_identity', $result->data->alt_extension);
                    Session::put('password', $result->data->secret);
                    Session::put('realm', $result->data->domain);
                    Session::put('public_identity', "sip:" . $result->data->alt_extension . "@" . $result->data->domain);
                    Session::put('websocket_server_url', "wss://" . $result->data->domain . ":8089/ws");
                    Session::put('ice_servers', "{ url:'turn:" . env('ICE_SERVER_USER') . "@" . $result->data->domain . "', credential:'" . env('ICE_SERVER_PASSWORD') . "'}");
                    Session::put('timezone_session', 0);
                    Session::put('affilaite_link_token', $result->data->affiliate_link);


                    return redirect('/dialer-new');
                    //return redirect('/dashboard');
                } else {
                    return redirect('/otp')->with('message', $response->errors[0]);
                }
            } catch (RequestException $ex) {
                $errors->add("error", $ex->getMessage());
                return redirect('/otp')->with('message', $message);
            }
        }

        //$mobile = substr($result->data->mobile,-4);
        return view('login.six-digit-mobile-otp', compact("result"));
    }
    function GoogleAuth(Request $request)
    {
        $sessions = Session::all();
        $result = $sessions['userTokenAllSession'];
        //echo "<pre>";print_r($result);die;

        $errors = new MessageBag();

        if ($request->isMethod('POST')) {
            try {
                $url = env('API_URL') . 'validate-google-auth';

                $body = array(
                    'type' => 'email',
                    'id' => $result->data->id,
                    'email' => $result->data->email,

                        'digit1'    => $request->digit1,
                        'digit2'    => $request->digit2,
                        'digit3'    => $request->digit3,
                        'digit4'    => $request->digit4,
                        'digit5'    => $request->digit5,
                        'digit6'    => $request->digit6,

                );

                $response = Helper::PostApi($url, $body);
            //echo "<pre>";print_r($response);die;

                if ($response->success) {
                    Session::put('tokenId', $result->data->token);
                    Session::put('parentId', $result->data->parent_id);  //parent id is roleid
                    Session::put('id', $result->data->id);
                    Session::put('extension', $result->data->extension);
                    Session::put('dialer_mode', $result->data->dialer_mode);
                    Session::put('role', $result->data->role);
                    Session::put('emailId', $result->data->email);
                    Session::put('vm_drop', $result->data->vm_drop);
                    Session::put('level', $result->data->level);
                    Session::put('permissions', (array)$result->data->permissions);
                    Session::put('showQuestion', TRUE);
                    Session::put('display_name', $result->data->first_name . ' ' . $result->data->last_name);
                    Session::put('private_identity', $result->data->alt_extension);
                    Session::put('password', $result->data->secret);
                    Session::put('realm', $result->data->domain);
                    Session::put('public_identity', "sip:" . $result->data->alt_extension . "@" . $result->data->domain);
                    Session::put('websocket_server_url', "wss://" . $result->data->domain . ":8089/ws");
                    Session::put('ice_servers', "{ url:'turn:" . env('ICE_SERVER_USER') . "@" . $result->data->domain . "', credential:'" . env('ICE_SERVER_PASSWORD') . "'}");
                    Session::put('timezone_session', 0);
                    Session::put('affilaite_link_token', $result->data->affiliate_link);
                    Session::put('webphone', $result->data->webphone);


                    return redirect('/dialer-new');
                } else {
                    return redirect('/allow-google-auth')->with('message', $response->message);
                }
            } catch (RequestException $ex) {
                $errors->add("error", $ex->getMessage());
                return redirect('/allow-google-auth')->with('message', $message);
            }
        }

        //$mobile = substr($result->data->mobile,-4);

        return view('login.allow-google-auth', compact("result"));
    }
    public function logout()
    {
        $url = env('API_URL') . "/user-logout";
        $body = array('logout_all' => 1);
        try {
            $logout = Helper::PostApi($url, $body);
        } catch (\Exception $exception) {
        }
        Session::flush();
        return redirect('/');
    }


    public function getIp(Request $request)
    {
        foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$key]) as $ip) {
                    $ip = trim($ip); // just to be safe
                    if (strlen($ip) > 8 && (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false)) {
                        return $ip;
                    }
                }
            }
        }
        return $request->ip();
    }
      public function redirectToGoogle()
    {
        return Socialite::driver('google')->stateless()->redirect();

    }

    // Handle the callback from Google
public function handleGoogleCallback()
{
    try {
        $googleUser = Socialite::driver('google')->stateless()->user();
        $body = [
            'user_id' => $googleUser->id,
            'id' => $googleUser->id,
            'email' => $googleUser->email,
            'access_token' => $googleUser->token,
            'name' => $googleUser->name
        ];

        $url = env('API_URL') . 'auth/google/callback';
        $response = Helper::PostApi($url, $body);
         //echo "<pre>";print_r($response);die;


        // Ensure $response is an object and not an array
        if ($response) {
            // Case 1: If backend returned prospect with email_otp_id
            if (isset($response->email_otp_id)) {
                Session::put('google_id', $response->google_id);
                Session::put('email', $response->email);
                // Save verification/session data
                Session::put('otp_verified', true);
                Session::put('email_otp_id', $response->email_otp_id);

                // Store user details in session for later use
                if (isset($response->prospect)) {
                    Session::put('email', $response->prospect->email);
                    Session::put('name', $response->prospect->name);
                    Session::put('company_name', $response->prospect->company_name);
                }
                return redirect('/register');
            }
            // Case 2: If backend returned an authenticated user with token
    // Save user and token to session
                    Session::put('tokenId', $response->user->token);
                   Session::put('parentId', $response->user->parent_id);
                    Session::put('id', $response->user->id);
                    Session::put('extension', $response->user->extension);
                    Session::put('role', $response->user->role);
                    Session::put('emailId', $response->user->email);
                    Session::put('vm_drop', $response->user->vm_drop);
                    Session::put('level', $response->user->user_level);
                    Session::put('display_name', $response->user->first_name.' '.$response->user->last_name);
                    Session::put('private_identity', $response->user->alt_extension);
                    Session::put('public_identity', "sip:".$response->user->alt_extension."@".$response->user->domain);
                    Session::put('realm', $response->user->domain);
                    Session::put('websocket_server_url', "wss://".$response->user->domain.":8089/ws");
                    Session::put('affilaite_link_token', $response->user->affiliate_link);
                    Session::put('webphone', $response->user->webphone);

                    // Optional: if these are also present directly or nested
                    Session::put('dialer_mode', $response->dialer_mode ?? '');
                    Session::put('password', $response->secret ?? '');
                    Session::put('permissions', (array) ($response->permissions ?? []));



                    return redirect('/dialer-new');
} else {
    return redirect('/')->withErrors(['message' => 'Invalid login response from backend.']);
}

} catch (\GuzzleHttp\Exception\ClientException $e) {
    $response = $e->getResponse();
    $body = json_decode($response->getBody()->getContents());
    $errorMessage = $body->error ?? 'This Email is not registered with us.';

    return redirect('/')->withErrors(['message' => $errorMessage]);
} catch (\Exception $e) {
    \Log::error('Google callback error: ' . $e->getMessage());
    return redirect('/')->withErrors(['message' => 'Google authentication failed.']);
}
}
public function SendMobileOtp(Request $request)
{
    try {


        $url = env('API_URL') . 'prospect/sendotp/mobile';
        // keep only digits
        $rawPhone = $request->phone;
        $cleanPhone = preg_replace('/\D/', '', $rawPhone);
        $body = [
            'phone' => $cleanPhone,
            'country_code'=>$request->countryCode
        ];


        $response = Helper::PostApi($url, $body);

        //echo "<pre>";print_r($response);die;

          Session::put('mobile', $cleanPhone);
        Session::put('country_code', $request->countryCode);


        if (isset($response->success) && $response->success) {
            return response()->json([
                'success' => true,
                'message' => $response->message ?? 'Otp sent successfully!',
                //'redirect_url' => route('otp.verify') // ✅ optional, if you want to redirect via JS
            ]);
        } else if (isset($response->errors) && !empty($response->errors)) {
    return response()->json([
        'success' => false,
        'message' => $response->errors['email'][0] ?? 'Validation failed.',
        'errors'  => $response->errors
    ], 422);
}

else
{
            return response()->json([
                'success' => false,
                'message' => $response->message ?? 'Otp failed.'
            ], 400);
        }

    } catch (\Illuminate\Validation\ValidationException $e) {
        // Return validation errors as JSON
        return response()->json([
            'success' => false,
            'message' => 'Validation failed',
            'errors' => $e->errors(),
        ], 422);
    } catch (\Throwable $e) {
        return response()->json([
            'success' => false,
            'message' => 'Server error: '.$e->getMessage(),
        ], 500);
    }
}
public function verifyMobileOtp(Request $request)
{ Log::info('reached mobile verify ',[Session::get('email_otp_id')]);
      $rawPhone = $request->phone;
        $cleanPhone = preg_replace('/\D/', '', $rawPhone);
    if ($request->action === 'verify') {
        $otp = $request->otp; // use otp directly from ajax
        $phone = $cleanPhone ?? Session::get('mobile');
        $email = Session::get('email');
        $email_otp_id  = Session::get('email_otp_id');
        $plainPassword = Session::get('plainPassword');

        //Log::info('email generatedd',['email'=>$email]);

        $url  = env('API_URL') . 'prospect/verify/mobile';
        $body = [
            'phone'        => $phone,
            'otp'          => $otp,
            'email'        => $email,
            'email_otp_id' => $email_otp_id,
            'plainPassword' => $plainPassword,
        ];

        try {
            $response = Helper::PostApi($url, $body);
            $data     = is_object($response) ? (array) $response : $response;

            if (!empty($data['status']) && $data['status'] == 1) {
                Session::forget('verification_code');
                Session::forget('otp_generated_at');
                Session::put('otp_verified', true);
                Session::put('email',  value: $email);
                Session::put('plainPassword', $plainPassword);

                if ($request->ajax()) {
                    return response()->json([
                        'success' => true,
                        'email' => $email,
                        'password' => $plainPassword,
                        'message' => $data['message'] ?? 'Phone  number verified successfully!',
                    ]);
                }

                return redirect()->route('login')
                                 ->with('success', $data['message'] ?? 'Phone number verified successfully!');
            } else {
                return response()->json([
                    'success' => false,
                    'message' => $data['message'] ?? 'Invalid OTP'
                ], 422);
            }
        } catch (\Exception $ex) {
            return response()->json([
                'success' => false,
                'message' => $ex->getMessage()
            ], 500);
        }
    }


   if ($request->action === 'resend') {
    $url = env('API_URL') . 'prospect/resend/mobile';
    $body = [
            'phone' => Session::get('mobile'),
            'country_code'=>Session::get('country_code')
        ];

    try {
        $response = Helper::PostApi($url, $body);
        $data     = is_object($response) ? (array) $response : $response;

        Log::info('verified response', ['response' => $data]);

        if (!empty($data['success']) && $data['success']) {
            Session::put('verification_code', $data['data']->verification_code ?? null);
            Session::put('otp_generated_at', \Carbon\Carbon::now());

            return response()->json([
                'success' => true,
                'message' => $data['message'] ?? 'OTP resent successfully!'
            ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => $data['message'] ?? 'Resend failed.'
            ], 422);
        }
    } catch (\Throwable $e) {
        return response()->json([
            'success' => false,
            'message' => 'Server error: ' . $e->getMessage()
        ], 500);
    }
}


    return response()->json(['success' => false, 'message' => 'Invalid action'], 400);
}

}
