<?php
session_start();

include("../elements/new_functions.php");

// ----------------------------API CALL--------------------//
$jsonFilePath = __DIR__ . '/../urls/api_endpoints.json';
$jsonData = file_get_contents($jsonFilePath);
$endpoints = json_decode($jsonData, true);
$url = $endpoints["switch_list"]; // Assuming you have a separate endpoint for switches
// ----------------------- ENDS HERE-------------------------// 

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

$token = $_SESSION['token'];
$result = make_get_request($url, ["Authorization: $token"]);
$response_data = $result['response']; // Get the actual response
$http_code = $result['http_code']; // Get the HTTP status code

// Decode the response
$response = json_decode($response_data, true);
$_SESSION["response"] = $response;

// Debug output
echo '<pre>';
echo "HTTP Status Code: $http_code\n";
print_r($response); // Display the structured response
echo '</pre>';

$switch_groups = []; // Initialize an empty array to hold switch groups

// Check if 'items' exist in the response
if (isset($response['items']) && is_array($response['items'])) {
    foreach ($response['items'] as $item) {
        $groupName = $item['group']; // Get the group name
        $typeValue = $item['type']; // Get the type value or description

        // Store group and type in the switch_groups array
        if (!isset($switch_groups[$groupName])) {
            $switch_groups[$groupName] = []; // Initialize an array for this group
        }
        $switch_groups[$groupName][] = $typeValue; // Append the type (or description) to the group
    }
}

// Debug output (optional)
echo '<pre>';
print_r($switch_groups); // To see the structured data
echo '</pre>';
?>

<!-- HTML to display switch groups and their types -->
<div id="switchGroupsContainer">
    <?php foreach ($switch_groups as $group => $types): ?>
        <div>
            <strong><?php echo htmlspecialchars($group); ?></strong>: 
            <?php echo htmlspecialchars(implode(', ', $types)); // Display all types in the group ?>
        </div>
    <?php endforeach; ?>
</div>
