<?php
session_start();
$activePage = 'configuration';
$activeSubPage = 'accessduration';
include("../elements/master.php");
?>

<!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"> <!-- Add your CSS path if needed -->
</head>
<body>
    <?php include("./access_duration_function.php"); ?>
    <div class="container">
        <div class="usertable"> <!-- Applying usertable class for consistent styling -->
            <h3 class="heading">Access Duration</h3>
            <div class="content">
                <form action="">
                <div id="sec_one">
                    <!-- Original section that will be cloned -->
                    <div class="col-10">
                        <label>Access Duration Choices</label>
                    </div>
                    <div class="col-40 sec_one main-section">
                        <input type="number" name="access_duration[]">
                        <select id="durations" class="input" name="duration_choice[]">
                            <option value="1_hour">seconds</option>
                            <option value="1_day">minutes</option>
                            <option value="1_week">hours</option>
                            <option value="1_month">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">
            <!-- Show numeric value in input -->
            <input type="number" value="<?php echo $user['duration_value']; ?>" class="input">

            <!-- Show correct option in dropdown based on duration_unit -->
            <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>
                <option value="m" <?php echo $user['duration_unit'] === 'm' ? 'selected' : ''; ?>>minutes</option>
                <option value="s" <?php echo $user['duration_unit'] === 's' ? 'selected' : ''; ?>>seconds</option>
                <option value="Y" <?php echo $user['duration_unit'] === 'Y' ? 'selected' : ''; ?>>Year</option>
                <option value="W" <?php echo $user['duration_unit'] === 'W' ? 'selected' : ''; ?>>Week</option>
                <!-- Add more options here if needed (e.g., weeks, months, etc.) -->
            </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>
    <?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>
    // Function to clone and insert the section
function cloneAndInsertSection() {
    const originalSection = document.querySelector('.sec_one.main-section'); // Get the original section by class
    const clonedSection = originalSection.cloneNode(true); // Clone the section

    // Remove the ID from the cloned section (to prevent duplicate IDs)
    clonedSection.removeAttribute('id');

    // Reset the values in the cloned section if needed
    const inputs = clonedSection.querySelectorAll("input, select");
    inputs.forEach((input) => {
        if (input.tagName.toLowerCase() === 'input') {
            input.value = ""; // Clear input fields
        } else if (input.tagName.toLowerCase() === 'select') {
            input.selectedIndex = 0; // Set dropdowns to default value
        }
    });

    // Insert the cloned section before the button area (wherever you want)
    const buttonsSection = document.querySelector('.buttons');
    if (buttonsSection) {
        buttonsSection.parentElement.insertBefore(clonedSection, buttonsSection);
    }

    // Add a custom class to the cloned section to distinguish it from the original
    clonedSection.classList.add('cloned-section');

    // Reinitialize event listeners for the newly cloned section
    initializeSectionControls();
}

// Function to remove the section
function removeSection(event) {
    const sectionToRemove = event.target.closest('.sec_one');

    // Prevent removal of the main section (original section)
    if (sectionToRemove && sectionToRemove.classList.contains('cloned-section')) {
        sectionToRemove.remove(); // Only remove cloned sections
    } else {
        console.log("Cannot remove the original section.");
    }
}

// Function to initialize event listeners for the add and remove buttons
function initializeSectionControls() {
    const addButtons = document.querySelectorAll('.plus');
    addButtons.forEach((button) => {
        button.removeEventListener('click', cloneAndInsertSection); // Remove previous listener to prevent duplicates
        button.addEventListener('click', cloneAndInsertSection);
    });

    const removeButtons = document.querySelectorAll('.minus');
    removeButtons.forEach((button) => {
        button.removeEventListener('click', removeSection); // Remove previous listener to prevent duplicates
        button.addEventListener('click', removeSection);
    });
}

// Initialize event listeners for existing elements on page load
document.addEventListener('DOMContentLoaded', () => {
    initializeSectionControls();
});

    </script>

</body>
</html>
