<?php

namespace App\Http\Controllers;

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


class AppSessionController extends Controller
{

    public function confirmSmsAuthToken(Request $request)
    {
        return view('confirm_sms_auth_token');
    }
    public function setPassword(Request $request)
    {
        return view('set_password');
    }
    public function setSecurityQuestions(Request $request)
    {
        return view('set_security_questions');
    }

    public function postConfirmSmsAuthToken(Request $request) {

        try {

            $url = env('BACKEND_URL', 'http://localhost:8080') . '/api/session/confirmSmsAuthToken';

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

            $response = Http::asForm()
                ->withHeaders(['sessionKey'=>$request->cookie('sessionKey')])
                ->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('/confirm_sms_auth_token')
                    ->withInput()
                    ->with('message', $message);
            }

            return redirect('/');

        } catch (\Exception $e) {
            return redirect()->back()->with('message', $e->getMessage());
        }
    }

    public function resendSmsAuthToken(Request $request) {
        try {

            $url = env('BACKEND_URL', 'http://localhost:8080/api') . '/session/resendSmsAuthToken';

            $data = [];

            $response = Http::asForm()
                ->withHeaders(['sessionKey'=>$request->cookie('sessionKey')])
                ->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('/confirm_sms_auth_token')
                    ->withInput()
                    ->with('message', $message);
            }

            return redirect('/confirm_sms_auth_token')->with('info', 'SMS Auth Token sent');

        } catch (\Exception $e) {
            return redirect()->back()->with('message', $e->getMessage());
        }
    }

    public function postSetPassword(Request $request) {
        try {

            $url = env('BACKEND_URL', 'http://localhost:8080') . '/api/pro/selfPutPassword';

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

            $response = Http::asForm()
                ->withHeaders(['sessionKey'=>$request->cookie('sessionKey')])
                ->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('/set_password')
                    ->withInput()
                    ->with('message', $message);
            }

            return redirect('/');

        } catch (\Exception $e) {
            return redirect()->back()->with('message', $e->getMessage());
        }
    }
    public function postSetSecurityQuestions(Request $request) {

        try {

            $url = env('BACKEND_URL', 'http://localhost:8080') . '/api/pro/selfPutSecurityQuestions';

            $data = [
                'securityQuestion1' => $request->input('securityQuestion1'),
                'securityAnswer1' => $request->input('securityAnswer1'),
                'securityQuestion2' => $request->input('securityQuestion2'),
                'securityAnswer2' => $request->input('securityAnswer2'),
            ];

            $response = Http::asForm()
                ->withHeaders(['sessionKey'=>$request->cookie('sessionKey')])
                ->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('/set_password')
                    ->withInput()
                    ->with('message', $message);
            }

            return redirect('/');

        } catch (\Exception $e) {
            return redirect()->back()->with('message', $e->getMessage());
        }

    }

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

    public function processRequestPasswordReset(Request $request)
    {
        try {

            $url = env('BACKEND_URL', 'http://localhost:8080') . '/api/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', $e->getMessage());
        }
    }

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

    public function processSelfResetPassword(Request $request)
    {
        try {

            $url = env('BACKEND_URL', 'http://localhost:8080') . '/api/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', $e->getMessage());
        }
    }


    public function proLogIn(){
        return view('public.pro-log-in');
    }

    public function processProLogOut(Request $request){
        $logOutUrl = env('BACKEND_URL', 'http://localhost:8080/api') . '/session/logOut';
        $response = Http::asForm()->withHeaders(['sessionKey'=>$request->cookie('sessionKey')])->get($logOutUrl)->json();
        if(!$response['success']){
            return back()->with("message", $response['message']);
        }
        Cookie::queue(Cookie::forget('sessionKey'));
        return redirect(route('login'));
    }

    public function login(Request $request)
    {
        $api = new Backend();
        try {
            $apiResponse = $api->post('session/proLogInWithPassword', [
                'cellNumber' => $request->post('cellNumber'),
                '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('/confirm_sms_auth_token');

        } catch (\Exception $e) {
            return redirect()->back()->with('message', $e->getMessage());
        }
    }

    public function postToAPI(Request $request) {

        session()->remove('message');

        // call java api

        $data = [];
        $fields = $request->all();
        foreach ($fields as $key => $value) {
            if($key[0] !== '_') {
                $data[$key] = $value;
            }
        }

        if(!isset($data['uid']) && isset($fields['_uid'])) {
            $data['uid'] = $fields['_uid'];
        }

        $url = env('BACKEND_URL', 'http://localhost:8080') . $request->input('_api');

        $file = $request->file('file');
        if($file) {
            $localFile = $file->store("storage/uploads");
            $stream = fopen(storage_path("app/" . $localFile), 'r');
            $response = Http::asMultipart()
                ->withHeaders(['sessionKey'=>$request->cookie('sessionKey')])
                ->attach('file', $stream, $file->getClientOriginalName())
                ->post($url, $data)
                ->json();
            fclose($stream);
        }
        else {
            $response = Http::asForm()
                ->withHeaders(['sessionKey'=>$request->cookie('sessionKey')])
                ->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->input('_return'))
                ->withInput()
                ->with('message', $message);
        }

        return redirect($request->input('_success'));

    }

    public function postToAPIAjax(Request $request) {

        session()->remove('message');

        // call java api

        $data = [];
        $fields = $request->all();
        foreach ($fields as $key => $value) {
            if($key[0] !== '_') {
                $data[$key] = $value;
            }
        }

        if(!isset($data['uid']) && isset($fields['_uid'])) {
            $data['uid'] = $fields['_uid'];
        }

        $url = env('BACKEND_URL', 'http://localhost:8080') . $request->input('_api');
        // dd($url);

        $response = Http::asForm()
            ->withHeaders(['sessionKey'=>$request->cookie('sessionKey')])
            ->post($url, $data)
            ->json();

        // dd($response);

        return response()->json($response);
    }
}
