/* ============================================================
   FoodFlow Admin — Core JS
   ============================================================ */

'use strict';

// ── Sidebar Toggle ────────────────────────────────────────────
const sidebar  = document.getElementById('sidebar');
const overlay  = document.getElementById('sidebarOverlay');
const toggler  = document.getElementById('sidebarToggler');

if (toggler) {
    toggler.addEventListener('click', () => {
        sidebar?.classList.toggle('open');
        overlay?.classList.toggle('show');
    });
}
if (overlay) {
    overlay.addEventListener('click', () => {
        sidebar?.classList.remove('open');
        overlay?.classList.remove('show');
    });
}

// ── Image Upload Preview ──────────────────────────────────────
document.querySelectorAll('.img-upload-input').forEach(input => {
    input.addEventListener('change', function () {
        const preview = document.getElementById(this.dataset.preview);
        if (!preview) return;

        const file = this.files[0];
        if (!file) return;

        // Client-side size check (max defined in PHP config, mirror here)
        const maxKB = parseInt(document.body.dataset.uploadMaxKb || '2048');
        if (file.size > maxKB * 1024) {
            showToast(`Image too large. Maximum allowed size is ${maxKB} KB.`, 'danger');
            this.value = '';
            return;
        }

        const reader = new FileReader();
        reader.onload = e => { preview.src = e.target.result; };
        reader.readAsDataURL(file);
    });
});

// ── Auto-dismiss alerts ───────────────────────────────────────
document.querySelectorAll('.alert.fade.show').forEach(el => {
    setTimeout(() => {
        const bsAlert = bootstrap.Alert.getOrCreateInstance(el);
        bsAlert?.close();
    }, 5000);
});

// ── Confirm Delete ────────────────────────────────────────────
document.addEventListener('click', e => {
    const btn = e.target.closest('[data-confirm]');
    if (!btn) return;

    const msg = btn.dataset.confirm || 'Are you sure you want to delete this?';
    if (!confirm(msg)) {
        e.preventDefault();
        e.stopImmediatePropagation();
    }
});

// ── Toggle Switch via AJAX ────────────────────────────────────
document.querySelectorAll('.toggle-status').forEach(el => {
    el.addEventListener('change', async function () {
        const url    = this.dataset.url;
        const csrf   = document.querySelector('meta[name="csrf-token"]')?.content;

        try {
            const res  = await fetch(url, {
                method:  'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRF-TOKEN': csrf },
                body:    `_csrf_token=${encodeURIComponent(csrf)}`
            });
            const data = await res.json();

            if (!data.success) {
                this.checked = !this.checked;          // revert
                showToast(data.message || 'Failed to update.', 'danger');
            } else {
                showToast(data.message || 'Updated.', 'success');
            }
        } catch {
            this.checked = !this.checked;
            showToast('Network error. Please try again.', 'danger');
        }
    });
});

// ── Toast Notification ────────────────────────────────────────
function showToast(message, type = 'info') {
    let container = document.getElementById('toastContainer');
    if (!container) {
        container = document.createElement('div');
        container.id = 'toastContainer';
        container.className = 'toast-container position-fixed bottom-0 end-0 p-3';
        container.style.zIndex = '9999';
        document.body.appendChild(container);
    }

    const icon = { success: 'check-circle-fill', danger: 'x-circle-fill', warning: 'exclamation-triangle-fill', info: 'info-circle-fill' }[type] || 'info-circle-fill';

    const toastEl = document.createElement('div');
    toastEl.className = `toast align-items-center text-bg-${type} border-0`;
    toastEl.setAttribute('role', 'alert');
    toastEl.innerHTML = `
        <div class="d-flex">
            <div class="toast-body d-flex align-items-center gap-2">
                <i class="bi bi-${icon}"></i> ${message}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>`;

    container.appendChild(toastEl);
    const toast = new bootstrap.Toast(toastEl, { delay: 4000 });
    toast.show();
    toastEl.addEventListener('hidden.bs.toast', () => toastEl.remove());
}

// Expose globally
window.showToast = showToast;

// ── Order Alert Polling ───────────────────────────────────────
(function orderAlertPoller() {
    const bell        = document.getElementById('orderBell');
    const badge       = document.getElementById('orderBellBadge');
    const sidebarBadge = document.getElementById('sidebarOrderBadge');
    if (!bell) return;

    let lastCount = 0;

    function playAlert() {
        try {
            const ctx = new (window.AudioContext || window.webkitAudioContext)();
            [0, 0.22, 0.44].forEach(t => {
                const osc = ctx.createOscillator();
                const g   = ctx.createGain();
                osc.connect(g); g.connect(ctx.destination);
                osc.frequency.value = 880;
                g.gain.setValueAtTime(0.5, ctx.currentTime + t);
                g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + t + 0.2);
                osc.start(ctx.currentTime + t);
                osc.stop(ctx.currentTime + t + 0.2);
            });
        } catch(e) {}
    }

    async function poll() {
        try {
            const res   = await fetch('/abc/food_delivery/public/orders/pending-count');
            const data  = await res.json();
            const count = data.count ?? 0;

            if (badge)       badge.textContent       = count > 99 ? '99+' : count;
            if (sidebarBadge) sidebarBadge.textContent = count > 0 ? count : '';

            if (count > 0) {
                bell.classList.add('has-orders');
                if (count > lastCount) {
                    playAlert();
                    showToast(`New order received! (${count} pending)`, 'warning');
                }
            } else {
                bell.classList.remove('has-orders');
            }

            lastCount = count;
        } catch { /* silently fail */ }
    }

    poll();
    setInterval(poll, 30000); // every 30 seconds
})();

// ── DataTable Enhancement (if table has .fd-table class) ──────
document.querySelectorAll('.fd-table').forEach(table => {
    // Simple client-side search
    const searchId = table.dataset.search;
    const searchEl = searchId ? document.getElementById(searchId) : null;

    if (searchEl) {
        searchEl.addEventListener('input', function () {
            const q    = this.value.toLowerCase();
            const rows = table.querySelectorAll('tbody tr');
            rows.forEach(row => {
                row.style.display = row.textContent.toLowerCase().includes(q) ? '' : 'none';
            });
        });
    }
});

// ── Form Loading State ────────────────────────────────────────
document.querySelectorAll('form.fd-form').forEach(form => {
    form.addEventListener('submit', function () {
        const btn = this.querySelector('[type="submit"]');
        if (btn) {
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Please wait…';
        }
    });
});
