<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Http;


class AppSessionController extends Controller
{

    public function proRequestSmsLogInToken(){
        return view('public.pro-request-sms-login-token');
    }

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

    public function processProLogIn(Request $request){
        $loginUrl = env('BACKEND_URL', 'http://localhost:8080') . '/api/session/proLogIn';

        $response = Http::asForm()->post($loginUrl, [
            'cellNumber' => $request->get('cellNumber'),
            'token' => $request->get('token'),
        ])->json();

        if(!$response['success']){
            return back()->with("message", $response['message']);
        }

        $sessionKey = $response['data']["sessionKey"];
        $request->session()->put("authID", $response['data']["proId"]);

        $cookie = cookie()->forever('sessionKey', $sessionKey, '/');

        return redirect("/mc/dashboard")->withCookie($cookie);
    }

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

    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');
        // dd($url);

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

        // dd($response);

        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'));

    }
}
