<?php
$systemTypes = [];
$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;
}
?>

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

                <div class="mb-3">
                    <label class="form-label">System Type Title</label>
                    <input type="text" class="form-control" id="pmrSystemTypeTitle" placeholder="LX, AV, SND, Induction Loop">
                </div>

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

                <div class="d-flex gap-2">
                    <button type="button" class="btn btn-info" id="savePmrSystemTypeBtn">Save System Type</button>
                    <button type="button" class="btn btn-secondary" id="resetPmrSystemTypeBtn">Reset</button>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-7 mb-4">
        <div class="card">
            <div class="card-header">
                <strong>System Types</strong>
            </div>
            <div class="card-body">
                <?php if (empty($systemTypes)) { ?>
                    <div class="alert alert-warning mb-0">No system types 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>Title</th>
                                    <th style="width:90px;">Status</th>
                                    <th style="width:170px;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($systemTypes as $row) { ?>
                                    <tr>
                                        <td><?= (int)$row['sort_order'] ?></td>
                                        <td><?= htmlspecialchars($row['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-system-type"
                                                    data-id="<?= (int)$row['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-system-type" data-id="<?= (int)$row['id'] ?>" data-direction="up">&#8593;</button>
                                            <button type="button" class="btn btn-secondary btn-sm me-1 pmr-move-system-type" data-id="<?= (int)$row['id'] ?>" data-direction="down">&#8595;</button>
                                            <button type="button" class="btn btn-danger btn-sm pmr-delete-system-type" 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('pmrSystemTypeId').value = '0';
        document.getElementById('pmrSystemTypeTitle').value = '';
        document.getElementById('pmrSystemTypeStatus').checked = true;
    }

    function postSystemType(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=system_types';
            }
        })
        .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('savePmrSystemTypeBtn').addEventListener('click', function () {
        postSystemType({
            FUNCTION: 'saveSystemType',
            id: document.getElementById('pmrSystemTypeId').value,
            title: document.getElementById('pmrSystemTypeTitle').value,
            status: document.getElementById('pmrSystemTypeStatus').checked ? '1' : ''
        });
    });

    document.getElementById('resetPmrSystemTypeBtn').addEventListener('click', resetForm);

    document.querySelectorAll('.pmr-edit-system-type').forEach(function (btn) {
        btn.addEventListener('click', function () {
            document.getElementById('pmrSystemTypeId').value = btn.dataset.id;
            document.getElementById('pmrSystemTypeTitle').value = btn.dataset.title || '';
            document.getElementById('pmrSystemTypeStatus').checked = btn.dataset.status === '1';
            window.scrollTo({top: 0, behavior: 'smooth'});
        });
    });

    document.querySelectorAll('.pmr-delete-system-type').forEach(function (btn) {
        btn.addEventListener('click', function () {
            confirmDelete('Delete this system type? Sections, groups, and questions under it will also be deleted.', function () {
                postSystemType({FUNCTION: 'deleteSystemType', id: btn.dataset.id});
            });
        });
    });

    document.querySelectorAll('.pmr-move-system-type').forEach(function (btn) {
        btn.addEventListener('click', function () {
            postSystemType({FUNCTION: 'moveSystemType', id: btn.dataset.id, direction: btn.dataset.direction});
        });
    });
})();
</script>
