<?php $formtypes_con = mysqli_query($con, "SELECT formnumber, formtype FROM dd_formtypes WHERE regs LIKE '%Lifting Operations and Lifting Equipment Regulations 1998%'");
$formtypes_master = mysqli_query($master, "SELECT formnumber, formtype FROM dd_formtypes WHERE regs LIKE '%Lifting Operations and Lifting Equipment Regulations 1998%'");
?>

<div class="container mt-5">
    <h3>Create New Nature Entry</h3>
    <form id="natureForm">
        <div class="form-group">
            <label for="description">Text for selection <small class="text-lighter">(e.g In-Service Thorough Examination)</small></label>
            <input type="text" class="form-control" id="description" name="description" required>
        </div>

        <div class="form-group">
            <label>Select Formtypes to associate with the entry</label><br>
            <?php while ($row = mysqli_fetch_assoc($formtypes_con)) : ?>
            <div class="form-check form-check-inline border rounded bg-info text-light mb-3">
                <input class="form-check-input" type="checkbox" id="formtype<?= $row['formnumber'] ?>" name="formtypes[]" value="<?= $row['formnumber'] ?>">
                <label class="form-check-label me-2" for="formtype<?= $row['formnumber'] ?>"><?= $row['formtype'] ?></label>
            </div>
            <?php endwhile; ?>

            <?php while ($row = mysqli_fetch_assoc($formtypes_master)) : ?>
            <div class="form-check form-check-inline border rounded bg-info text-light mb-3">
                <input class="form-check-input" type="checkbox" id="formtype<?= $row['formnumber'] ?>" name="formtypes[]" value="<?= $row['formnumber'] ?>">
                <label class="form-check-label me-2" for="formtype<?= $row['formnumber'] ?>"><?= $row['formtype'] ?></label>
            </div>
            <?php endwhile; ?>
        </div>

        <div class="form-group">
            <label>Status</label>
            <select class="form-control" id="status" name="status">
                <option value="1">Active</option>
                <option value="0">Inactive</option>
            </select>
        </div>
        <input type="hidden" name="tenant" value="<?=TENANT_URL?>">
        <button type="submit" class="btn btn-primary">Create Entry</button>
    </form>

    <!-- List of Entries -->
    <h2 class="mt-5">Saved Nature Entries</h2>
    <table class="table" id="natureEntries">
        <thead>
            <tr>
                <th>Description</th>
                <th>Formtypes</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <!-- Entries will be loaded here dynamically -->
        </tbody>
    </table>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    loadNatureEntries();

    // Handle form submission
    document.getElementById('natureForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        formData.append('action', 'create');

        fetch(ROOT_URL + '/includes/formgen/form_nature_actions.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                alert(data)
                if (data.status === 'success') {
                    showResponse('success', 'Entry created successfully!');
                    loadNatureEntries(); // Refresh the list of entries
                } else {
                    showResponse('danger', 'Error creating entry.');
                }
            });
    });
});

// Load the list of saved entries
function loadNatureEntries() {
    fetch(ROOT_URL + '/includes/formgen/form_nature_actions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'action=fetch&tenant=' + TENANT_URL
        })
        .then(response => response.json())
        .then(data => {
            const entriesTable = document.getElementById('natureEntries').querySelector('tbody');
            entriesTable.innerHTML = ''; // Clear existing rows

            data.forEach(entry => {
                const row = `<tr>
                                    <td>${entry.description}</td>
                                    <td>${entry.formtypes}</td>
                                    <td>${entry.status == 1 ? 'Active' : 'Inactive'}</td>
                                    <td>
                                        <button onclick="editEntry(${entry.id})" class="btn btn-primary btn-sm">Edit</button>
                                        <button onclick="deleteEntry(${entry.id})" class="btn btn-danger btn-sm">Delete</button>
                                    </td>
                                </tr>`;
                entriesTable.insertAdjacentHTML('beforeend', row);
            });
        });
}

// Delete an entry
function deleteEntry(id) {
    if (confirm('Are you sure you want to delete this entry?')) {
        fetch(ROOT_URL + '/includes/formgen/form_nature_actions.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: `action=delete&id=${id}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    showResponse('success', 'Entry deleted successfully!');
                    loadNatureEntries(); // Refresh the list of entries
                } else {
                    showResponse('danger', 'Error deleting entry.');
                }
            });
    }
}

// Edit an entry (modal functionality can be added here)
function editEntry(id) {
    // Code for handling editing (similar to delete but populates modal for editing)
}

// Show response function
function showResponse(type, message) {
    alert(`${type.toUpperCase()}: ${message}`);
}

document.getElementById('navBox').innerHTML = '<li class="breadcrumb-item">Tools <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb-item active">Nature Droplist Manage</li>';
</script>