<?php


namespace App\Core\Service;

use Firebase\JWT\JWT;
use Firebase\JWT\ExpiredException;
use Illuminate\Support\Facades\Config;


class JwtService
{


    private $jwt ;
    private $jwtISS = 'jwtExtranet';

    public function __construct(
        JWT $jwt
    )
    {
        $this->jwt = $jwt ;
    }


    protected function jwt($params)
    {
        $payload = [
            'iss' => $params['iss'], // Issuer of the token
            'sub' => $params['sub'], // Subject of the token
            'user_id' => $params['user_id'],
            'remember_me' => $params['remember_me'],
            'iat' => $params['iat'], // Time when JWT was issued.
            'exp' => $params['exp'] // Expiration time 5 Hours
        ];

        // As you can see we are passing `JWT_SECRET` as the second parameter that will
        // be used to decode the token in the future.
        return JWT::encode($payload, Config::get('app.jwt.secret'));
    }

    public function jwtCreate($params){

        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            $dayCounter = isset( $params['day_counter'] ) ? $params['day_counter'] : 5 ;
            $rememberMe = isset( $params['remember_me'] ) && $params['remember_me']  === true ? true : false ;
            $jwtParams = [
                'iss' => $this->jwtISS, // Issuer of the token
                'sub' => 'UserLoginToken', // Subject of the token
                'user_id' => $params['user_id'],
                'iat' => time(), // Time when JWT was issued.
                'exp' =>  $rememberMe ? time() + (60 * 60 * 24 * 30) : time() + (60 * 60 * 24 * $dayCounter),
                'remember_me' => $rememberMe ? true : false ,
            ];
            $response = [
                'status ' => 1,
                'data' => [
                    'token' => $this->jwt($jwtParams),
                    'iat' => $jwtParams['iat'],
                    'remember_me' => $rememberMe ,
                    'exp' => $jwtParams['exp']
                ],

            ];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }
        return output($response);

    }

}
