<?php
session_start();


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["access_duration"];
// ----------------------- 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'])) {
    $user_list = array_map(function($user) {
        $access_duration = $user['access_duration'] ?? '-';
        // Separate digits and text part
        preg_match('/(\d+)(\D+)/', $access_duration, $matches);
        return [
            "duration_value" => $matches[1] ?? '', // Numeric part (e.g., '1')
            "duration_unit" => $matches[2] ?? ''  // Text part (e.g., 'h', 'd')
        ];
    }, $response['items']);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Access Duration</title>
    <link rel="stylesheet" href="../css/accessduration.css">
</head>
<body>
    <div class="container">
        <div class="usertable">
            <h3 class="heading">Access Duration</h3>
            <div class="content">
                <form action="">
                    <div id="sec_one" class="sec_one main-section">
                        <!-- Original section that will be cloned -->
                        <div class="col-10">
                            <label>Access Duration Choices</label>
                        </div>
                        <div class="col-40">
                            <input type="number" name="access_duration[]">
                            <select id="durations" class="input" name="duration_choice[]">
                                <option value="h">hours</option>
                                <option value="d">days</option>
                            </select>
                            <div class="image">
                                <img src="../images/add_hover.png" class="plus" alt="Add Field">
                                <img src="../images/minus_hover.png" class="minus" alt="Remove Field">
                            </div>
                        </div>
                    </div>

                    <?php if (!empty($user_list)): ?>
                        <?php foreach ($user_list as $user): ?>
                            <div class="col-40">
                                <input type="number" value="<?php echo $user['duration_value']; ?>" class="input">
                                <select id="durations" class="input" name="duration_choice[]">
                                    <option value="h" <?php echo $user['duration_unit'] === 'h' ? 'selected' : ''; ?>>hours</option>
                                    <option value="d" <?php echo $user['duration_unit'] === 'd' ? 'selected' : ''; ?>>days</option>
                                </select>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>

                    <div class="buttons">
                        <button type="submit" class="save_button">Save</button>
                        <button type="reset" class="reset_button">Reset</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
    // JavaScript for cloning sections remains the same
    // Function to clone and insert the section
    function cloneAndInsertSection() {
        const originalSection = document.querySelector('.sec_one.main-section'); 
        const clonedSection = originalSection.cloneNode(true); 

        clonedSection.removeAttribute('id');
        const inputs = clonedSection.querySelectorAll("input, select");
        inputs.forEach((input) => {
            if (input.tagName.toLowerCase() === 'input') {
                input.value = ""; 
            } else if (input.tagName.toLowerCase() === 'select') {
                input.selectedIndex = 0;
            }
        });

        const buttonsSection = document.querySelector('.buttons');
        if (buttonsSection) {
            buttonsSection.parentElement.insertBefore(clonedSection, buttonsSection);
        }

        clonedSection.classList.add('cloned-section');
        initializeSectionControls();
    }

    function initializeSectionControls() {
        const addButtons = document.querySelectorAll('.plus');
        addButtons.forEach((button) => {
            button.removeEventListener('click', cloneAndInsertSection); 
            button.addEventListener('click', cloneAndInsertSection);
        });

        const removeButtons = document.querySelectorAll('.minus');
        removeButtons.forEach((button) => {
            button.removeEventListener('click', removeSection); 
            button.addEventListener('click', removeSection);
        });
    }

    document.addEventListener('DOMContentLoaded', () => {
        initializeSectionControls();
    });
    </script>
</body>
</html>
