<?php
$systemTypes = [];
$sectionsBySystem = [];
$groupsBySection = [];
$questionsBySection = [];
$questionsByGroup = [];

$res = mysqli_query(
    $GLOBALS['con'],
    "SELECT * FROM `pmr_system_types` ORDER BY `sort_order` ASC, `id` ASC"
) or die(mysqli_error($GLOBALS['con']));
while ($row = mysqli_fetch_assoc($res)) {
    $systemTypes[] = $row;
    $sectionsBySystem[(int)$row['id']] = [];
}

$res = mysqli_query(
    $GLOBALS['con'],
    "SELECT * FROM `pmr_sections` ORDER BY `system_type_id` ASC, `sort_order` ASC, `id` ASC"
) or die(mysqli_error($GLOBALS['con']));
while ($row = mysqli_fetch_assoc($res)) {
    $systemTypeId = (int)$row['system_type_id'];
    $sectionId = (int)$row['id'];
    $sectionsBySystem[$systemTypeId][] = $row;
    $groupsBySection[$sectionId] = [];
    $questionsBySection[$sectionId] = [];
}

$res = mysqli_query(
    $GLOBALS['con'],
    "SELECT * FROM `pmr_groups` ORDER BY `section_id` ASC, `sort_order` ASC, `id` ASC"
) or die(mysqli_error($GLOBALS['con']));
while ($row = mysqli_fetch_assoc($res)) {
    $sectionId = (int)$row['section_id'];
    $groupId = (int)$row['id'];
    $groupsBySection[$sectionId][] = $row;
    $questionsByGroup[$groupId] = [];
}

$res = mysqli_query(
    $GLOBALS['con'],
    "SELECT * FROM `pmr_questions` ORDER BY `section_id` ASC, COALESCE(`group_id`, 0) ASC, `sort_order` ASC, `id` ASC"
) or die(mysqli_error($GLOBALS['con']));
while ($row = mysqli_fetch_assoc($res)) {
    $row['input_types'] = json_decode((string)$row['input_types_json'], true);
    if (!is_array($row['input_types'])) {
        $row['input_types'] = [];
    }

    $groupId = isset($row['group_id']) ? (int)$row['group_id'] : 0;
    if ($groupId > 0) {
        $questionsByGroup[$groupId][] = $row;
    } else {
        $questionsBySection[(int)$row['section_id']][] = $row;
    }
}

$inputOptions = [
    'yes' => 'Yes',
    'no' => 'No',
    'na' => 'N/A',
    'notes' => 'Notes',
    'textarea' => 'Textarea',
    'text' => 'Text',
    'numeric' => 'Numeric'
];

function pmrBuilderInputChecks(array $inputOptions, string $scope): void
{
    foreach ($inputOptions as $value => $label) { ?>
        <label class="form-check form-check-inline mb-1">
            <input class="form-check-input pmr-builder-input-type" type="checkbox" value="<?= htmlspecialchars($value, ENT_QUOTES) ?>">
            <span class="form-check-label"><?= htmlspecialchars($label, ENT_QUOTES) ?></span>
        </label>
    <?php }
}
?>

<style>
.pmr-builder-system-btn {
    text-align: left;
    white-space: normal;
}
.pmr-builder-system-panel {
    display: none;
}
.pmr-builder-system-panel.active {
    display: block;
}
.pmr-builder-section {
    border: 1px solid #dee2e6;
    border-radius: 6px;
    margin-bottom: 1rem;
    overflow: hidden;
}
.pmr-builder-section > summary {
    cursor: pointer;
    list-style: none;
}
.pmr-builder-section > summary::-webkit-details-marker {
    display: none;
}
.pmr-builder-section-header {
    background: #f8f9fa;
    padding: .75rem;
}
.pmr-builder-section-toggle {
    color: #6c757d;
    display: inline-block;
    font-size: 1.05rem;
    margin-right: .35rem;
    transition: transform .15s ease-in-out;
}
.pmr-builder-section[open] .pmr-builder-section-toggle {
    transform: rotate(90deg);
}
.pmr-builder-group {
    border-left: 4px solid #17a2b8;
    background: #fff;
}
.pmr-builder-question {
    border-bottom: 1px solid #eef0f2;
    padding: .5rem 0;
}
.pmr-builder-question:last-child {
    border-bottom: 0;
}
.pmr-builder-add {
    background: #fbfbfc;
    border: 1px dashed #ced4da;
    border-radius: 6px;
    padding: .75rem;
}
.pmr-builder-modal-backdrop {
    align-items: center;
    background: rgba(0, 0, 0, .35);
    display: none;
    inset: 0;
    justify-content: center;
    position: fixed;
    z-index: 1050;
}
.pmr-builder-modal-backdrop.active {
    display: flex;
}
.pmr-builder-modal {
    background: #fff;
    border-radius: 6px;
    box-shadow: 0 12px 30px rgba(0, 0, 0, .2);
    max-width: 640px;
    width: calc(100% - 2rem);
}
</style>

