<?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 = [];
$res = mysqli_query(
    $GLOBALS['con'],
    "SELECT g.*, s.`title` AS section_title, st.`title` AS system_type_title
     FROM `pmr_groups` g
     INNER JOIN `pmr_sections` s ON s.`id` = g.`section_id`
     INNER JOIN `pmr_system_types` st ON st.`id` = s.`system_type_id`
     ORDER BY st.`sort_order` ASC, s.`sort_order` ASC, g.`sort_order` ASC, g.`id` ASC"
) or die(mysqli_error($GLOBALS['con']));
while ($row = mysqli_fetch_assoc($res)) {
    $groups[] = $row;
}
?>

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

                <div class="mb-3">
                    <label class="form-label">Section</label>
                    <select class="form-control" id="pmrGroupSection">
                        <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 Title</label>
                    <input type="text" class="form-control" id="pmrGroupTitle" placeholder="GENERIC LED, DISTRIBUTION BOARD">
                </div>

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

                <div class="d-flex gap-2">
                    <button type="button" class="btn btn-info" id="savePmrGroupBtn">Save Group</button>
                    <button type="button" class="btn btn-secondary" id="resetPmrGroupBtn">Reset</button>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-7 mb-4">
        <div class="card">
            <div class="card-header">
                <strong>Groups</strong>
            </div>
            <div class="card-body">
                <?php if (empty($groups)) { ?>
                    <div class="alert alert-warning mb-0">No groups 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>Group</th>
                                    <th>Section</th>
                                    <th style="width:90px;">Status</th>
                                    <th style="width:170px;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($groups as $row) { ?>
                                    <tr>
                                        <td><?= (int)$row['sort_order'] ?></td>
                                        <td><?= htmlspecialchars($row['title'], ENT_QUOTES) ?></td>
                                        <td>
                                            <?= htmlspecialchars($row['system_type_title'], ENT_QUOTES) ?>
                                            <span class="text-muted">/</span>
                                            <?= htmlspecialchars($row['section_title'], 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-group"
                                                    data-id="<?= (int)$row['id'] ?>"
                                                    data-section-id="<?= (int)$row['section_id'] ?>"
                                                    data-title="<?= htmlspecialchars($row['title'], ENT_QUOTES) ?>"
                                                    data-status="<?= (int)$row['status'] ?>">Edit</button>
                                            <button type="button" class="btn btn-secondary btn-sm me-1 pmr-move-group" data-id="<?= (int)$row['id'] ?>" data-direction="up">&#8593;</button>
                                            <button type="button" class="btn btn-secondary btn-sm me-1 pmr-move-group" data-id="<?= (int)$row['id'] ?>" data-direction="down">&#8595;</button>
                                            <button type="button" class="btn btn-danger btn-sm pmr-delete-group" 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';

    function resetForm() {
        document.getElementById('pmrGroupId').value = '0';
        document.getElementById('pmrGroupSection').value = '';
        document.getElementById('pmrGroupTitle').value = '';
        document.getElementById('pmrGroupStatus').checked = true;
    }

    function postGroup(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=groups';
        })
        .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();
        });
    }

    document.getElementById('savePmrGroupBtn').addEventListener('click', function () {
        postGroup({
            FUNCTION: 'saveGroup',
            id: document.getElementById('pmrGroupId').value,
            section_id: document.getElementById('pmrGroupSection').value,
            title: document.getElementById('pmrGroupTitle').value,
            status: document.getElementById('pmrGroupStatus').checked ? '1' : ''
        });
    });
    document.getElementById('resetPmrGroupBtn').addEventListener('click', resetForm);

    document.querySelectorAll('.pmr-edit-group').forEach(function (btn) {
        btn.addEventListener('click', function () {
            document.getElementById('pmrGroupId').value = btn.dataset.id;
            document.getElementById('pmrGroupSection').value = btn.dataset.sectionId || '';
            document.getElementById('pmrGroupTitle').value = btn.dataset.title || '';
            document.getElementById('pmrGroupStatus').checked = btn.dataset.status === '1';
            window.scrollTo({top: 0, behavior: 'smooth'});
        });
    });
    document.querySelectorAll('.pmr-delete-group').forEach(function (btn) {
        btn.addEventListener('click', function () {
            confirmDelete('Delete this group? Questions under it will also be deleted.', function () {
                postGroup({FUNCTION: 'deleteGroup', id: btn.dataset.id, tenant: TENANT_URL});
            });
        });
    });
    document.querySelectorAll('.pmr-move-group').forEach(function (btn) {
        btn.addEventListener('click', function () {
            postGroup({FUNCTION: 'moveGroup', id: btn.dataset.id, direction: btn.dataset.direction, tenant: TENANT_URL});
        });
    });
})();
</script>
