<?php
include 'db.php';
include 'layout.php';

$cat_result = mysqli_query($conn, "SELECT * FROM setting_categories ORDER BY name");
$categories = [];
while ($cat = mysqli_fetch_assoc($cat_result)) {
    $categories[] = $cat;
}
?>

<div class="page-wrapper">
    <div class="content settings-content">
        <div class="page-header settings-pg-header">
            <div class="add-item d-flex">
                <div class="page-title">
                    <h4>Settings</h4>
                    <h6>Click a category to load its settings</h6>
                </div>
            </div>
        </div>

        <div class="row">
            <?php foreach ($categories as $cat): ?>
                <div class="col-12 mb-3">
                    <h5 class="pointer category-heading" data-id="<?= $cat['id'] ?>" style="cursor:pointer;">
                        <i data-feather="folder"></i> <?= htmlspecialchars($cat['name']) ?>
                    </h5>
                   <div id="cat-settings-<?= $cat['id'] ?>" class="category-settings" style="display:none;">
   <?php if ($cat['code'] === 'integration'): ?>
    <?php include 'fbr_config_form.php'; ?>
<?php elseif ($cat['code'] === 'fbr_digital_integration'): ?>
    <?php include 'fbr_digital_config_form.php'; ?>
<?php elseif ($cat['code'] === 'kpra_integration'): ?>
    <?php include 'kpra_config_form.php'; ?>
<?php elseif ($cat['code'] === 'system_settings'): ?>
    <?php include 'includes/system_settings_form.php'; ?>
<?php elseif ($cat['code'] === 'tax_settings'): ?>
    <?php include 'includes/tax_settings_form.php'; ?>
<?php endif; ?>


</div>

                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<script>
document.querySelectorAll('.category-heading').forEach(header => {
    header.addEventListener('click', function () {
        const catId = this.dataset.id;
        const container = document.getElementById('cat-settings-' + catId);

        container.style.display = container.style.display === 'none' ? 'block' : 'none';

        if (container.getAttribute('data-loaded')) return;

     document.querySelectorAll('.category-heading').forEach(header => {
    header.addEventListener('click', function () {
        const catId = this.dataset.id;
        const catCode = this.textContent.trim().toLowerCase();
        const container = document.getElementById('cat-settings-' + catId);

        // Toggle visibility
        container.style.display = container.style.display === 'none' ? 'block' : 'none';

        // If it's already loaded, do nothing
        if (container.getAttribute('data-loaded')) return;

        // 🚫 Don't fetch for Integration – it's already included
        if (catCode.includes('integration')) {
            container.setAttribute('data-loaded', '1');
            feather.replace();
            return;
        }

        // ✅ AJAX load for other categories
        fetch('load_category_settings.php?category_id=' + catId)
            .then(res => res.text())
            .then(html => {
                container.innerHTML = html;
                container.setAttribute('data-loaded', '1');
                feather.replace();
            });
    });
});

    });
});

// ✅ Handle setting toggle updates (generic)
document.addEventListener('change', function (e) {
    if (e.target.classList.contains('setting-toggle')) {
        const settingId = e.target.dataset.id;
        const newValue = e.target.checked ? '1' : '0';

        fetch('update_setting.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `id=${settingId}&value=${newValue}`
        })
        .then(res => res.text())
        .then(msg => {
            console.log('Setting updated:', msg);
            if (typeof Swal !== 'undefined') {
                Swal.fire({
                    toast: true,
                    icon: 'success',
                    title: 'Setting saved',
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 1200
                });
            }
        })
        .catch(() => alert('Error saving setting'));
    }
});

function updateSetting(input) {
    const settingId = input.dataset.id;
    const newValue = input.value;
    fetch('update_setting.php?ts=' + Date.now(), {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `id=${settingId}&value=${encodeURIComponent(newValue)}`
    })
    .then(res => res.text())
    .then(msg => {
        // Optionally show a toast or alert
        // alert(msg);
    });
}
</script>