<div class="row">
    <div class="col-lg-3 mb-4">
        <div class="card">
            <div class="card-header">
                <strong>System Types</strong>
            </div>
            <div class="card-body">
                <div class="pmr-builder-add mb-3">
                    <label class="form-label">Add new system type</label>
                    <div class="input-group">
                        <input type="text" class="form-control" id="pmrBuilderSystemTitle" placeholder="LX, AV, SND">
                        <button type="button" class="btn btn-info" id="pmrBuilderAddSystem">Add</button>
                    </div>
                </div>

                <?php if (empty($systemTypes)) { ?>
                    <div class="alert alert-warning mb-0">Add a system type to start building PMR checklists.</div>
                <?php } else { ?>
                    <div class="list-group" id="pmrBuilderSystemList">
                        <?php foreach ($systemTypes as $index => $systemType) { ?>
                            <button type="button"
                                    class="list-group-item list-group-item-action pmr-builder-system-btn <?= $index === 0 ? 'active' : '' ?>"
                                    data-system-id="<?= (int)$systemType['id'] ?>">
                                <strong><?= htmlspecialchars($systemType['title'], ENT_QUOTES) ?></strong>
                                <?php if ((int)$systemType['status'] !== 1) { ?>
                                    <span class="badge bg-secondary ms-1">Inactive</span>
                                <?php } ?>
                                <span class="badge bg-light text-dark float-end"><?= count($sectionsBySystem[(int)$systemType['id']] ?? []) ?></span>
                            </button>
                        <?php } ?>
                    </div>
                <?php } ?>
            </div>
        </div>
    </div>

    <div class="col-lg-9 mb-4">
        <?php foreach ($systemTypes as $index => $systemType) { ?>
            <?php $systemTypeId = (int)$systemType['id']; ?>
            <div class="pmr-builder-system-panel <?= $index === 0 ? 'active' : '' ?>" data-system-id="<?= $systemTypeId ?>">
                <div class="card mb-3">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <div>
                            <strong><?= htmlspecialchars($systemType['title'], ENT_QUOTES) ?></strong>
                            <span class="text-muted">checklist builder</span>
                        </div>
                        <div>
                            <button type="button" class="btn btn-secondary btn-sm pmr-builder-edit-system"
                                    data-id="<?= $systemTypeId ?>"
                                    data-title="<?= htmlspecialchars($systemType['title'], ENT_QUOTES) ?>"
                                    data-status="<?= (int)$systemType['status'] ?>">Edit</button>
                            <button type="button" class="btn btn-secondary btn-sm pmr-builder-move" data-function="moveSystemType" data-id="<?= $systemTypeId ?>" data-direction="up">&#8593;</button>
                            <button type="button" class="btn btn-secondary btn-sm pmr-builder-move" data-function="moveSystemType" data-id="<?= $systemTypeId ?>" data-direction="down">&#8595;</button>
                            <button type="button" class="btn btn-danger btn-sm pmr-builder-delete" data-function="deleteSystemType" data-id="<?= $systemTypeId ?>" data-message="Delete this system type and all sections, groups, and questions inside it?">Delete</button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="pmr-builder-add">
                            <label class="form-label">Add new section</label>
                            <div class="input-group">
                                <input type="text" class="form-control pmr-builder-section-title" placeholder="OVERALL SYSTEM, LANTERNS">
                                <button type="button" class="btn btn-info pmr-builder-add-section" data-system-type-id="<?= $systemTypeId ?>">Add Section</button>
                            </div>
                        </div>
                    </div>
                </div>

                <?php foreach (($sectionsBySystem[$systemTypeId] ?? []) as $section) { ?>
                    <?php
                    $sectionId = (int)$section['id'];
                    $sectionQuestionCount = count($questionsBySection[$sectionId] ?? []);
                    $sectionGroupCount = count($groupsBySection[$sectionId] ?? []);
                    $groupQuestionCount = 0;
                    foreach (($groupsBySection[$sectionId] ?? []) as $countGroup) {
                        $groupQuestionCount += count($questionsByGroup[(int)$countGroup['id']] ?? []);
                    }
                    ?>
                    <details class="pmr-builder-section">
                        <summary class="pmr-builder-section-header d-flex justify-content-between align-items-center">
                            <div>
                                <span class="pmr-builder-section-toggle">&#9656;</span>
                                <strong><?= htmlspecialchars($section['title'], ENT_QUOTES) ?></strong>
                                <span class="badge bg-light text-dark ms-2"><?= $sectionGroupCount ?> groups</span>
                                <span class="badge bg-light text-dark"><?= $sectionQuestionCount + $groupQuestionCount ?> questions</span>
                                <?php if ((int)$section['status'] !== 1) { ?>
                                    <span class="badge bg-secondary ms-1">Inactive</span>
                                <?php } ?>
                            </div>
                            <div>
                                <button type="button" class="btn btn-secondary btn-sm pmr-builder-edit-section"
                                        data-id="<?= $sectionId ?>"
                                        data-system-type-id="<?= $systemTypeId ?>"
                                        data-title="<?= htmlspecialchars($section['title'], ENT_QUOTES) ?>"
                                        data-status="<?= (int)$section['status'] ?>">Edit</button>
                                <button type="button" class="btn btn-secondary btn-sm pmr-builder-move" data-function="moveSection" data-id="<?= $sectionId ?>" data-direction="up">&#8593;</button>
                                <button type="button" class="btn btn-secondary btn-sm pmr-builder-move" data-function="moveSection" data-id="<?= $sectionId ?>" data-direction="down">&#8595;</button>
                                <button type="button" class="btn btn-danger btn-sm pmr-builder-delete" data-function="deleteSection" data-id="<?= $sectionId ?>" data-message="Delete this section and everything inside it?">Delete</button>
                            </div>
                        </summary>

                        <div class="p-3">
                            <div class="row">
                                <div class="col-xl-6 mb-3">
                                    <div class="pmr-builder-add">
                                        <label class="form-label">Add section question</label>
                                        <textarea class="form-control pmr-builder-question-text mb-2" rows="2" placeholder="Question shown directly under this section"></textarea>
                                        <div class="mb-2"><?php pmrBuilderInputChecks($inputOptions, 'section-' . $sectionId); ?></div>
                                        <button type="button" class="btn btn-info btn-sm pmr-builder-add-question" data-section-id="<?= $sectionId ?>" data-group-id="">Add Question</button>
                                    </div>
                                </div>
                                <div class="col-xl-6 mb-3">
                                    <div class="pmr-builder-add">
                                        <label class="form-label">Add group</label>
                                        <div class="input-group">
                                            <input type="text" class="form-control pmr-builder-group-title" placeholder="GENERIC LED, DISTRIBUTION BOARD">
                                            <button type="button" class="btn btn-info pmr-builder-add-group" data-section-id="<?= $sectionId ?>">Add Group</button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <?php if (!empty($questionsBySection[$sectionId])) { ?>
                                <div class="mb-3">
                                    <strong class="d-block mb-2">Section questions</strong>
                                    <?php foreach ($questionsBySection[$sectionId] as $question) { ?>
                                        <div class="pmr-builder-question d-flex justify-content-between align-items-start">
                                            <div>
                                                <?= htmlspecialchars($question['question_text'], ENT_QUOTES) ?>
                                                <div class="small text-muted"><?= htmlspecialchars(implode(', ', $question['input_types']), ENT_QUOTES) ?></div>
                                            </div>
                                            <div class="ms-2 text-nowrap">
                                                <button type="button" class="btn btn-secondary btn-sm pmr-builder-edit-question"
                                                        data-id="<?= (int)$question['id'] ?>"
                                                        data-section-id="<?= $sectionId ?>"
                                                        data-group-id=""
                                                        data-text="<?= htmlspecialchars($question['question_text'], ENT_QUOTES) ?>"
                                                        data-inputs="<?= htmlspecialchars(json_encode($question['input_types']), ENT_QUOTES) ?>"
                                                        data-status="<?= (int)$question['status'] ?>">Edit</button>
                                                <button type="button" class="btn btn-danger btn-sm pmr-builder-delete" data-function="deleteQuestion" data-id="<?= (int)$question['id'] ?>" data-message="Delete this question?">Delete</button>
                                            </div>
                                        </div>
                                    <?php } ?>
                                </div>
                            <?php } ?>

                            <?php foreach (($groupsBySection[$sectionId] ?? []) as $group) { ?>
                                <?php $groupId = (int)$group['id']; ?>
                                <details class="pmr-builder-group mb-3 p-3" open>
                                    <summary class="d-flex justify-content-between align-items-center" style="cursor:pointer;">
                                        <span>
                                            <strong><?= htmlspecialchars($group['title'], ENT_QUOTES) ?></strong>
                                            <span class="badge bg-light text-dark"><?= count($questionsByGroup[$groupId] ?? []) ?></span>
                                        </span>
                                        <span>
                                            <button type="button" class="btn btn-secondary btn-sm pmr-builder-edit-group"
                                                    data-id="<?= $groupId ?>"
                                                    data-section-id="<?= $sectionId ?>"
                                                    data-title="<?= htmlspecialchars($group['title'], ENT_QUOTES) ?>"
                                                    data-status="<?= (int)$group['status'] ?>">Edit</button>
                                            <button type="button" class="btn btn-secondary btn-sm pmr-builder-move" data-function="moveGroup" data-id="<?= $groupId ?>" data-direction="up">&#8593;</button>
                                            <button type="button" class="btn btn-secondary btn-sm pmr-builder-move" data-function="moveGroup" data-id="<?= $groupId ?>" data-direction="down">&#8595;</button>
                                            <button type="button" class="btn btn-danger btn-sm pmr-builder-delete" data-function="deleteGroup" data-id="<?= $groupId ?>" data-message="Delete this group and its questions?">Delete</button>
                                        </span>
                                    </summary>

                                    <div class="pt-3">
                                        <?php foreach (($questionsByGroup[$groupId] ?? []) as $question) { ?>
                                            <div class="pmr-builder-question d-flex justify-content-between align-items-start">
                                                <div>
                                                    <?= htmlspecialchars($question['question_text'], ENT_QUOTES) ?>
                                                    <div class="small text-muted"><?= htmlspecialchars(implode(', ', $question['input_types']), ENT_QUOTES) ?></div>
                                                </div>
                                                <div class="ms-2 text-nowrap">
                                                    <button type="button" class="btn btn-secondary btn-sm pmr-builder-edit-question"
                                                            data-id="<?= (int)$question['id'] ?>"
                                                            data-section-id="<?= $sectionId ?>"
                                                            data-group-id="<?= $groupId ?>"
                                                            data-text="<?= htmlspecialchars($question['question_text'], ENT_QUOTES) ?>"
                                                            data-inputs="<?= htmlspecialchars(json_encode($question['input_types']), ENT_QUOTES) ?>"
                                                            data-status="<?= (int)$question['status'] ?>">Edit</button>
                                                    <button type="button" class="btn btn-danger btn-sm pmr-builder-delete" data-function="deleteQuestion" data-id="<?= (int)$question['id'] ?>" data-message="Delete this question?">Delete</button>
                                                </div>
                                            </div>
                                        <?php } ?>

                                        <div class="pmr-builder-add mt-3">
                                            <label class="form-label">Add question to <?= htmlspecialchars($group['title'], ENT_QUOTES) ?></label>
                                            <textarea class="form-control pmr-builder-question-text mb-2" rows="2"></textarea>
                                            <div class="mb-2"><?php pmrBuilderInputChecks($inputOptions, 'group-' . $groupId); ?></div>
                                            <button type="button" class="btn btn-info btn-sm pmr-builder-add-question" data-section-id="<?= $sectionId ?>" data-group-id="<?= $groupId ?>">Add Question</button>
                                        </div>
                                    </div>
                                </details>
                            <?php } ?>
                        </div>
                    </details>
                <?php } ?>
            </div>
        <?php } ?>
    </div>
