<?php
$sections = [];
$resSections = mysqli_query(
    $GLOBALS['con'],
    "SELECT s.`id`, s.`title`, st.`title` AS system_type_title
     FROM `pmr_sections` s
     INNER JOIN `pmr_system_types` st ON st.`id` = s.`system_type_id`
     ORDER BY st.`sort_order` ASC, s.`sort_order` ASC, s.`id` ASC"
) or die(mysqli_error($GLOBALS['con']));
while ($row = mysqli_fetch_assoc($resSections)) {
    $sections[] = $row;
}

$groups = [];
$resGroups = mysqli_query(
    $GLOBALS['con'],
    "SELECT g.`id`, g.`section_id`, g.`title`
     FROM `pmr_groups` g
     ORDER BY g.`section_id` ASC, g.`sort_order` ASC, g.`id` ASC"
) or die(mysqli_error($GLOBALS['con']));
while ($row = mysqli_fetch_assoc($resGroups)) {
    $groups[] = $row;
}

$questions = [];
$res = mysqli_query(
    $GLOBALS['con'],
    "SELECT q.*, s.`title` AS section_title, st.`title` AS system_type_title, g.`title` AS group_title
     FROM `pmr_questions` q
     INNER JOIN `pmr_sections` s ON s.`id` = q.`section_id`
     INNER JOIN `pmr_system_types` st ON st.`id` = s.`system_type_id`
     LEFT JOIN `pmr_groups` g ON g.`id` = q.`group_id`
     ORDER BY st.`sort_order` ASC, s.`sort_order` ASC, COALESCE(g.`sort_order`, 0) ASC, q.`sort_order` ASC, q.`id` ASC"
) or die(mysqli_error($GLOBALS['con']));
while ($row = mysqli_fetch_assoc($res)) {
    $inputs = json_decode((string)$row['input_types_json'], true);
    $row['input_types'] = is_array($inputs) ? $inputs : [];
    $questions[] = $row;
}

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

