// ── Advanced Tab ───────────────────────────────────────────────────────
function populateAdvancedTab() {
    const cfg = currentConfig.advanced || {};
    // Audit
    document.getElementById('advAudit').checked = cfg.auditEnabled || false;
    document.getElementById('advAuditTable').value = cfg.auditTable || '';
    document.getElementById('advAuditTable').disabled = cfg.auditEnabled || false;
    // Record Locking
    document.getElementById('advLocking').checked = cfg.recordLocking || false;
    document.getElementById('advLockTable').value = cfg.lockTable || '';
    document.getElementById('advLockTable').disabled = cfg.recordLocking || false;
    // Notifications (checkbox, not radios)
    const notifCheckbox = document.getElementById('notifEnableCheck');
    if (notifCheckbox) {
        notifCheckbox.checked = cfg.notifEnabled === true;
        document.getElementById('notifTableName').disabled = cfg.notifEnabled === true;
        document.getElementById('notifFields').style.display = cfg.notifEnabled ? 'block' : 'none';
    }
    // Other fields
    document.getElementById('advLockTimeout').value = cfg.lockTimeout || 300;
    document.getElementById('advWatermark').value = cfg.exportWatermark || '';
    const tz = document.getElementById('advTimezone');
    if (tz) tz.value = cfg.timezone || '';
    updateTzInfo();
}

// Live "+5:45 9:23 PM" readout for the selected project timezone.
function updateTzInfo() {
    const out = document.getElementById('advTzInfo');
    const sel = document.getElementById('advTimezone');
    if (!out || !sel) return;
    const tz = sel.value || 'UTC';
    try {
        const now = new Date();
        let off = '';
        const parts = new Intl.DateTimeFormat('en-US', { timeZone: tz, timeZoneName: 'shortOffset' }).formatToParts(now);
        const op = parts.find(p => p.type === 'timeZoneName');
        if (op) off = op.value.replace(/GMT|UTC/, '');
        if (!off) off = '+0:00';
        off = off.replace(/^([+-])0(\d:)/, '$1$2'); // +05:45 -> +5:45
        if (/^[+-]?\d+$/.test(off)) off += ':00'; // whole hours: +1 -> +1:00
        const time = new Intl.DateTimeFormat('en-US', { timeZone: tz, hour: 'numeric', minute: '2-digit', hour12: true }).format(now);
        out.innerHTML = '<span class="adv-tz-off">' + off + '</span> ' + time;
    } catch (e) {
        out.textContent = '';
    }
}
// Keep the clock ticking (guard against duplicate intervals across renders).
if (!window.__advTzTick) {
    window.__advTzTick = setInterval(updateTzInfo, 1000);
}

// Helper to collect current advanced settings data
function getAdvancedData() {
    return {
        auditEnabled: document.getElementById('advAudit')?.checked || false,
        auditTable: document.getElementById('advAuditTable')?.value || '',
        recordLocking: document.getElementById('advLocking')?.checked || false,
        lockTable: document.getElementById('advLockTable')?.value || '',
        lockTimeout: parseInt(document.getElementById('advLockTimeout')?.value) || 300,
        exportWatermark: document.getElementById('advWatermark')?.value || '',
        timezone: document.getElementById('advTimezone')?.value || '',
        notifEnabled: document.getElementById('notifEnableCheck')?.checked || false,
        notifTableName: document.getElementById('notifTableName')?.value || 'notifications'
    };
}

// Save on page hide using sendBeacon
window.addEventListener('pagehide', () => {
    if (typeof isPageUnloading !== 'undefined') isPageUnloading = true;
    const data = getAdvancedData();
    navigator.sendBeacon(
        `${baseUrl}/project/${projectSlug}/misc/save`,
        JSON.stringify({ section: 'advanced', data })
    );
});

