<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Laravel\Socialite\Facades\Socialite;
use App\Models\User;
use App\Http\Services\EmailService;
use App\Models\AppSession;

class LogInController extends Controller
{

    protected $emailService;
    public function __construct(EmailService $emailService)
    {
        parent::__construct();
        $this->emailService = $emailService;
    }

    public function logIn(Request $request)
    {

        return view('app.auth.log-in');
    }
    public function processLogIn(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required|string'
        ]);
        $userLogInResponse = $this->callJava('/api/auth/logInStandard', [
            'email' => $request->get('email'),
            'password' => $request->get('password')
        ], null);

        if (!@$userLogInResponse['success']) {
            return redirect()->back()->with('error', $userLogInResponse['message'])->withInput($request->all());
        }

        $sessionKey = $userLogInResponse['data'];
        Cookie::queue(config('app.sessionKeyName'), $sessionKey);

        return redirect()->to(route('admin.dashboard'));
    }
    public function processLogOut(Request $request)
    {
        $sessionKey = Cookie::get(config('app.sessionKeyName'));
        $this->callJava('/api/auth/logOut', [], $sessionKey);
        Cookie::forget(config('app.sessionKeyName'));
        return redirect()->to(route('index'));
    }    

    public function logInWithGoogle(Request $request)
    {
        return Socialite::driver('google')->redirect();
    }

    public function processLogInWithGoogle(Request $request)
    {

        $user = null;
        try {
            $user = Socialite::driver('google')->user();
        } catch (\Exception $ex) {
            return redirect()->back()->with('error', 'Unable to complete the process');
        }

        $userAlreadyExists = User::where('google_login_email', $user['email'])->first();
        if(!$userAlreadyExists){
            return redirect()->to(route('log-in'))->with('error', 'No such admin account!');
        }
        if($userAlreadyExists && !$userAlreadyExists->is_super_admin){
            return redirect()->to(route('log-in'))->with('error', 'You do not  have sufficient priviledges to log in!');
        }
        $userUidToEnableGoogleLogIn = $request->session()->get('user_uid_to_enable_google_log_in');

        if ($userUidToEnableGoogleLogIn) {
            $request->session()->forget('user_uid_to_enable_google_log_in');
            $enableGoogleLoginResponse = $this->callJava('/api/auth/enableLoginWithGoogle', [
                'googleLoginEmail' => $user['email'],
                'googleDataJson' => json_encode($user)
            ], $this->sessionKey);

            if (!@$enableGoogleLoginResponse['success']) {
                return redirect()->to(route('my-account.log-in-settings'))->with('error', $enableGoogleLoginResponse['message'] ?? 'Enable Google log in failed!');
            }
            return redirect()->to(route('my-account.log-in-settings'))->with('success', 'Google login has been enabled.');
        }else {
            $userLogInResponse = $this->callJava('/api/auth/logInWithGoogle', [
                'name' => $user['name'],
                'googleLoginEmail' => $user['email'],
                'detailJson' => json_encode($user),
                'ipAddress' => $request->ip(),
                'userAgent' => $request->header('User-Agent')
            ], null);


            if (!@$userLogInResponse['success']) {
                return redirect()->back()->with('error', $userLogInResponse['message'])->withInput($request->all());
            }

            $sessionKey = $userLogInResponse['data'];
            $appSession = AppSession::where('session_key', $sessionKey)->first();
            $newUser = $appSession->user;

            if($newUser && !$userAlreadyExists){
                
              }
            
            Cookie::queue(config('app.sessionKeyName'), $sessionKey);

            return redirect()->to(route('dashboard'));
        }

    }

    public function logInWithFacebook(Request $request)
    {
        return Socialite::driver('facebook')->redirect();
    }

    public function processLogInWithFacebook(Request $request)
    {

        try {
            $user = Socialite::driver('facebook')->user();
        } catch (\Exception $ex) {
            return redirect()->back()->with('error', 'Unable to complete the process');
        }

        $userAlreadyExists = User::where('facebook_login_email', $user['email'])->first();
        $userUidToEnableFacebookLogIn = $request->session()->get('user_uid_to_enable_facebook_log_in');
        if ($userUidToEnableFacebookLogIn) {
            $request->session()->forget('user_uid_to_enable_facebook_log_in');
            $enableFacebookLoginResponse = $this->callJava('/api/auth/enableLoginWithFacebook', [
                'facebookLoginEmail' => $user['email'],
                'facebookDataJson' => json_encode($user)
            ], $this->sessionKey);

            if (!@$enableFacebookLoginResponse['success']) {
                return redirect()->to(route('my-account.log-in-settings'))->with('error', $enableFacebookLoginResponse['message'] ?? 'Enable Facebook log in failed!');
            }
            return redirect()->to(route('my-account.log-in-settings'))->with('success', 'Facebook login has been enabled.');
        }else {
            $userLogInResponse = $this->callJava('/api/auth/logInWithFacebook', [
                'name' => $user['name'],
                'facebookLoginEmail' => $user['email'],
                'detailJson' => json_encode($user),
                'ipAddress' => $request->ip(),
                'userAgent' => $request->header('User-Agent')
            ], null);


            if (!@$userLogInResponse['success']) {
                return redirect()->back()->with('error', $userLogInResponse['message'])->withInput($request->all());
            }

            $sessionKey = $userLogInResponse['data'];
            $appSession = AppSession::where('session_key', $sessionKey)->first();
            $newUser = $appSession->user;

            if($newUser && !$userAlreadyExists){
                
              }

            Cookie::queue(config('app.sessionKeyName'), $sessionKey);

            return redirect()->to(route('my-account.index'));
        }
      
    }

    public function forgotPassword(Request $request)
    {

        return view('app.auth.forgot-password');
    }
    public function processForgotPassword(Request $request)
    {
        $request->validate([
            'email' => 'required|email'
        ]);

        $email = $request->get('email');

        //call java
        $this->callJava('/api/auth/requestPasswordReset', [
            'emailAddress' => $email
        ], null);

        $user = User::where('email', $email)->first();
        if ($user) {
            $this->emailService->sendUserPasswordResetEmail($user);
        }
        return redirect()->to(route('forgot-password-success'));
    }

    public function forgotPasswordSuccess(Request $request)
    {

        return view('app.auth.forgot-password-success');
    }

    public function resetPassword(Request $request, $passwordResetToken)
    {
        return view('app.auth.reset-password', compact('passwordResetToken'));
    }
    public function processResetPassword(Request $request)
    {
        $request->validate([
            'passwordResetToken' => 'required',
            'newPassword' => 'required',
            'newPasswordConfirmation' => 'required'
        ]);

        //get credentials
        $passwordResetToken = $request->get('passwordResetToken');
        $newPassword = $request->get('newPassword');
        $newPasswordConfirmation = $request->get('newPasswordConfirmation');

        $user = User::where('password_reset_token', $passwordResetToken)->first();
        if(!$user) return redirect()->back()->with('error', 'Invalid token');

        //call java
        $resetPasswordResponse = $this->callJava('/api/auth/resetPassword', [
            'emailAddress' => $user->email,
            'passwordResetToken' => $passwordResetToken,
            'newPassword' => $newPassword,
            'confirmNewPassword' => $newPasswordConfirmation,
        ], null);

        if (!@$resetPasswordResponse['success']) {
            return redirect()->back()->with('error', $resetPasswordResponse['message'])->withInput($request->all());
        }

        return redirect()->to(route('log-in'))->with('success', "Your password has been updated.");
    }
}