<div class="row">
    <div class="col-lg-5 mb-4">
        <div class="card">
            <div class="card-header">
                <strong>Question Editor</strong>
            </div>
            <div class="card-body">
                <input type="hidden" id="pmrQuestionId" value="0">

                <div class="mb-3">
                    <label class="form-label">Section</label>
                    <select class="form-control" id="pmrQuestionSection">
                        <option value="">Select section</option>
                        <?php foreach ($sections as $row) { ?>
                            <option value="<?= (int)$row['id'] ?>">
                                <?= htmlspecialchars($row['system_type_title'] . ' / ' . $row['title'], ENT_QUOTES) ?>
                            </option>
                        <?php } ?>
                    </select>
                </div>

                <div class="mb-3">
                    <label class="form-label">Group</label>
                    <select class="form-control" id="pmrQuestionGroup">
                        <option value="">Directly under section</option>
                        <?php foreach ($groups as $row) { ?>
                            <option value="<?= (int)$row['id'] ?>" data-section-id="<?= (int)$row['section_id'] ?>">
                                <?= htmlspecialchars($row['title'], ENT_QUOTES) ?>
                            </option>
                        <?php } ?>
                    </select>
                    <small class="text-muted">Leave blank for section-level questions such as OVERALL SYSTEM.</small>
                </div>

                <div class="mb-3">
                    <label class="form-label">Question Text</label>
                    <textarea class="form-control" id="pmrQuestionText" rows="5"></textarea>
                </div>

                <div class="mb-3">
                    <label class="form-label d-block">Input Types</label>
                    <?php foreach ($inputOptions as $value => $label) { ?>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input pmr-question-input-type" type="checkbox" id="pmrInput<?= htmlspecialchars($value, ENT_QUOTES) ?>" value="<?= htmlspecialchars($value, ENT_QUOTES) ?>">
                            <label class="form-check-label" for="pmrInput<?= htmlspecialchars($value, ENT_QUOTES) ?>"><?= htmlspecialchars($label, ENT_QUOTES) ?></label>
                        </div>
                    <?php } ?>
                </div>

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

                <div class="d-flex gap-2">
                    <button type="button" class="btn btn-info" id="savePmrQuestionBtn">Save Question</button>
                    <button type="button" class="btn btn-secondary" id="resetPmrQuestionBtn">Reset</button>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-7 mb-4">
        <div class="card">
            <div class="card-header">
                <strong>Questions</strong>
            </div>
            <div class="card-body">
                <?php if (empty($questions)) { ?>
                    <div class="alert alert-warning mb-0">No questions created yet.</div>
                <?php } else { ?>
                    <div class="table-responsive">
                        <table class="table table-sm align-middle">
                            <thead>
                                <tr>
                                    <th style="width:70px;">Order</th>
                                    <th>Question</th>
                                    <th style="width:180px;">Location</th>
                                    <th style="width:120px;">Inputs</th>
                                    <th style="width:90px;">Status</th>
                                    <th style="width:170px;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($questions as $row) { ?>
                                    <tr>
                                        <td><?= (int)$row['sort_order'] ?></td>
                                        <td><?= htmlspecialchars($row['question_text'], ENT_QUOTES) ?></td>
                                        <td>
                                            <?= htmlspecialchars($row['system_type_title'], ENT_QUOTES) ?>
                                            <span class="text-muted">/</span>
                                            <?= htmlspecialchars($row['section_title'], ENT_QUOTES) ?>
                                            <?php if (!empty($row['group_title'])) { ?>
                                                <div class="small text-muted"><?= htmlspecialchars($row['group_title'], ENT_QUOTES) ?></div>
                                            <?php } ?>
                                        </td>
                                        <td><?= htmlspecialchars(implode(', ', $row['input_types']), ENT_QUOTES) ?></td>
                                        <td><?= (int)$row['status'] === 1 ? 'Active' : 'Inactive' ?></td>
                                        <td>
                                            <button type="button" class="btn btn-info btn-sm me-1 pmr-edit-question"
                                                    data-id="<?= (int)$row['id'] ?>"
                                                    data-section-id="<?= (int)$row['section_id'] ?>"
                                                    data-group-id="<?= (int)($row['group_id'] ?? 0) ?>"
                                                    data-text="<?= htmlspecialchars($row['question_text'], ENT_QUOTES) ?>"
                                                    data-inputs="<?= htmlspecialchars(json_encode($row['input_types']), ENT_QUOTES) ?>"
                                                    data-status="<?= (int)$row['status'] ?>">Edit</button>
                                            <button type="button" class="btn btn-secondary btn-sm me-1 pmr-move-question" data-id="<?= (int)$row['id'] ?>" data-direction="up">&#8593;</button>
                                            <button type="button" class="btn btn-secondary btn-sm me-1 pmr-move-question" data-id="<?= (int)$row['id'] ?>" data-direction="down">&#8595;</button>
                                            <button type="button" class="btn btn-danger btn-sm pmr-delete-question" data-id="<?= (int)$row['id'] ?>">Delete</button>
                                        </td>
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    </div>
                <?php } ?>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    const endpoint = ROOT_URL + '/includes/pmr/pmr_functions.php';
    const sectionSelect = document.getElementById('pmrQuestionSection');
    const groupSelect = document.getElementById('pmrQuestionGroup');

    function filterGroups() {
        const sectionId = sectionSelect.value || '';
        [...groupSelect.options].forEach(function (option) {
            if (!option.value) {
                option.hidden = false;
                return;
            }
            option.hidden = option.dataset.sectionId !== sectionId;
        });
        if (groupSelect.selectedOptions.length && groupSelect.selectedOptions[0].hidden) {
            groupSelect.value = '';
        }
    }

    function resetForm() {
        document.getElementById('pmrQuestionId').value = '0';
        sectionSelect.value = '';
        groupSelect.value = '';
        document.getElementById('pmrQuestionText').value = '';
        document.getElementById('pmrQuestionStatus').checked = true;
        document.querySelectorAll('.pmr-question-input-type').forEach(cb => cb.checked = false);
        filterGroups();
    }

    function selectedInputTypes() {
        return [...document.querySelectorAll('.pmr-question-input-type:checked')].map(cb => cb.value);
    }

    function postQuestion(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=questions';
        })
        .catch(() => showResponse('danger', 'There was a problem processing the request'));
    }

    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();
        });
    }

    sectionSelect.addEventListener('change', filterGroups);
    filterGroups();

    document.getElementById('savePmrQuestionBtn').addEventListener('click', function () {
        postQuestion({
            FUNCTION: 'saveQuestion',
            id: document.getElementById('pmrQuestionId').value,
            section_id: sectionSelect.value,
            group_id: groupSelect.value,
            question_text: document.getElementById('pmrQuestionText').value,
            input_types_json: JSON.stringify(selectedInputTypes()),
            status: document.getElementById('pmrQuestionStatus').checked ? '1' : '',
                tenant: TENANT_URL
        });
    });
    document.getElementById('resetPmrQuestionBtn').addEventListener('click', resetForm);

    document.querySelectorAll('.pmr-edit-question').forEach(function (btn) {
        btn.addEventListener('click', function () {
            document.getElementById('pmrQuestionId').value = btn.dataset.id;
            sectionSelect.value = btn.dataset.sectionId || '';
            filterGroups();
            groupSelect.value = btn.dataset.groupId && btn.dataset.groupId !== '0' ? btn.dataset.groupId : '';
            document.getElementById('pmrQuestionText').value = btn.dataset.text || '';
            document.getElementById('pmrQuestionStatus').checked = btn.dataset.status === '1';
            let inputs = [];
            try { inputs = JSON.parse(btn.dataset.inputs || '[]'); } catch (e) { inputs = []; }
            document.querySelectorAll('.pmr-question-input-type').forEach(function (cb) {
                cb.checked = inputs.includes(cb.value);
            });
            window.scrollTo({top: 0, behavior: 'smooth'});
        });
    });
    document.querySelectorAll('.pmr-delete-question').forEach(function (btn) {
        btn.addEventListener('click', function () {
            confirmDelete('Delete this question?', function () {
                postQuestion({FUNCTION: 'deleteQuestion', id: btn.dataset.id, tenant: TENANT_URL});
            });
        });
    });
    document.querySelectorAll('.pmr-move-question').forEach(function (btn) {
        btn.addEventListener('click', function () {
            postQuestion({FUNCTION: 'moveQuestion', id: btn.dataset.id, direction: btn.dataset.direction, tenant: TENANT_URL});
        });
    });
})();
</script>