</div>

<div class="pmr-builder-modal-backdrop" id="pmrBuilderEditModal">
    <div class="pmr-builder-modal">
        <div class="p-3 border-bottom d-flex justify-content-between align-items-center">
            <strong id="pmrBuilderEditTitle">Edit</strong>
            <button type="button" class="btn btn-secondary btn-sm" id="pmrBuilderEditClose">Close</button>
        </div>
        <div class="p-3">
            <input type="hidden" id="pmrBuilderEditFunction">
            <input type="hidden" id="pmrBuilderEditId">
            <input type="hidden" id="pmrBuilderEditSystemTypeId">
            <input type="hidden" id="pmrBuilderEditSectionId">
            <input type="hidden" id="pmrBuilderEditGroupId">

            <div class="mb-3" id="pmrBuilderEditTitleField">
                <label class="form-label">Title</label>
                <input type="text" class="form-control" id="pmrBuilderEditValue">
            </div>

            <div class="mb-3 d-none" id="pmrBuilderEditQuestionField">
                <label class="form-label">Question Text</label>
                <textarea class="form-control" id="pmrBuilderEditQuestionText" rows="4"></textarea>
            </div>

            <div class="mb-3 d-none" id="pmrBuilderEditInputsField">
                <label class="form-label d-block">Input Types</label>
                <?php pmrBuilderInputChecks($inputOptions, 'edit'); ?>
            </div>

            <div class="form-check mb-3">
                <input class="form-check-input" type="checkbox" id="pmrBuilderEditStatus">
                <label class="form-check-label" for="pmrBuilderEditStatus">Active</label>
            </div>

            <div class="d-flex gap-2">
                <button type="button" class="btn btn-info" id="pmrBuilderEditSave">Save</button>
                <button type="button" class="btn btn-secondary" id="pmrBuilderEditCancel">Cancel</button>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    const endpoint = ROOT_URL + '/includes/pmr/pmr_functions.php';
    const editModal = document.getElementById('pmrBuilderEditModal');

    function postBuilder(data) {
        fetch(endpoint, {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: new URLSearchParams(data)
        })
        .then(r => r.json())
        .then(j => {
            showResponse(j.status === 'success' ? 'success' : (j.status === 'warning' ? 'warning' : 'danger'), j.message);
            if (j.status === 'success') {
                window.location.href = 'index.php?t=includes/master&p=pmr_config.php&view=builder';
            }
        })
        .catch(() => showResponse('danger', 'There was a problem processing the request'));
    }

    function inputTypesFrom(container) {
        return [...container.querySelectorAll('.pmr-builder-input-type:checked')].map(cb => cb.value);
    }

    function escapeHtml(value) {
        const div = document.createElement('div');
        div.textContent = value || '';
        return div.innerHTML;
    }

    function confirmDelete(message, callback) {
        const body = '<div class="p-2">' +
            '<p class="mb-2">' + escapeHtml(message || 'Delete this item?') + '</p>' +
            '<p class="text-danger mb-0"><strong>This action cannot be undone.</strong></p>' +
            '</div>';

        loadModalContent(body, 'pmrDeleteBox', 'modal-md', 1080, 'true', 'Confirm Delete', 'cancelConfirm', function () {
            if (typeof killModal === 'function') killModal('pmrDeleteBox');
            callback();
        });
    }

    document.querySelectorAll('.pmr-builder-section summary button, .pmr-builder-group summary button').forEach(function (btn) {
        btn.addEventListener('click', function (e) {
            e.stopPropagation();
        });
    });

    function closeEditModal() {
        editModal.classList.remove('active');
    }

    function openEditModal(type, data) {
        document.getElementById('pmrBuilderEditFunction').value = data.functionName;
        document.getElementById('pmrBuilderEditId').value = data.id || '0';
        document.getElementById('pmrBuilderEditSystemTypeId').value = data.systemTypeId || '';
        document.getElementById('pmrBuilderEditSectionId').value = data.sectionId || '';
        document.getElementById('pmrBuilderEditGroupId').value = data.groupId || '';
        document.getElementById('pmrBuilderEditStatus').checked = data.status === '1';

        const titleField = document.getElementById('pmrBuilderEditTitleField');
        const questionField = document.getElementById('pmrBuilderEditQuestionField');
        const inputsField = document.getElementById('pmrBuilderEditInputsField');
        const editInputs = inputsField.querySelectorAll('.pmr-builder-input-type');

        titleField.classList.toggle('d-none', type === 'question');
        questionField.classList.toggle('d-none', type !== 'question');
        inputsField.classList.toggle('d-none', type !== 'question');

        document.getElementById('pmrBuilderEditTitle').textContent = data.heading || 'Edit';
        document.getElementById('pmrBuilderEditValue').value = data.value || '';
        document.getElementById('pmrBuilderEditQuestionText').value = data.value || '';

        let selectedInputs = [];
        try { selectedInputs = JSON.parse(data.inputs || '[]'); } catch (e) { selectedInputs = []; }
        editInputs.forEach(cb => cb.checked = selectedInputs.includes(cb.value));

        editModal.classList.add('active');
    }

    document.querySelectorAll('.pmr-builder-system-btn').forEach(function (btn) {
        btn.addEventListener('click', function () {
            document.querySelectorAll('.pmr-builder-system-btn').forEach(b => b.classList.remove('active'));
            document.querySelectorAll('.pmr-builder-system-panel').forEach(p => p.classList.remove('active'));
            btn.classList.add('active');
            const panel = document.querySelector('.pmr-builder-system-panel[data-system-id="' + btn.dataset.systemId + '"]');
            if (panel) panel.classList.add('active');
        });
    });

    document.getElementById('pmrBuilderAddSystem')?.addEventListener('click', function () {
        postBuilder({
            FUNCTION: 'saveSystemType',
            id: '0',
            title: document.getElementById('pmrBuilderSystemTitle').value,
            status: '1',
            tenant: TENANT_URL
        });
    });

    document.querySelectorAll('.pmr-builder-add-section').forEach(function (btn) {
        btn.addEventListener('click', function () {
            const container = btn.closest('.pmr-builder-add');
            postBuilder({
                FUNCTION: 'saveSection',
                id: '0',
                system_type_id: btn.dataset.systemTypeId,
                title: container.querySelector('.pmr-builder-section-title').value,
                status: '1',
                tenant: TENANT_URL
            });
        });
    });

    document.querySelectorAll('.pmr-builder-add-group').forEach(function (btn) {
        btn.addEventListener('click', function () {
            const container = btn.closest('.pmr-builder-add');
            postBuilder({
                FUNCTION: 'saveGroup',
                id: '0',
                section_id: btn.dataset.sectionId,
                title: container.querySelector('.pmr-builder-group-title').value,
                status: '1',
                tenant: TENANT_URL
            });
        });
    });

    document.querySelectorAll('.pmr-builder-add-question').forEach(function (btn) {
        btn.addEventListener('click', function () {
            const container = btn.closest('.pmr-builder-add');
            postBuilder({
                FUNCTION: 'saveQuestion',
                id: '0',
                section_id: btn.dataset.sectionId,
                group_id: btn.dataset.groupId || '',
                question_text: container.querySelector('.pmr-builder-question-text').value,
                input_types_json: JSON.stringify(inputTypesFrom(container)),
                status: '1',
                tenant: TENANT_URL
            });
        });
    });

    document.querySelectorAll('.pmr-builder-edit-system').forEach(function (btn) {
        btn.addEventListener('click', function () {
            openEditModal('title', {
                functionName: 'saveSystemType',
                heading: 'Edit system type',
                id: btn.dataset.id,
                value: btn.dataset.title || '',
                status: btn.dataset.status
            });
        });
    });

    document.querySelectorAll('.pmr-builder-edit-section').forEach(function (btn) {
        btn.addEventListener('click', function () {
            openEditModal('title', {
                functionName: 'saveSection',
                heading: 'Edit section',
                id: btn.dataset.id,
                systemTypeId: btn.dataset.systemTypeId,
                value: btn.dataset.title || '',
                status: btn.dataset.status
            });
        });
    });

    document.querySelectorAll('.pmr-builder-edit-group').forEach(function (btn) {
        btn.addEventListener('click', function (e) {
            e.preventDefault();
            openEditModal('title', {
                functionName: 'saveGroup',
                heading: 'Edit group',
                id: btn.dataset.id,
                sectionId: btn.dataset.sectionId,
                value: btn.dataset.title || '',
                status: btn.dataset.status
            });
        });
    });

    document.querySelectorAll('.pmr-builder-edit-question').forEach(function (btn) {
        btn.addEventListener('click', function () {
            openEditModal('question', {
                functionName: 'saveQuestion',
                heading: 'Edit question',
                id: btn.dataset.id,
                sectionId: btn.dataset.sectionId,
                groupId: btn.dataset.groupId || '',
                value: btn.dataset.text || '',
                inputs: btn.dataset.inputs || '[]',
                status: btn.dataset.status
            });
        });
    });

    document.getElementById('pmrBuilderEditClose').addEventListener('click', closeEditModal);
    document.getElementById('pmrBuilderEditCancel').addEventListener('click', closeEditModal);
    editModal.addEventListener('click', function (e) {
        if (e.target === editModal) closeEditModal();
    });

    document.getElementById('pmrBuilderEditSave').addEventListener('click', function () {
        const functionName = document.getElementById('pmrBuilderEditFunction').value;
        const status = document.getElementById('pmrBuilderEditStatus').checked ? '1' : '';

        if (functionName === 'saveSystemType') {
            postBuilder({
                FUNCTION: functionName,
                id: document.getElementById('pmrBuilderEditId').value,
                title: document.getElementById('pmrBuilderEditValue').value,
                status: status,
                tenant: TENANT_URL
            });
            return;
        }

        if (functionName === 'saveSection') {
            postBuilder({
                FUNCTION: functionName,
                id: document.getElementById('pmrBuilderEditId').value,
                system_type_id: document.getElementById('pmrBuilderEditSystemTypeId').value,
                title: document.getElementById('pmrBuilderEditValue').value,
                status: status,
                tenant: TENANT_URL
            });
            return;
        }

        if (functionName === 'saveGroup') {
            postBuilder({
                FUNCTION: functionName,
                id: document.getElementById('pmrBuilderEditId').value,
                section_id: document.getElementById('pmrBuilderEditSectionId').value,
                title: document.getElementById('pmrBuilderEditValue').value,
                status: status,
                tenant: TENANT_URL
            });
            return;
        }

        if (functionName === 'saveQuestion') {
            postBuilder({
                FUNCTION: functionName,
                id: document.getElementById('pmrBuilderEditId').value,
                section_id: document.getElementById('pmrBuilderEditSectionId').value,
                group_id: document.getElementById('pmrBuilderEditGroupId').value,
                question_text: document.getElementById('pmrBuilderEditQuestionText').value,
                input_types_json: JSON.stringify(inputTypesFrom(document.getElementById('pmrBuilderEditInputsField'))),
                status: status,
                tenant: TENANT_URL
            });
        }
    });

    document.querySelectorAll('.pmr-builder-delete').forEach(function (btn) {
        btn.addEventListener('click', function (e) {
            e.preventDefault();
            confirmDelete(btn.dataset.message || 'Delete this item?', function () {
                postBuilder({FUNCTION: btn.dataset.function, id: btn.dataset.id, tenant: TENANT_URL});
            });
        });
    });

    document.querySelectorAll('.pmr-builder-move').forEach(function (btn) {
        btn.addEventListener('click', function (e) {
            e.preventDefault();
            postBuilder({FUNCTION: btn.dataset.function, id: btn.dataset.id, direction: btn.dataset.direction, tenant: TENANT_URL});
        });
    });
})();
</script>
