<?php
$templates = [];
$res = mysqli_query(
    $GLOBALS['con'],
    "SELECT * FROM `puwer_templates` ORDER BY `sort_order` ASC, `id` ASC"
) or die(mysqli_error($GLOBALS['con']));

while ($row = mysqli_fetch_assoc($res)) {
    $checklistIds = json_decode((string)($row['checklist_ids_json'] ?? '[]'), true);
    if (!is_array($checklistIds)) {
        $checklistIds = [];
    }
    $row['checklist_ids'] = array_map('intval', $checklistIds);

    $templates[] = $row;
}

$checklists = [];
$res2 = mysqli_query(
    $GLOBALS['con'],
    "SELECT `id`, `title`, `status`, `sort_order`
     FROM `puwer_checklists`
     ORDER BY `sort_order` ASC, `id` ASC"
) or die(mysqli_error($GLOBALS['con']));

while ($row = mysqli_fetch_assoc($res2)) {
    $checklists[] = $row;
}

$checklistLookup = [];
foreach ($checklists as $row) {
    $checklistLookup[(int)$row['id']] = $row['title'];
}
?>

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

                <div class="mb-3">
                    <label class="form-label">Template Set Title</label>
                    <input type="text" class="form-control" id="puwerTemplateTitle">
                </div>

                <div class="mb-3">
                    <label class="form-label">Available Checklists</label>
                    <div class="border rounded p-2" style="max-height:220px; overflow:auto;">
                        <?php foreach ($checklists as $row) { ?>
                            <div class="d-flex justify-content-between align-items-center border-bottom py-1">
                                <div>
                                    <?= htmlspecialchars($row['title'], ENT_QUOTES) ?>
                                    <?php if ((int)$row['status'] !== 1) { ?>
                                        <small class="text-danger">(Inactive)</small>
                                    <?php } ?>
                                </div>
                                <button type="button"
                                        class="btn btn-info btn-sm puwer-add-checklist"
                                        data-id="<?= (int)$row['id'] ?>"
                                        data-title="<?= htmlspecialchars($row['title'], ENT_QUOTES) ?>">
                                    Add
                                </button>
                            </div>
                        <?php } ?>
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label">Selected Checklists</label>
                    <div class="border rounded p-2">
                        <ul class="list-group mb-0" id="puwerSelectedChecklists"></ul>
                    </div>
                    <small class="text-muted">Drag and drop to change the order they load in 5002.</small>
                </div>

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

                <div class="d-flex gap-2">
                    <button type="button" class="btn btn-info" id="savePuwerTemplateBtn">Save Template Set</button>
                    <button type="button" class="btn btn-secondary" id="resetPuwerTemplateBtn">Reset</button>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-7 mb-4">
        <div class="card">
            <div class="card-header">
                <strong>Template Sets</strong>
            </div>
            <div class="card-body">
                <?php if (empty($templates)) { ?>
                    <div class="alert alert-warning mb-0">No template sets 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>Template Set</th>
                                    <th style="width:120px;">Checklists</th>
                                    <th style="width:90px;">Status</th>
                                    <th style="width:130px;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($templates as $row) { ?>
                                    <?php
                                    $checklistLabels = [];
                                    foreach ($row['checklist_ids'] as $cid) {
                                        if (isset($checklistLookup[$cid])) {
                                            $checklistLabels[] = $checklistLookup[$cid];
                                        }
                                    }
                                    ?>
                                    <tr>
                                        <td><?= (int)$row['sort_order'] ?></td>
                                        <td>
                                            <strong><?= htmlspecialchars($row['template_title'], ENT_QUOTES) ?></strong>
                                            <?php if (!empty($checklistLabels)) { ?>
                                                <div class="small text-muted mt-1">
                                                    <?= htmlspecialchars(implode(', ', $checklistLabels), ENT_QUOTES) ?>
                                                </div>
                                            <?php } ?>
                                        </td>
                                        <td><?= count($row['checklist_ids']) ?></td>
                                        <td><?= (int)$row['status'] === 1 ? 'Active' : 'Inactive' ?></td>
                                        <td>
                                            <button type="button"
                                                    class="btn btn-info btn-sm me-1 puwer-edit-template"
                                                    data-id="<?= (int)$row['id'] ?>"
                                                    data-title="<?= htmlspecialchars($row['template_title'], ENT_QUOTES) ?>"
                                                    data-checklists="<?= htmlspecialchars(json_encode($row['checklist_ids']), ENT_QUOTES) ?>"
                                                    data-status="<?= (int)$row['status'] ?>">
                                                Edit
                                            </button>

                                            <button type="button"
                                                    class="btn btn-danger btn-sm puwer-delete-template"
                                                    data-id="<?= (int)$row['id'] ?>">
                                                Delete
                                            </button>
                                        </td>
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    </div>
                    <small class="text-muted d-block mt-2">Template display order still uses sort_order. Checklist order inside each template set is drag-and-drop.</small>
                <?php } ?>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    const endpoint = ROOT_URL + '/includes/puwer/puwer_functions.php';
    const tenant = typeof TENANT_URL !== 'undefined' ? TENANT_URL : '';
    const selectedList = document.getElementById('puwerSelectedChecklists');

    function resetTemplateForm() {
        document.getElementById('puwerTemplateId').value = '0';
        document.getElementById('puwerTemplateTitle').value = '';
        document.getElementById('puwerTemplateStatus').checked = true;
        selectedList.innerHTML = '';
    }

    function createChecklistListItem(id, title) {
        const li = document.createElement('li');
        li.className = 'list-group-item d-flex justify-content-between align-items-center puwer-selected-checklist';
        li.setAttribute('data-id', id);
        li.setAttribute('draggable', 'true');
        li.innerHTML =
            '<span class="puwer-drag-handle" style="cursor:move;">&#9776; ' + title + '</span>' +
            '<button type="button" class="btn btn-danger btn-sm puwer-remove-checklist">Remove</button>';

        li.addEventListener('dragstart', function (e) {
            li.classList.add('dragging');
            e.dataTransfer.setData('text/plain', id);
        });

        li.addEventListener('dragend', function () {
            li.classList.remove('dragging');
        });

        li.querySelector('.puwer-remove-checklist').addEventListener('click', function () {
            li.remove();
        });

        return li;
    }

    selectedList.addEventListener('dragover', function (e) {
        e.preventDefault();
        const dragging = selectedList.querySelector('.dragging');
        if (!dragging) return;

        const items = [...selectedList.querySelectorAll('.puwer-selected-checklist:not(.dragging)')];
        const nextItem = items.find(item => {
            const box = item.getBoundingClientRect();
            return e.clientY <= box.top + box.height / 2;
        });

        if (nextItem) {
            selectedList.insertBefore(dragging, nextItem);
        } else {
            selectedList.appendChild(dragging);
        }
    });

    function getSelectedChecklistIds() {
        return [...selectedList.querySelectorAll('.puwer-selected-checklist')].map(function (li) {
            return parseInt(li.getAttribute('data-id') || '0', 10);
        }).filter(Boolean);
    }

    function postTemplate(data) {
        data.tenant = tenant;

        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=puwer_config.php&view=templates&tenant=' + encodeURIComponent(tenant);
            }
        })
        .catch(() => showResponse('danger', 'There was a problem processing the request'));
    }

    document.querySelectorAll('.puwer-add-checklist').forEach(function (btn) {
        btn.addEventListener('click', function () {
            const id = btn.dataset.id;
            const title = btn.dataset.title || '';

            const exists = [...selectedList.querySelectorAll('.puwer-selected-checklist')].some(function (li) {
                return li.getAttribute('data-id') === id;
            });

            if (exists) return;

            selectedList.appendChild(createChecklistListItem(id, title));
        });
    });

    document.getElementById('savePuwerTemplateBtn').addEventListener('click', function () {
        postTemplate({
            FUNCTION: 'saveTemplate',
            id: document.getElementById('puwerTemplateId').value,
            template_title: document.getElementById('puwerTemplateTitle').value,
            checklist_ids_json: JSON.stringify(getSelectedChecklistIds()),
            status: document.getElementById('puwerTemplateStatus').checked ? '1' : '',
            tenant: TENANT_URL
        });
    });

    document.getElementById('resetPuwerTemplateBtn').addEventListener('click', resetTemplateForm);

    document.querySelectorAll('.puwer-edit-template').forEach(function (btn) {
        btn.addEventListener('click', function () {
            resetTemplateForm();

            document.getElementById('puwerTemplateId').value = btn.dataset.id || '0';
            document.getElementById('puwerTemplateTitle').value = btn.dataset.title || '';
            document.getElementById('puwerTemplateStatus').checked = btn.dataset.status === '1';

            let checklistIds = [];
            try { checklistIds = JSON.parse(btn.dataset.checklists || '[]'); } catch (e) { checklistIds = []; }

            checklistIds.forEach(function (cid) {
                const addBtn = document.querySelector('.puwer-add-checklist[data-id="' + cid + '"]');
                if (addBtn) {
                    selectedList.appendChild(createChecklistListItem(cid, addBtn.dataset.title || ''));
                }
            });

            window.scrollTo({top: 0, behavior: 'smooth'});
        });
    });

    document.querySelectorAll('.puwer-delete-template').forEach(function (btn) {
        btn.addEventListener('click', function () {
            if (!confirm('Delete this template set?')) return;

            postTemplate({
                FUNCTION: 'deleteTemplate',
                id: btn.dataset.id,
                tenant: TENANT_URL
            });
        });
    });
})();
</script>