<?php
session_start();

$activePage = 'configuration';
$activeSubPage = 'Authentication';

include("../elements/master.php");
include("../elements/functions.php");

//-------------------API CALL------------------------------------//

$jsonFilePath = __DIR__ . '/../urls/api_endpoints.json';
$jsonData = file_get_contents($jsonFilePath);
$endpoints = json_decode($jsonData, true);
$url = $endpoints['auth_function']; // Update with the correct endpoint key

//---------------------------ENDS HERE-----------------------------------------//

if (!isset($_SESSION['token'])) {
    include('token_exp.php');
}

$token = $_SESSION['token'];
$result = make_get_request($url, ["Authorization: $token"]);
$response = json_decode($result, true);
$_SESSION["response"] = $response;

if (isset($response['items']) && is_array($response['items'])) {
    $auth_rules_list = array_map(function($rule) {
        return [
            'id' => $rule['id'] ?? '-',
            'description' => $rule['description'] ?? '-',
            'status' => $rule['status'] ?? '-',
            'actions' => isset($rule['authentication_rules'][0]['actions']) 
                ? implode(', ', array_map(fn($action) => $action['type'] . ': ' . $action['value'], $rule['authentication_rules'][0]['actions'])) 
                : '-',
            'conditions' => isset($rule['authentication_rules'][0]['conditions']) 
                ? implode(', ', array_map(fn($condition) => $condition['attribute'] . ' ' . $condition['operator'] . ' ' . $condition['value'], $rule['authentication_rules'][0]['conditions'])) 
                : '-'
        ];
    }, $response['items']);

    $_SESSION['auth_rules_list'] = $auth_rules_list;
} else {
    $auth_rules_list = "No authentication rules found or invalid response format.";
}
?>
