<?php

namespace App\Http\Controllers;

use App\Lib\Backend;
use App\Models\AppSession;
use App\Models\CompanyPro;
use App\Models\PotentialPro;
use App\Models\Pro;
use App\Models\ProHrInvitation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;

class LoginController extends Controller
{

    public function login(Request $request){
        return view('login');
    }

    public function sendSmsAuthToken(Request $request){
        $cellNumber = $request->get('cell_number');
        $cellNumber = preg_replace("/[^0-9]/", "", $cellNumber);

        
        // $request->validate([
        //     'g-recaptcha-response' => 'required|recaptcha'
        // ]);

        $javaResponse = $this->callJava($request, '/potentialPro/createAndSendSmsAuthToken', [
            'cellNumber'=>$cellNumber
        ]);


        if(!$javaResponse['success']){
            return redirect()->back()->withInput($request->input())->with('message', $javaResponse['message']);
        }

        Cookie::queue('current_cell_number', $cellNumber, 300);
        return redirect()->to(route('confirm-auth-token'));
    }

    public function resendSmsAuthToken(Request $request){
        $cellNumber = $request->cookie('current_cell_number');

        $javaResponse = $this->callJava($request, '/potentialPro/createAndSendSmsAuthToken', [
            'cellNumber'=>$cellNumber
        ]);


        if(!$javaResponse['success']){
            return $this->fail($javaResponse['message']);
        }

        return $this->pass();

    }

    public function confirmAuthToken(Request $request){
        $cellNumber = $request->cookie('current_cell_number');
        $maskedCellNumber = str_pad(substr($cellNumber, -4), strlen($cellNumber), '*', STR_PAD_LEFT);
        return view('confirm-auth-token',compact('maskedCellNumber'));
    }

    public function processConfirmAuthToken(Request $request){
        $confirmationToken = $request->get('confirmation_token');
        $cellNumber = $request->cookie('current_cell_number');

        $javaResponse = $this->callJava($request, '/potentialPro/confirmSmsAuthToken', [
            'confirmationToken'=>$confirmationToken,
            'cellNumber' => $cellNumber,
        ]);

        if(!$javaResponse['success']){
            return redirect()->back()->withInput($request->input())->with('message', $javaResponse['message']);
        }

        Cookie::queue('current_confirmation_token', $confirmationToken, 300);

        $potentialPro = PotentialPro::where('cell_number_confirmation_token', $confirmationToken)->first();

        //if potential pro -> account-setup
        if($potentialPro){
            return redirect()->to(route('account-setup'));
        }

        $existingPro = Pro::where('cell_number', $cellNumber)->first();
        $existingProAppSession = AppSession::where('pro_id', $existingPro->id)->where('two_step_sms_auth_token', $confirmationToken)->first();
        return redirect()->to(config('stag.authUrl').'/pro_log_in_with_session_key/'.$existingProAppSession->session_key);

    }

    public function accountSetup(Request $request){
        $cellNumber = $request->cookie('current_cell_number');
        $token = $request->cookie('current_confirmation_token');
        $potentialPro = PotentialPro::where('cell_number_confirmation_token', $token)->first();
        
        if(!$potentialPro){
            return redirect()->to(route('login'));
        }
        return view('account-setup');
    }

    //submitAccoutnSetup -> setup security questions  //create the actual pro and log the pro in without security questions set
    public function submitAccountSetup(Request $request){
        $request->validate([
            'first_name'=>'required',
            'last_name'=>'required',
            'email_address' => 'required|email',
            'password'=>'required'
        ]);

        $cellNumber = $request->cookie('current_cell_number');
        $token = $request->cookie('current_confirmation_token');
        $potentialPro = PotentialPro::where('cell_number_confirmation_token', $token)->get();
        if(!$potentialPro){
            abort(404, 'Not found');
        }

        $javaResponse = $this->callJava($request, '/session/proLogInAsPotentialPro', [
            'confirmationToken'=>$token,
            'cellNumber' => $cellNumber,
            'firstName' => $request->get('first_name'),
            'lastName' => $request->get('last_name'),
            'emailAddress' => $request->get('email_address'),
            'password'=>$request->get('password'),
        ]);

        if(!$javaResponse['success']){
            return redirect()->back()->withInput($request->input())->with('message', $javaResponse['message']);
        }

        $proSessionKey = $javaResponse['data'];
        return redirect()->to(config('stag.authUrl').'/pro_log_in_with_session_key/'.$proSessionKey);
    }


    public function logInWithHrInvitationToken(Request $request, $hrInvitationToken){
        //check that token is available
        if(!$hrInvitationToken){
            return redirect()->to('/');
        }
        //check that token is valid
        $proHrInvitation = ProHrInvitation::where('invitation_token', $hrInvitationToken)->first();

        if(!$proHrInvitation || !$proHrInvitation->is_active){
            return redirect()->to('/');
        }
        //send auth token for company pro and return sessionKey and store session key in cookie
        $javaResponse = $this->callJava($request, '/potentialPro/createAndSendSmsAuthToken', [
            'cellNumber'=>$proHrInvitation->pro->cell_number
        ]);

        if(!$javaResponse['success']){
            return redirect()->back()->withInput($request->input())->with('message', $javaResponse['message']);
        }

        Cookie::queue('current_cell_number', $proHrInvitation->pro->cell_number, 300);
        return redirect()->to(route('confirm-auth-token'));

    }


	public function logout(Request $request)
    {
        $api = new Backend();

        try {

            //$apiResponse = $api->get('session/logOut?sessionKey=' . $request->cookie('sessionKey'));
            $apiResponse = $api->sendRequest(
                'session/logOut',
                'GET',
                [
                    'headers'  => [
                        'sessionKey' => $request->cookie('sessionKey')
                    ]
                ]
            );

            $data = json_decode($apiResponse->getContents());

            if (!property_exists($data, 'success') || !$data->success) {
                //TODO: throw message to log
                throw new Exception('Failed to log out of backend');
            }
        } catch (Exception $e) {
            // TODO: Log message
            // TODO: Never fail on logout. Just delete cookie.
        } finally {
            Cookie::queue(Cookie::forget('sessionKey'));
        }


        return redirect()->route('login');
    }

}
