<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\MapUserUnitResource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use App\Http\Traits\EncDecService;
use App\Models\PersonalAccessToken;

class AuthController extends Controller
{
    use EncDecService;    

    public function login(Request $request){
        
        $loginList = [["user_id"=>1,"username"=>"admin", "password"=>"$2y$10$.MYOvLUcWxiyxld/knodvOGMyvVZ.e8H2C9wxlRzI9KoGlyK4NP5q"],
                       ["user_id"=>2,"username"=>"user", "password"=>"$2y$10$.MYOvLUcWxiyxld/knodvOGMyvVZ.e8H2C9wxlRzI9KoGlyK4NP5q"]];

        $rawRequest = $this->customDecrypt($request->x_key);        
        if(!in_array($rawRequest->USER_LOGIN_ID, array_column($loginList, 'username'))){
            $output = [
                'ResponseCode'  => config('constants.FAILURE_RESPONSE_STATUS_CODE'),
                'Response' => 'The provided username are incorrect.'
            ];
            $jsonOutput = $this->customEncrypt($output);
            return response()->json(["x_key" =>$output]);
            
        }

        $arrcol = array_column($loginList, 'password','username');
        if (!Hash::check($rawRequest->USER_PWD, $arrcol[$rawRequest->USER_LOGIN_ID])) {
             $output = [
                'ResponseCode'  => config('constants.FAILURE_RESPONSE_STATUS_CODE'),
                'Response' => 'The provided password is incorrect.'
            ];
            $jsonOutput = $this->customEncrypt($output);
            return response()->json(["jsonOutput" =>$output]);
            
        }
        $idx = array_search($rawRequest->USER_LOGIN_ID, array_column($loginList, 'username'));
        $userdata = $loginList[$idx];
        $user = User::find($userdata['user_id']);//prd($user);
        $createToken = $user->createToken('auth-token');prd($createToken);
        $accessToken = $createToken->accessToken;
        //$this -> loginLogoutTrail($accessToken,$request,'Login'); // storing login trail
        prd(Hash::make($accessToken->token));       
        
        $jsonData = ["ResponseCode" =>  config('constants.SUCCESS_RESPONSE_STATUS_CODE'),"Response"=>"Success"];
        $jsonOutput = $this->customEncrypt($jsonData);
        return response()->json(["x_key" =>$jsonData]); 
        
    }

    public function logout() {
        Session::flush();        
        return redirect("login")->withSuccess('You have Successfully logged out');;
    }
    
}
