<?php

namespace App\Http\Controllers;
use App\Utilities\ApiCalls;
use Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

class UserloginController extends Controller
{
    public function index(){
        $data = [
            'page_title' => 'User Login'
        ];
        return view('user-auth.login', $data);

    }
    
    public function handleLogin(Request $request){

        $this->validate($request, ['username' => 'required', 'password' => 'required']);
        $logged_in = '';

        // dd(config('database.connections.sqlite.database'));

        $check_user_url = 'auth/auth_user.php';
        $data = ['user' => $request->username, 'pass' => $request->password, 'api_token' => env('LUPMISAPIKEY')];
        $check_user = ApiCalls::CurlPost(json_encode($data), $check_user_url);
      
        if($check_user == false){
          return redirect("user-login")->withErrors(array("System not available at the moment. Try again later!"))->withInput();
        }
        $result = json_decode($check_user, true);
       
        if($result['success'] == false){
          return redirect("user-login")->withErrors(array("Incorrect Username/Password. Check and try again!"))->withInput();
        }
        if($result['data']['is_disabled'] == true){
          ##return redirect("user-login")->withErrors(array("Your Account has been disabled. Contact your administrator!"))->withInput();
        }
        $logged_in = $result['data'];
        // dd($logged_in);
        $plainToken = Str::random(60);
       
        // $hashedToken = hash('sha256', $plainToken);
        DB::table('sso_sessions')->insert([
            'user_id' => $logged_in['user_id'],
            'token' => hash('sha256', $plainToken),
            'created_at' => now(),
        ]);
        // dd($logged_in);
        $request->session()->regenerate(true);
        $region_name = isset($logged_in['region']) ? $logged_in['region'] : "N/A";
        $request->session()->put('current_user.ua_id', $logged_in['ua_id']);
        $request->session()->put('current_user.user_id', $logged_in['user_id']);
        $request->session()->put('current_user.username', $logged_in['username']);
        $request->session()->put('current_user.title', $logged_in['title']);
        $request->session()->put('current_user.full_name', $logged_in['full_name']);
        $request->session()->put('current_user.email', $logged_in['email']);
        $request->session()->put('current_user.user_type', $logged_in['user_type']);
        $request->session()->put('current_user.phone', $logged_in['phone']);
        $request->session()->put('current_user.allowed_apps', $logged_in['allowed_apps']);
        $request->session()->put('current_user.ua_position', $logged_in['ua_position']);
        $request->session()->put('current_user.region_id', $logged_in['region_id']);
        $request->session()->put('current_user.is_password_changed', $logged_in['is_password_changed']);
        $request->session()->put('current_user.district_id', $logged_in['district_id']);
        $request->session()->put('current_user.district_name', $logged_in['vr_district_name']);
        $request->session()->put('current_user.region_name', $region_name);
        $request->session()->put('current_user.plainToken', $plainToken);

        // dd($logged_in);
        // $request->session()->put('current_user.permissions', $logged_in['permissions']);
        Cookie::queue('sso_auth_token', $plainToken, 60, '/', '.lupmis4luspa.org');
        \Log::info($logged_in['full_name']. ' Successfully logged in at : ' . date('Y-m-d H:i:s'));
        return redirect(url('/landing'));
    }
    public function handle_logout(Request $request) {
        $user_id = session('current_user.id');
        $username = session('current_user.name');

        $plainToken = request()->cookie('sso_auth_token');
        if ($plainToken) {
            Cookie::queue(Cookie::forget('sso_auth_token', '/', '.lupmis4luspa.org'));
        }

        $logout_user_url = 'auth/logout_user.php';
        $data = ['user_id' => $user_id, 'api_token' => env('LUPMISAPIKEY')];
        $result = ApiCalls::CurlPost(json_encode($data), $logout_user_url);
        // dd($result);

        $request->session()->forget('current_user');
        $request->session()->flush();
        $request->session()->regenerate(true);

        \Log::info($username . ' Successfully logged out at : ' . date('Y-m-d H:i:s'));
        Session::flash('success_message', 'You have successfully logged out!');
        return redirect("/");
    }
    
}
