/**
 * i-BOK 5 - Własne skrypty
 */

// Chart.js — dostosuj kolory do dark mode
(function() {
    if (typeof Chart === 'undefined') return;
    var isDark = document.body.classList.contains('dark-mode');
    var textColor = isDark ? '#f1f5f9' : '#666';
    var gridColor = isDark ? 'rgba(255,255,255,0.15)' : 'rgba(0,0,0,0.1)';

    Chart.defaults.color = textColor;
    Chart.defaults.borderColor = gridColor;
    if (Chart.defaults.plugins && Chart.defaults.plugins.legend) {
        Chart.defaults.plugins.legend.labels.color = textColor;
    }
    if (Chart.defaults.plugins && Chart.defaults.plugins.tooltip) {
        Chart.defaults.plugins.tooltip.titleColor = '#fff';
        Chart.defaults.plugins.tooltip.bodyColor = '#fff';
    }
    if (Chart.defaults.scale) {
        Chart.defaults.scale.ticks.color = textColor;
        Chart.defaults.scale.grid.color = gridColor;
    }
})();

$(document).ready(function() {
    // Plugin sortowania IP dla DataTables (punkt 17 - sortuj numerycznie po oktetach)
    if ($.fn.DataTable) {
        $.fn.dataTable.ext.type.order['ip-address-pre'] = function(data) {
            if (!data || data === '-') return -1;
            var clean = String(data).replace(/<[^>]*>/g, '').trim().split('/')[0];
            var parts = clean.split('.');
            if (parts.length !== 4) return 0;
            return (parseInt(parts[0], 10) * 16777216) +
                   (parseInt(parts[1], 10) * 65536) +
                   (parseInt(parts[2], 10) * 256) +
                   (parseInt(parts[3], 10));
        };

        // Auto-detect kolumn z IP (monospace + format x.x.x.x)
        $.fn.dataTable.ext.type.detect.unshift(function(data) {
            if (data === null || data === '' || data === '-') return 'ip-address';
            var clean = String(data).replace(/<[^>]*>/g, '').trim();
            if (!clean) return 'ip-address';
            if (/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(\/\d{1,2})?$/.test(clean)) {
                return 'ip-address';
            }
            return null;
        });
    }

    // Inicjalizacja DataTables (polskie i18n)
    if ($.fn.DataTable) {
        var langPl = {
            "decimal": ",",
            "emptyTable": "Brak danych",
            "info": "Pozycje od _START_ do _END_ z _TOTAL_ łącznie",
            "infoEmpty": "Pozycji 0 z 0",
            "infoFiltered": "(filtrowane z _MAX_ pozycji)",
            "lengthMenu": "Pokaż _MENU_ pozycji",
            "loadingRecords": "Wczytywanie...",
            "processing": "Przetwarzanie...",
            "search": "Szukaj:",
            "zeroRecords": "Nie znaleziono pasujących pozycji",
            "paginate": {
                "first": "Pierwsza",
                "last": "Ostatnia",
                "next": "Następna",
                "previous": "Poprzednia"
            }
        };

        var langEn = {
            "decimal": ".",
            "emptyTable": "No data available",
            "info": "Showing _START_ to _END_ of _TOTAL_ entries",
            "infoEmpty": "Showing 0 to 0 of 0 entries",
            "infoFiltered": "(filtered from _MAX_ total entries)",
            "lengthMenu": "Show _MENU_ entries",
            "loadingRecords": "Loading...",
            "processing": "Processing...",
            "search": "Search:",
            "zeroRecords": "No matching records found",
            "paginate": {
                "first": "First",
                "last": "Last",
                "next": "Next",
                "previous": "Previous"
            }
        };

        // Wybierz język na podstawie cookie lub html lang
        var currentLang = document.documentElement.lang || 'pl';
        var dtLang = currentLang === 'en' ? langEn : langPl;

        // URL search parameter — auto-filter DataTables
        var urlSearch = '';
        try {
            var sp = new URLSearchParams(window.location.search);
            urlSearch = (sp.get('search') || '').trim();
        } catch(e) {}

        // Inicjalizuj wszystkie tabele z klasą .ibok-table
        $('.ibok-table').each(function() {
            if (!$.fn.DataTable.isDataTable(this)) {
                var dt = $(this).DataTable({
                    language: dtLang,
                    pageLength: 25,
                    order: [],
                    responsive: true,
                    dom: '<"row"<"col-sm-6"l><"col-sm-6"f>>rtip'
                });
                if (urlSearch) {
                    dt.search(urlSearch).draw();
                    // Fill the search input so user sees the filter
                    $(this).closest('.dataTables_wrapper').find('input[type="search"]').val(urlSearch);
                }
            }
        });

        // Tabele z domyślnym sortowaniem po dacie (malejąco)
        $('.ibok-table-date-desc').each(function() {
            if (!$.fn.DataTable.isDataTable(this)) {
                var dt = $(this).DataTable({
                    language: dtLang,
                    pageLength: 25,
                    order: [[0, 'desc']],
                    responsive: true,
                    dom: '<"row"<"col-sm-6"l><"col-sm-6"f>>rtip'
                });
                if (urlSearch) {
                    dt.search(urlSearch).draw();
                    $(this).closest('.dataTables_wrapper').find('input[type="search"]').val(urlSearch);
                }
            }
        });
    }

    // Tooltip Bootstrap
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function(el) {
        return new bootstrap.Tooltip(el);
    });

    // Dark mode - aktualizuj ikonę przy starcie
    var icon = document.getElementById('darkModeIcon');
    if (icon) {
        if (document.body.classList.contains('dark-mode')) {
            icon.className = 'bi bi-sun-fill';
        }
    }

    // Dark mode toggle - event listener (CSP-safe, zamiast onclick)
    var darkToggle = document.getElementById('darkModeToggle');
    if (darkToggle) {
        darkToggle.addEventListener('click', function(e) {
            e.preventDefault();
            toggleDarkMode();
        });
        // Dostępność: aktywacja klawiszem Spacja (link <a> reaguje natywnie tylko na Enter)
        darkToggle.addEventListener('keydown', function(e) {
            if (e.key === ' ' || e.code === 'Space') {
                e.preventDefault();
                toggleDarkMode();
            }
        });
    }
});