document.addEventListener('DOMContentLoaded', () => {
    // Regular fields: trigger normal save on change
    const regularFields = [
        'advLockTimeout', 'advWatermark', 'advTimezone'
    ];
    regularFields.forEach(id => {
        const el = document.getElementById(id);
        if (el) el.addEventListener('change', () => saveSection('advanced'));
    });
    const tzSel = document.getElementById('advTimezone');
    if (tzSel) tzSel.addEventListener('change', updateTzInfo);

    // ── Audit Trail Toggle ──────────────────────────────────────────────
    const auditCheckbox = document.getElementById('advAudit');
    const auditTableInput = document.getElementById('advAuditTable');
    if (auditCheckbox) {
        auditCheckbox.addEventListener('change', async function () {
            const isEnabling = this.checked;
            if (isEnabling) {
                const { value: tableName } = await Swal.fire({
                    title: 'Audit Trail Table Name',
                    input: 'text',
                    inputValue: auditTableInput.value.trim() || 'audit_log',
                    inputPlaceholder: 'Enter table name (e.g., audit_log)',
                    showCancelButton: true,
                    confirmButtonText: 'Create',
                    cancelButtonText: 'Cancel',
                    preConfirm: (name) => {
                        if (!name || !name.trim()) {
                            Swal.showValidationMessage('Table name is required');
                            return false;
                        }
                        if (!/^[a-zA-Z0-9_]+$/.test(name)) {
                            Swal.showValidationMessage('Only letters, numbers, and underscores allowed');
                            return false;
                        }
                        return name.trim();
                    }
                });
                if (!tableName) {
                    this.checked = false;
                    return;
                }
                try {
                    const res = await fetch(`${baseUrl}/project/${projectSlug}/misc/init-audit`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ tableName })
                    });
                    const data = await res.json();
                    if (data.success) {
                        pp.dialog.toast('success', data.message);
                        auditTableInput.value = tableName;
                        auditTableInput.disabled = true;
                        if (!currentConfig.advanced) currentConfig.advanced = {};
                        currentConfig.advanced.auditEnabled = true;
                        currentConfig.advanced.auditTable = tableName;
                    } else {
                        pp.dialog.toast('error', data.message);
                        this.checked = false;
                    }
                } catch (err) {
                    pp.dialog.toast('error', 'Network error.');
                    this.checked = false;
                }
            } else {
                const tableName = auditTableInput.value.trim() || 'audit_log';
                const { isConfirmed, dismiss } = await Swal.fire({
                    title: 'Disable Audit Trail?',
                    text: 'Do you want to keep the existing audit table or delete it?',
                    icon: 'question',
                    showDenyButton: true,
                    showCancelButton: true,
                    confirmButtonText: 'Keep Table',
                    denyButtonText: 'Delete Table',
                    cancelButtonText: 'Cancel'
                });
                let dropTable = false;
                if (isConfirmed) dropTable = false;
                else if (dismiss === Swal.DismissReason.deny) dropTable = true;
                else {
                    this.checked = true;
                    return;
                }
                try {
                    const res = await fetch(`${baseUrl}/project/${projectSlug}/misc/disable-audit`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ tableName, dropTable })
                    });
                    const data = await res.json();
                    if (data.success) {
                        pp.dialog.toast('success', data.message);
                        auditTableInput.disabled = false;
                        currentConfig.advanced.auditEnabled = false;
                        currentConfig.advanced.auditTable = tableName;
                    } else {
                        pp.dialog.toast('error', data.message);
                        this.checked = true;
                    }
                } catch (err) {
                    pp.dialog.toast('error', 'Network error.');
                    this.checked = true;
                }
            }
            saveSection('advanced');
        });
    }

    // ── Record Locking Toggle ──────────────────────────────────────────
    const lockingCheckbox = document.getElementById('advLocking');
    const lockTableInput = document.getElementById('advLockTable');
    if (lockingCheckbox) {
        lockingCheckbox.addEventListener('change', async function () {
            const isEnabling = this.checked;
            if (isEnabling) {
                const { value: tableName } = await Swal.fire({
                    title: 'Record Locking Table Name',
                    input: 'text',
                    inputValue: lockTableInput.value.trim() || 'record_locks',
                    inputPlaceholder: 'Enter table name (e.g., record_locks)',
                    showCancelButton: true,
                    confirmButtonText: 'Create',
                    cancelButtonText: 'Cancel',
                    preConfirm: (name) => {
                        if (!name || !name.trim()) {
                            Swal.showValidationMessage('Table name is required');
                            return false;
                        }
                        if (!/^[a-zA-Z0-9_]+$/.test(name)) {
                            Swal.showValidationMessage('Only letters, numbers, and underscores allowed');
                            return false;
                        }
                        return name.trim();
                    }
                });
                if (!tableName) {
                    this.checked = false;
                    return;
                }
                try {
                    const res = await fetch(`${baseUrl}/project/${projectSlug}/misc/init-locking`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ tableName })
                    });
                    const data = await res.json();
                    if (data.success) {
                        pp.dialog.toast('success', data.message);
                        lockTableInput.value = tableName;
                        lockTableInput.disabled = true;
                        if (!currentConfig.advanced) currentConfig.advanced = {};
                        currentConfig.advanced.recordLocking = true;
                        currentConfig.advanced.lockTable = tableName;
                    } else {
                        pp.dialog.toast('error', data.message);
                        this.checked = false;
                    }
                } catch (err) {
                    pp.dialog.toast('error', 'Network error.');
                    this.checked = false;
                }
            } else {
                const tableName = lockTableInput.value.trim() || 'record_locks';
                const { isConfirmed, dismiss } = await Swal.fire({
                    title: 'Disable Record Locking?',
                    text: 'Do you want to keep the existing locking table or delete it?',
                    icon: 'question',
                    showDenyButton: true,
                    showCancelButton: true,
                    confirmButtonText: 'Keep Table',
                    denyButtonText: 'Delete Table',
                    cancelButtonText: 'Cancel'
                });
                let dropTable = false;
                if (isConfirmed) dropTable = false;
                else if (dismiss === Swal.DismissReason.deny) dropTable = true;
                else {
                    this.checked = true;
                    return;
                }
                try {
                    const res = await fetch(`${baseUrl}/project/${projectSlug}/misc/disable-locking`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ tableName, dropTable })
                    });
                    const data = await res.json();
                    if (data.success) {
                        pp.dialog.toast('success', data.message);
                        lockTableInput.disabled = false;
                        currentConfig.advanced.recordLocking = false;
                        currentConfig.advanced.lockTable = tableName;
                    } else {
                        pp.dialog.toast('error', data.message);
                        this.checked = true;
                    }
                } catch (err) {
                    pp.dialog.toast('error', 'Network error.');
                    this.checked = true;
                }
            }
            saveSection('advanced');
        });
    }

    // ── Notifications Toggle (single checkbox) ──────────────────────────
    const notifCheckbox = document.getElementById('notifEnableCheck');
    const notifTableInput = document.getElementById('notifTableName');
    const notifFieldsDiv = document.getElementById('notifFields');
    if (notifCheckbox) {
        notifCheckbox.addEventListener('change', async function () {
            const isEnabling = this.checked;
            if (isEnabling) {
                const { value: tableName } = await Swal.fire({
                    title: 'Notifications Table Name',
                    input: 'text',
                    inputValue: notifTableInput.value.trim() || 'notifications',
                    inputPlaceholder: 'Enter table name (e.g., notifications)',
                    showCancelButton: true,
                    confirmButtonText: 'Create',
                    cancelButtonText: 'Cancel',
                    preConfirm: (name) => {
                        if (!name || !name.trim()) {
                            Swal.showValidationMessage('Table name is required');
                            return false;
                        }
                        if (!/^[a-zA-Z0-9_]+$/.test(name)) {
                            Swal.showValidationMessage('Only letters, numbers, and underscores allowed');
                            return false;
                        }
                        return name.trim();
                    }
                });
                if (!tableName) {
                    this.checked = false;
                    return;
                }
                try {
                    const res = await fetch(`${baseUrl}/project/${projectSlug}/misc/init-notif`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ tableName })
                    });
                    const data = await res.json();
                    if (data.success) {
                        pp.dialog.toast('success', data.message);
                        notifTableInput.value = tableName;
                        notifTableInput.disabled = true;
                        if (notifFieldsDiv) notifFieldsDiv.style.display = 'block';
                        if (!currentConfig.advanced) currentConfig.advanced = {};
                        currentConfig.advanced.notifEnabled = true;
                        currentConfig.advanced.notifTableName = tableName;
                    } else {
                        pp.dialog.toast('error', data.message);
                        this.checked = false;
                    }
                } catch (err) {
                    pp.dialog.toast('error', 'Network error.');
                    this.checked = false;
                }
            } else {
                const tableName = notifTableInput.value.trim() || 'notifications';
                const { isConfirmed, dismiss } = await Swal.fire({
                    title: 'Disable Notifications?',
                    text: 'Do you want to keep the existing notifications table or delete it?',
                    icon: 'question',
                    showDenyButton: true,
                    showCancelButton: true,
                    confirmButtonText: 'Keep Table',
                    denyButtonText: 'Delete Table',
                    cancelButtonText: 'Cancel'
                });
                let dropTable = false;
                if (isConfirmed) dropTable = false;
                else if (dismiss === Swal.DismissReason.deny) dropTable = true;
                else {
                    this.checked = true;
                    return;
                }
                try {
                    const res = await fetch(`${baseUrl}/project/${projectSlug}/misc/disable-notif`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ tableName, dropTable })
                    });
                    const data = await res.json();
                    if (data.success) {
                        pp.dialog.toast('success', data.message);
                        notifTableInput.disabled = false;
                        if (notifFieldsDiv) notifFieldsDiv.style.display = 'none';
                        currentConfig.advanced.notifEnabled = false;
                        currentConfig.advanced.notifTableName = tableName;
                    } else {
                        pp.dialog.toast('error', data.message);
                        this.checked = true;
                    }
                } catch (err) {
                    pp.dialog.toast('error', 'Network error.');
                    this.checked = true;
                }
            }
            saveSection('advanced');
        });
    }
});