<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Session;
use App\Utilities\ApiCalls;

class SsoController extends Controller
{


public function validateToken(Request $request)
{
    $plainToken = $request->input('token');
    // dd(plainToken);

    \Log::info("New Request : $plainToken");

    if (!$plainToken) {
        return response()->json(['valid' => false], 400);
    }
    $hashedToken = hash('sha256', $plainToken);
    \Log::info("hashed Token : $hashedToken");
    


    $session = DB::table('sso_sessions')->where('token', $hashedToken)->first();
    \Log::info("session : " . json_encode($session));
    if ($session){
        $check_user_url = 'user_mgt/get_user_by_user_id.php';
        $data = ['user_id' => $session->user_id, 'api_token' => env('LUPMISAPIKEY')];
        
        $check_user = ApiCalls::CurlPost(json_encode($data), $check_user_url);
        if($check_user == false){
            \Log::info("User not found : $hashedToken");
            return response()->json(['valid' => false], 401);
        }
        $result = json_decode($check_user, true);
        if($result['success'] == false){
            return response()->json(['valid' => false], 401);
        }
        // if($result['data']['is_disabled'] == true){
        //     return response()->json(['valid 099' => false], 401);
        // }
        $logged_in = $result['data'];
        return response()->json([
            'valid' => true,
            'logged_in_user' => $logged_in
        ], 200);
    }
    return response()->json(['valid 0123' => false], 401);
}
}
