// Dashboard JavaScript Functions

// Safe Chart initialization - wait for DOM
document.addEventListener('DOMContentLoaded', function() {

    // Configure Chart.js defaults
    if (typeof Chart !== 'undefined') {
        Chart.defaults.font.family = "'Cairo', 'Tajawal', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif";
        Chart.defaults.color = '#858796';
    }

    // Legacy Area Chart (myAreaChart - used in older pages)
    var areaCtx = document.getElementById("myAreaChart");
    if (areaCtx && typeof Chart !== 'undefined') {
        new Chart(areaCtx, {
            type: 'line',
            data: {
                labels: ["يناير", "فبراير", "مارس", "أبريل", "مايو", "يونيو",
                         "يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر"],
                datasets: [{
                    label: "التقارير",
                    lineTension: 0.3,
                    backgroundColor: "rgba(13, 110, 253, 0.05)",
                    borderColor: "rgba(13, 110, 253, 1)",
                    pointRadius: 3,
                    pointBackgroundColor: "rgba(13, 110, 253, 1)",
                    pointBorderColor: "rgba(13, 110, 253, 1)",
                    pointHoverRadius: 3,
                    pointHoverBackgroundColor: "rgba(13, 110, 253, 1)",
                    pointHoverBorderColor: "rgba(13, 110, 253, 1)",
                    pointHitRadius: 10,
                    pointBorderWidth: 2,
                    data: [0, 10000, 5000, 15000, 10000, 20000, 15000, 25000, 20000, 30000, 25000, 40000],
                }],
            },
            options: {
                maintainAspectRatio: false,
                layout: { padding: { left: 10, right: 25, top: 25, bottom: 0 } },
                scales: {
                    x: {
                        grid: { display: false, drawBorder: false },
                        ticks: { maxTicksLimit: 7 }
                    },
                    y: {
                        ticks: {
                            maxTicksLimit: 5,
                            padding: 10,
                            callback: function(value) { return number_format(value); }
                        },
                        grid: {
                            color: "rgb(234, 236, 244)",
                            drawBorder: false,
                            borderDash: [2]
                        }
                    }
                },
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: "rgb(255,255,255)",
                        bodyColor: "#858796",
                        titleColor: '#6e707e',
                        borderColor: '#dddfeb',
                        borderWidth: 1,
                        displayColors: false,
                        intersect: false,
                        mode: 'index',
                        callbacks: {
                            label: function(context) {
                                var label = context.dataset.label || '';
                                if (label) label += ': ';
                                if (context.parsed.y !== null) label += number_format(context.parsed.y);
                                return label;
                            }
                        }
                    }
                }
            }
        });
    }

    // Legacy Pie Chart (myPieChart - used in older pages)
    var pieCtx = document.getElementById("myPieChart");
    if (pieCtx && typeof Chart !== 'undefined') {
        new Chart(pieCtx, {
            type: 'doughnut',
            data: {
                labels: ["الطابق السادس", "العناية المركزة", "الطابق الخامس", "غرفة العمليات", "أخرى"],
                datasets: [{
                    data: [55, 30, 15, 10, 5],
                    backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc', '#f6c23e', '#e74a3b'],
                    hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf', '#f4b619', '#e02d1b'],
                    hoverBorderColor: "rgba(234, 236, 244, 1)",
                }],
            },
            options: {
                maintainAspectRatio: false,
                plugins: {
                    tooltip: {
                        backgroundColor: "rgb(255,255,255)",
                        bodyColor: "#858796",
                        borderColor: '#dddfeb',
                        borderWidth: 1,
                        displayColors: false,
                    },
                    legend: { display: false }
                },
                cutout: 80,
            }
        });
    }

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

    // Initialize Bootstrap popovers
    var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
    popoverTriggerList.forEach(function(el) {
        new bootstrap.Popover(el);
    });

    // Add fade-in animation to cards
    var cards = document.querySelectorAll('.card');
    cards.forEach(function(card, index) {
        setTimeout(function() {
            card.classList.add('fade-in');
        }, index * 80);
    });

    // Load chart data from API if charts exist on this page
    if (document.getElementById('myAreaChart') || document.getElementById('myPieChart')) {
        loadChartData();
    }
});

// =============================================
// Number formatting utility
// =============================================
function number_format(number, decimals, dec_point, thousands_sep) {
    number = (number + '').replace(',', '').replace(' ', '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function(n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

// =============================================
// Chart data loading from API
// =============================================
function loadChartData() {
    fetch('api/chart_data.php')
        .then(function(response) { return response.json(); })
        .then(function(data) {
            if (data.monthly) updateAreaChart(data.monthly);
            if (data.units) updatePieChart(data.units);
        })
        .catch(function(error) {
            console.warn('Chart data load failed:', error);
        });
}

function updateAreaChart(data) {
    var chart = Chart.getChart ? Chart.getChart('myAreaChart') : null;
    if (chart) {
        chart.data.labels = data.map(function(item) { return item.month; });
        chart.data.datasets[0].data = data.map(function(item) { return item.count; });
        chart.update();
    }
}

function updatePieChart(data) {
    var chart = Chart.getChart ? Chart.getChart('myPieChart') : null;
    if (chart) {
        chart.data.labels = data.map(function(item) { return item.unit_name; });
        chart.data.datasets[0].data = data.map(function(item) { return item.count; });
        chart.update();
    }
}

// Auto-refresh chart data every 5 minutes
setInterval(loadChartData, 300000);

// =============================================
// Dashboard utility functions
// =============================================
function refreshDashboard() {
    var refreshBtn = document.getElementById('refreshBtn');
    if (refreshBtn) {
        var originalText = refreshBtn.innerHTML;
        refreshBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        refreshBtn.disabled = true;
        setTimeout(function() {
            location.reload();
        }, 500);
    } else {
        location.reload();
    }
}

function searchReports() {
    var searchInput = document.getElementById('searchInput');
    if (!searchInput) return;
    var searchTerm = searchInput.value.toLowerCase();
    var tableRows = document.querySelectorAll('#dataTable tbody tr');
    tableRows.forEach(function(row) {
        row.style.display = row.textContent.toLowerCase().includes(searchTerm) ? '' : 'none';
    });
}

function filterByStatus(status) {
    var tableRows = document.querySelectorAll('#dataTable tbody tr');
    tableRows.forEach(function(row) {
        if (status === 'all') {
            row.style.display = '';
        } else {
            var statusCell = row.querySelector('.badge');
            row.style.display = (statusCell && statusCell.textContent.includes(status)) ? '' : 'none';
        }
    });
}

function showNotification(message, type) {
    type = type || 'info';
    var notification = document.createElement('div');
    notification.className = 'alert alert-' + type + ' alert-dismissible fade show position-fixed';
    notification.style.cssText = 'top: 20px; inset-inline-end: 20px; z-index: 9999; min-width: 300px;';
    notification.innerHTML = message + '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
    document.body.appendChild(notification);
    setTimeout(function() {
        if (notification.parentNode) notification.parentNode.removeChild(notification);
    }, 5000);
}

function confirmDelete(id, type) {
    var msg = (document.documentElement.lang === 'ar')
        ? 'هل أنت متأكد من حذف هذا ' + type + '؟'
        : 'Are you sure you want to delete this ' + type + '?';
    if (confirm(msg)) {
        window.location.href = 'delete.php?id=' + encodeURIComponent(id) + '&type=' + encodeURIComponent(type);
    }
}

function printReport(reportId) {
    window.open('print_report.php?id=' + encodeURIComponent(reportId), '_blank');
}
