/* Seven Digital — Web Push client.
   Usage: include this script, then call sdEnablePush() from a button.
   The app base path is derived from this script's own URL (…/assets/push.js → app root). */
(function () {
    var me = document.currentScript ? document.currentScript.src : '';
    var BASE = me ? new URL('../', me).pathname : '/';            // e.g. /seven-credit-system/
    var VAPID_PUBLIC = 'BKq9Z5pac_iEehZd3aWwsNWVzKozJd2SH8ZUNv28AaW9BIt4hmiAwdKQmoPZhgntV-V8IHwa8SsKI0JiHdOSk4k';

    function b64ToUint8(base64) {
        var pad = '='.repeat((4 - base64.length % 4) % 4);
        var b = (base64 + pad).replace(/-/g, '+').replace(/_/g, '/');
        var raw = atob(b), arr = new Uint8Array(raw.length);
        for (var i = 0; i < raw.length; i++) arr[i] = raw.charCodeAt(i);
        return arr;
    }

    window.sdPushSupported = function () {
        return ('serviceWorker' in navigator) && ('PushManager' in window) && ('Notification' in window);
    };

    window.sdEnablePush = async function () {
        if (!window.sdPushSupported()) {
            alert('This device/browser does not support notifications. On iPhone, add this app to your Home Screen first.');
            return false;
        }
        try {
            var perm = await Notification.requestPermission();
            if (perm !== 'granted') { alert('Notifications were not allowed.'); return false; }

            var reg = await navigator.serviceWorker.register(BASE + 'sw.js', { scope: BASE });
            await navigator.serviceWorker.ready;

            var sub = await reg.pushManager.getSubscription();
            if (!sub) {
                sub = await reg.pushManager.subscribe({
                    userVisibleOnly: true,
                    applicationServerKey: b64ToUint8(VAPID_PUBLIC)
                });
            }
            var j = sub.toJSON();
            var res = await fetch(BASE + 'push_subscribe.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'subscribe',
                    endpoint: sub.endpoint,
                    p256dh: j.keys && j.keys.p256dh,
                    auth: j.keys && j.keys.auth
                })
            });
            var d = await res.json();
            if (d && d.ok) { alert('🔔 Notifications enabled on this phone.'); return true; }
            alert('Could not save the subscription. Please try again.');
            return false;
        } catch (e) {
            alert('Could not enable notifications: ' + e.message);
            return false;
        }
    };

    /* set the app-icon badge to the server's unread count */
    window.sdUpdateBadge = async function () {
        if (!('setAppBadge' in navigator)) return;
        try {
            var res = await fetch(BASE + 'notif_badge.php', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: 'count' })
            });
            var d = await res.json();
            if (d && d.count > 0) navigator.setAppBadge(d.count).catch(function(){});
            else navigator.clearAppBadge().catch(function(){});
        } catch (e) {}
    };

    /* clear the badge (mark everything seen) — called when the app is opened */
    window.sdClearBadge = async function () {
        try {
            await fetch(BASE + 'notif_badge.php', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: 'seen' })
            });
        } catch (e) {}
        if ('clearAppBadge' in navigator) navigator.clearAppBadge().catch(function(){});
    };

    /* opening the app clears the icon count */
    if ('clearAppBadge' in navigator) {
        window.addEventListener('load', function () { window.sdClearBadge(); });
    }

    window.sdTestPush = async function () {
        try {
            var res = await fetch(BASE + 'push_subscribe.php', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: 'test' })
            });
            var d = await res.json();
            if (d && d.ok) { alert('Test sent (' + (d.sent || 0) + ' device).'); }
            else { alert('Test failed: ' + ((d && d.error) || 'no devices subscribed')); }
        } catch (e) { alert('Test failed: ' + e.message); }
    };
})();