﻿<?php

namespace App\Http\Middleware;

use Closure;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;

use Exception;

class JwtVerify
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $token = $request->bearerToken();

        if (!$token) {
            return response()->json([
                'status' => 'Failed',
                'message' => 'Token not provided'
            ], 401);
        }

        try {
            // Secret Key or Public Key for core api
            $secretKey = env('JWT_SECRET');

            // Decode the token and validate it (change to 'RS256' if using RSA)
            $decoded = JWT::decode($token, new Key($secretKey, 'HS256'));

            //Grab User ID 
            $userId = $decoded->sub;

            // Step 4: Find the user by ID
            $login_user =  \App\Models\User::find($userId);

            if (!$login_user) {
                return response()->json([
                    'status' => 'Failed',
                    'message' => 'User not found'
                ], 404);
            }

            // Step 5: Log in the user
            Auth::login($login_user);
            // Attach the user data to the request for later use (if needed in controllers)
            $request->attributes->add(['user' => $decoded]);

            return $next($request);
        } catch (Exception $e) {
            return response()->json(['error' => 'Invalid token', 'message' => $e->getMessage()], 401);
        }
    }