<?php

namespace App\Http\Controllers;

use App\Http\Middleware\RedirectAuthenticatedPro;
use App\Lib\Backend;
use App\Models\Pro;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Exception;
use Illuminate\Support\Facades\Http;

class LoginController extends Controller
{
    public function __construct()
    {
        $this->middleware('pro.auth.redirect')->except('logout');
    }


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

    public function showRequestPasswordReset(Request $request)
    {
        return view('app/request_password_reset');
    }

    public function processRequestPasswordReset(Request $request)
    {
        try {

            $url =  config('stag.backendUrl') . '/pro/requestPasswordReset';

            $data = [
                'cellNumber' => $request->input('cellNumber'),
            ];

            $response = Http::asForm()
                ->post($url, $data)
                ->json();

            if(!isset($response['success']) || !$response['success']){
                $message = 'API error';
                if(isset($response['error'])) {
                    $message = $response['error'];
                    if(isset($response['path'])) $message .= ': ' . $response['path'];
                }
                else if(isset($response['message'])) $message = $response['message'];
                return redirect('/request_password_reset')
                    ->withInput()
                    ->with('message', $message);
            }

            // load pro and set security questions in the session
            $guestPro = Pro::where('cell_number', $request->input('cellNumber'))->first();
            $request->session()->put('sq1', $guestPro->security_question_1);
            $request->session()->put('sq2', $guestPro->security_question_2);

            return redirect('/self_reset_password');

        } catch (\Exception $e) {
            return redirect()->back()
                ->with('message', 'Unable to process your request at the moment. Please try again later.')
                ->withInput($request->input());
        }
    }

    public function showSelfResetPassword(Request $request)
    {
        return view('app/self_reset_password');
    }

    public function processSelfResetPassword(Request $request)
    {
        try {

            $url =  config('stag.backendUrl') . '/pro/selfResetPassword';

            $data = [
                'cellNumber' => $request->input('cellNumber'),
                'passwordResetToken' => $request->input('passwordResetToken'),
                'securityQuestionAnswer1' => $request->input('securityQuestionAnswer1'),
                'securityQuestionAnswer2' => $request->input('securityQuestionAnswer2'),
                'password' => $request->input('password'),
                'passwordConfirmation' => $request->input('passwordConfirmation'),
            ];

            $response = Http::asForm()
                ->post($url, $data)
                ->json();

            if(!isset($response['success']) || !$response['success']){
                $message = 'API error';
                if(isset($response['error'])) {
                    $message = $response['error'];
                    if(isset($response['path'])) $message .= ': ' . $response['path'];
                }
                else if(isset($response['message'])) $message = $response['message'];
                return redirect('/self_reset_password')
                    ->withInput()
                    ->with('message', $message);
            }

            $request->session()->remove('sq1');
            $request->session()->remove('sq2');

            return redirect('/login');

        } catch (\Exception $e) {
            return redirect()->back()
                ->with('message', 'Unable to process your request at the moment. Please try again later.')
                ->withInput($request->input());
        }
    }


    public function login(Request $request)
    {
        $this->validate($request, [
            'cell-number' => 'required',
            'password' => 'required'
        ]);

        $api = new Backend();

        try {
            $apiResponse = $api->post('session/proLogInWithPassword', [
                'cellNumber' => $request->post('cell-number'),
                'password' => $request->post('password')
            ]);
            $data = json_decode($apiResponse->getContents());

            if (!property_exists($data, 'success') || !$data->success) {
                return back()->with('message', 'Invalid login credentials.')
                    ->withInput($request->input());
            }

            Cookie::queue('sessionKey', $data->data->sessionKey);

            return redirect('/mc');

        } catch (\Exception $e) {
            return redirect()->back()
                ->with('message', 'Unable to process your request at the moment. Please try again later.')
                ->withInput($request->input());
        }
    }


    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()->to(config('stag.authUrl').'/logout');
    }

    public function loginWithSessionKey($sessionKey, $appAccessUID=null, Request $request){
        $url = "/session/pro_log_in_with_session_key/${sessionKey}";
        if(!!$appAccessUID) {
            $url .= "/$appAccessUID";
        }
        $api = new Backend();
        try {
            $apiResponse = $api->post($url, []);
            $data = json_decode($apiResponse->getContents());

            if (!property_exists($data, 'success') || !$data->success) {
                return redirect('/mc');
            }
            
            Cookie::queue('sessionKey', $data->data->sessionKey);

            return redirect('/mc');

        } catch (\Exception $e) {
            return redirect('/mc');
        }
    }
}