// Dark mode - ładowanie z localStorage (IIFE, bez jQuery - uruchom ASAP)
(function() {
    if (localStorage.getItem('ibok_dark_mode') === '1') {
        document.body.classList.add('dark-mode');
    }
})();

// Auto-logout warning — 2 minuty przed wygaśnięciem sesji
(function() {
    if (typeof window.IBOK_SESSION_TIMEOUT === 'undefined') return;

    var timeout = window.IBOK_SESSION_TIMEOUT;
    var warningBefore = 120; // 2 minuty
    var lastActivity = Date.now();
    var warningShown = false;
    var countdownInterval = null;
    var modal = null;

    function resetTimer() {
        lastActivity = Date.now();
    }

    // Resetuj timer na aktywność użytkownika
    ['click', 'keydown', 'mousemove', 'scroll'].forEach(function(evt) {
        document.addEventListener(evt, resetTimer, { passive: true });
    });

    function checkSession() {
        var elapsed = (Date.now() - lastActivity) / 1000;
        var remaining = timeout - elapsed;

        if (remaining <= 0) {
            // Sesja wygasła — wyloguj
            window.location.href = window.IBOK_LOGOUT_URL || 'index.php?action=logout';
            return;
        }

        if (remaining <= warningBefore && !warningShown) {
            showWarning(Math.floor(remaining));
        }
    }

    function showWarning(seconds) {
        warningShown = true;
        var modalEl = document.getElementById('sessionExpireModal');
        if (!modalEl) return;

        modal = new bootstrap.Modal(modalEl);
        modal.show();

        var countdownEl = document.getElementById('sessionCountdown');
        var remaining = seconds;

        countdownInterval = setInterval(function() {
            remaining--;
            if (countdownEl) {
                var m = Math.floor(remaining / 60);
                var s = remaining % 60;
                countdownEl.textContent = m + ':' + (s < 10 ? '0' : '') + s;
            }
            if (remaining <= 0) {
                clearInterval(countdownInterval);
                window.location.href = window.IBOK_LOGOUT_URL || 'index.php?action=logout';
            }
        }, 1000);

        // Przycisk "Przedłuż"
        var extendBtn = document.getElementById('sessionExtendBtn');
        if (extendBtn) {
            extendBtn.addEventListener('click', function() {
                clearInterval(countdownInterval);
                warningShown = false;
                lastActivity = Date.now();
                if (modal) modal.hide();
                // Ping serwer
                var xhr = new XMLHttpRequest();
                xhr.open('GET', window.IBOK_SESSION_PING_URL || 'session_ping.php', true);
                xhr.send();
            });
        }
    }

    // Sprawdzaj co 10 sekund
    setInterval(checkSession, 10000);
})();

function toggleDarkMode() {
    // Enable transitions only during dark mode switch
    document.body.classList.add('dm-transition');
    document.body.classList.toggle('dark-mode');
    var isDark = document.body.classList.contains('dark-mode');
    localStorage.setItem('ibok_dark_mode', isDark ? '1' : '0');
    var icon = document.getElementById('darkModeIcon');
    if (icon) {
        icon.className = isDark ? 'bi bi-sun-fill' : 'bi bi-moon-fill';
    }
    // Remove transition class after animation completes
    setTimeout(function() {
        document.body.classList.remove('dm-transition');
    }, 350);
    // Aktualizuj kolory Chart.js
    if (typeof Chart !== 'undefined') {
        var textColor = isDark ? '#f1f5f9' : '#666';
        var gridColor = isDark ? 'rgba(255,255,255,0.15)' : 'rgba(0,0,0,0.1)';
        Chart.defaults.color = textColor;
        Chart.defaults.borderColor = gridColor;
        if (Chart.defaults.plugins && Chart.defaults.plugins.legend) {
            Chart.defaults.plugins.legend.labels.color = textColor;
        }
        var borderColor = isDark ? '#2d3748' : '#fff';
        // Przebuduj każdy wykres od zera (chart.update nie odświeża legendy)
        Object.values(Chart.instances).forEach(function(chart) {
            var canvas = chart.canvas;
            var cfg = {
                type: chart.config.type,
                data: JSON.parse(JSON.stringify(chart.data)),
                options: JSON.parse(JSON.stringify(chart.options))
            };
            // Ustaw nowe kolory
            cfg.options.color = textColor;
            if (cfg.options.plugins && cfg.options.plugins.legend && cfg.options.plugins.legend.labels) {
                cfg.options.plugins.legend.labels.color = textColor;
            }
            if (cfg.options.scales) {
                Object.keys(cfg.options.scales).forEach(function(k) {
                    var s = cfg.options.scales[k];
                    if (s.ticks) s.ticks.color = textColor;
                    if (s.grid) s.grid.color = gridColor;
                });
            }
            cfg.data.datasets.forEach(function(ds) {
                if (cfg.type === 'doughnut' || cfg.type === 'pie') {
                    ds.borderColor = borderColor;
                }
            });
            chart.destroy();
            new Chart(canvas, cfg);
        });
    }
}
