<?php
/**
 * This file returns an array of available public keys
 */
define('NO_DEBUG_DISPLAY', true);
require_once("../config/database.php");
require_once("lti.php");

@header('Content-Type: application/json; charset=utf-8');

$lti = new LTI();

$id = $_GET['id'];

$private_key_db = "";
$kid_db = "";
$lti_company_data = $lti->get_company_detail($id);
if ($result = $lti_company_data->fetch(PDO::FETCH_ASSOC)) {
    $private_key_db = $result['private_key'];
    $kid_db = $result['kid'];
}

function get_jwks($private_key_db,$kid_db)
{
    $jwks = array('keys' => array());

    $res = openssl_pkey_get_private($private_key_db);
    $details = openssl_pkey_get_details($res);
    $kid = $kid_db;
    $jwk = array();
    $jwk['kty'] = 'RSA';
    $jwk['alg'] = 'RS256';
    $jwk['kid'] = $kid;
    $jwk['e'] = rtrim(strtr(base64_encode($details['rsa']['e']), '+/', '-_'), '=');
    $jwk['n'] = rtrim(strtr(base64_encode($details['rsa']['n']), '+/', '-_'), '=');
    $jwk['use'] = 'sig';

    $jwks['keys'][] = $jwk;
    return $jwks;
}

echo json_encode(get_jwks($private_key_db,$kid_db), JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);