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

while ($row = mysqli_fetch_assoc($res)) {
    $rows[] = $row;
}
?>

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

                <div class="mb-3">
                    <label class="form-label">Ref</label>
                    <input type="text" class="form-control" id="puwerAssessmentRef">
                </div>

                <div class="mb-3">
                    <label class="form-label">Item Text</label>
                    <textarea class="form-control" id="puwerAssessmentText" rows="6"></textarea>
                </div>

                <div class="form-check mb-2">
                    <input class="form-check-input" type="checkbox" id="puwerAssessmentHeading">
                    <label class="form-check-label" for="puwerAssessmentHeading">Heading row</label>
                </div>

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

                <div class="d-flex gap-2">
                    <button type="button" class="btn btn-info" id="savePuwerAssessmentBtn">Save Row</button>
                    <button type="button" class="btn btn-secondary" id="resetPuwerAssessmentBtn">Reset</button>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-7 mb-4">
        <div class="card">
            <div class="card-header">
                <strong>Assessment Defaults</strong>
            </div>
            <div class="card-body">
                <?php if (empty($rows)) { ?>
                    <div class="alert alert-warning mb-0">No assessment defaults 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 style="width:90px;">Ref</th>
                                    <th>Item</th>
                                    <th style="width:90px;">Heading</th>
                                    <th style="width:90px;">Status</th>
                                    <th style="width:170px;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($rows as $row) { ?>
                                    <tr>
                                        <td><?= (int)$row['sort_order'] ?></td>
                                        <td><?= htmlspecialchars($row['ref'], ENT_QUOTES) ?></td>
                                        <td><?= htmlspecialchars($row['item_text'], ENT_QUOTES) ?></td>
                                        <td><?= (int)$row['is_heading'] === 1 ? 'Yes' : 'No' ?></td>
                                        <td><?= (int)$row['status'] === 1 ? 'Active' : 'Inactive' ?></td>
                                        <td>
                                            <button type="button"
                                                    class="btn btn-info btn-sm me-1 puwer-edit-assessment"
                                                    data-id="<?= (int)$row['id'] ?>"
                                                    data-ref="<?= htmlspecialchars($row['ref'], ENT_QUOTES) ?>"
                                                    data-text="<?= htmlspecialchars($row['item_text'], ENT_QUOTES) ?>"
                                                    data-heading="<?= (int)$row['is_heading'] ?>"
                                                    data-status="<?= (int)$row['status'] ?>">
                                                Edit
                                            </button>

                                            <button type="button"
                                                    class="btn btn-secondary btn-sm me-1 puwer-move-assessment"
                                                    data-id="<?= (int)$row['id'] ?>"
                                                    data-direction="up">
                                                ↑
                                            </button>

                                            <button type="button"
                                                    class="btn btn-secondary btn-sm me-1 puwer-move-assessment"
                                                    data-id="<?= (int)$row['id'] ?>"
                                                    data-direction="down">
                                                ↓
                                            </button>

                                            <button type="button"
                                                    class="btn btn-danger btn-sm puwer-delete-assessment"
                                                    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/puwer/puwer_functions.php';

    function resetAssessmentForm() {
        document.getElementById('puwerAssessmentId').value = '0';
        document.getElementById('puwerAssessmentRef').value = '';
        document.getElementById('puwerAssessmentText').value = '';
        document.getElementById('puwerAssessmentHeading').checked = false;
        document.getElementById('puwerAssessmentStatus').checked = true;
    }

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

    document.getElementById('savePuwerAssessmentBtn').addEventListener('click', function () {
        postAssessment({
            FUNCTION: 'saveAssessment',
            id: document.getElementById('puwerAssessmentId').value,
            ref: document.getElementById('puwerAssessmentRef').value,
            item_text: document.getElementById('puwerAssessmentText').value,
            is_heading: document.getElementById('puwerAssessmentHeading').checked ? '1' : '',
            status: document.getElementById('puwerAssessmentStatus').checked ? '1' : '',
             tenant: TENANT_URL,
        });
    });

    document.getElementById('resetPuwerAssessmentBtn').addEventListener('click', resetAssessmentForm);

    document.querySelectorAll('.puwer-edit-assessment').forEach(function (btn) {
        btn.addEventListener('click', function () {
            document.getElementById('puwerAssessmentId').value = btn.dataset.id;
            document.getElementById('puwerAssessmentRef').value = btn.dataset.ref || '';
            document.getElementById('puwerAssessmentText').value = btn.dataset.text || '';
            document.getElementById('puwerAssessmentHeading').checked = btn.dataset.heading === '1';
            document.getElementById('puwerAssessmentStatus').checked = btn.dataset.status === '1';
            window.scrollTo({top: 0, behavior: 'smooth'});
        });
    });

    document.querySelectorAll('.puwer-delete-assessment').forEach(function (btn) {
        btn.addEventListener('click', function () {
            if (!confirm('Delete this assessment row?')) return;
            postAssessment({
                FUNCTION: 'deleteAssessment',
                id: btn.dataset.id,
                tenant: TENANT_URL,
            });
        });
    });

    document.querySelectorAll('.puwer-move-assessment').forEach(function (btn) {
        btn.addEventListener('click', function () {
            postAssessment({
                FUNCTION: 'moveAssessment',
                id: btn.dataset.id,
                direction: btn.dataset.direction,
                tenant: TENANT_URL,
            });
        });
    });
})();
</script>