<?php
$rows = [];
$loadError = '';

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    $loadError = 'Database connection is not available.';
} else {
    $res = mysqli_query(
        $GLOBALS['con'],
        "SELECT `formnumber`, `formtype`, `description`, `regs`
         FROM `dd_formtypes`
         ORDER BY `formnumber` ASC"
    );

    if ($res) {
        while ($row = mysqli_fetch_assoc($res)) {
            $rows[] = $row;
        }
    } else {
        $loadError = 'Report type records could not be loaded.';
    }
}
?>

<script>
document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item">Tools <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb-item active">Report Type Titles</li>';
</script>

<div class="row mb-4">
    <div class="col-12">
        <div class="note note-primary mb-3">
            <strong>Report Type Titles:</strong> Manage the tenant-facing report descriptions and regulation text used by
            available custom form types. 
        </div>
    </div>
</div>

<?php if ($loadError !== '') { ?>
    <div class="alert alert-warning"><?= htmlspecialchars($loadError, ENT_QUOTES) ?></div>
<?php } elseif (empty($rows)) { ?>
    <div class="alert alert-warning">No report type records found.</div>
<?php } else { ?>
    <div class="row">
        <?php foreach ($rows as $row) {
            $formnumber = (int)($row['formnumber'] ?? 0);
            ?>
            <div class="col-12 col-lg-6 col-xxl-4 mb-4">
                <div class="card h-100 reptype-card" data-formnumber="<?= $formnumber ?>">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <strong>Form <?= $formnumber ?></strong>
                        <span class="badge badge-secondary">#<?= $formnumber ?></span>
                    </div>
                    <div class="card-body">
                        <input type="hidden" class="reptype-formnumber" value="<?= $formnumber ?>">

                        <div class="row g-3">
                            <div class="col-12 col-md-7">
                                <label class="form-label">Report Type</label>
                                <input type="text"
                                       class="form-control reptype-formtype"
                                       maxlength="80"
                                       value="<?= htmlspecialchars((string)($row['formtype'] ?? ''), ENT_QUOTES) ?>">
                            </div>

                            <div class="col-12 col-md-5">
                                <label class="form-label">Description</label>
                                <input type="text"
                                       class="form-control reptype-description"
                                       maxlength="50"
                                       value="<?= htmlspecialchars((string)($row['description'] ?? ''), ENT_QUOTES) ?>">
                            </div>

                            <div class="col-12">
                                <label class="form-label">Regulations</label>
                                <textarea class="form-control reptype-regs" rows="5"><?= htmlspecialchars((string)($row['regs'] ?? ''), ENT_QUOTES) ?></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="card-footer text-end">
                        <button type="button" class="btn btn-success reptype-save">
                            <i class="fad fa-save me-1"></i>Save
                        </button>
                    </div>
                </div>
            </div>
        <?php } ?>
    </div>
<?php } ?>

<script>
(function () {
    const endpoint = ROOT_URL + '/includes/reptypes/reptypes_functions.php';

    function postReportType(card) {
        const formnumber = card.querySelector('.reptype-formnumber').value;
        const formtype = card.querySelector('.reptype-formtype').value;
        const description = card.querySelector('.reptype-description').value;
        const regs = card.querySelector('.reptype-regs').value;
        const button = card.querySelector('.reptype-save');

        if (button) {
            button.disabled = true;
        }

        fetch(endpoint, {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: new URLSearchParams({
                FUNCTION: 'updateReportType',
                tenant: '<?= htmlspecialchars((string)(defined('TENANT_URL') ? TENANT_URL : ''), ENT_QUOTES) ?>',
                formnumber: formnumber,
                formtype: formtype,
                description: description,
                regs: regs
            })
        })
        .then(response => response.json())
        .then(data => {
            showResponse(data.status === 'success' ? 'success' : 'danger', data.message || 'Unable to update report type');
        })
        .catch(() => {
            showResponse('danger', 'There was a problem updating the report type');
        })
        .finally(() => {
            if (button) {
                button.disabled = false;
            }
        });
    }

    document.querySelectorAll('.reptype-save').forEach(function (button) {
        button.addEventListener('click', function () {
            const card = button.closest('.reptype-card');
            if (card) {
                postReportType(card);
            }
        });
    });

    document.addEventListener('DOMContentLoaded', function () {
        const footerControls = document.getElementById('footerControls');
        if (footerControls) {
            footerControls.innerHTML = '';
        }
    });
})();
</script>
