// Chart.js functionality for Cyber Invest platform
$(document).ready(function() {

    // Initialize charts when Chart.js is loaded
    if (typeof Chart !== 'undefined') {
        initializeCharts();
    }

    // Initialize all charts on the page
    function initializeCharts() {
        // Investment growth chart
        if ($('#investment-growth-chart').length) {
            loadInvestmentGrowthChart();
        }

        // Profit distribution chart
        if ($('#profit-distribution-chart').length) {
            loadProfitDistributionChart();
        }

        // User registration chart
        if ($('#user-registration-chart').length) {
            loadUserRegistrationChart();
        }

        // Transaction volume chart
        if ($('#transaction-volume-chart').length) {
            loadTransactionVolumeChart();
        }

        // Investment plans popularity chart
        if ($('#plans-popularity-chart').length) {
            loadPlansPopularityChart();
        }

        // Revenue chart
        if ($('#revenue-chart').length) {
            loadRevenueChart();
        }

        // User balance distribution
        if ($('#balance-distribution-chart').length) {
            loadBalanceDistributionChart();
        }

        // Country distribution chart
        if ($('#country-distribution-chart').length) {
            loadCountryDistributionChart();
        }
    }

    // Investment Growth Chart
    function loadInvestmentGrowthChart() {
        $.ajax({
            url: 'api/get-investment-growth.php',
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    const ctx = document.getElementById('investment-growth-chart').getContext('2d');
                    new Chart(ctx, {
                        type: 'line',
                        data: {
                            labels: response.labels,
                            datasets: [{
                                label: 'Total Investments',
                                data: response.investments,
                                borderColor: 'rgb(59, 130, 246)',
                                backgroundColor: 'rgba(59, 130, 246, 0.1)',
                                tension: 0.4,
                                fill: true
                            }, {
                                label: 'Active Investments',
                                data: response.active_investments,
                                borderColor: 'rgb(16, 185, 129)',
                                backgroundColor: 'rgba(16, 185, 129, 0.1)',
                                tension: 0.4,
                                fill: true
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    position: 'top',
                                },
                                title: {
                                    display: true,
                                    text: 'Investment Growth Over Time'
                                }
                            },
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    ticks: {
                                        callback: function(value) {
                                            return '$' + value.toLocaleString();
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            }
        });
    }

    // Profit Distribution Chart
    function loadProfitDistributionChart() {
        $.ajax({
            url: 'api/get-profit-distribution.php',
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    const ctx = document.getElementById('profit-distribution-chart').getContext('2d');
                    new Chart(ctx, {
                        type: 'doughnut',
                        data: {
                            labels: response.labels,
                            datasets: [{
                                data: response.data,
                                backgroundColor: [
                                    'rgb(59, 130, 246)',
                                    'rgb(16, 185, 129)',
                                    'rgb(245, 158, 11)',
                                    'rgb(239, 68, 68)',
                                    'rgb(139, 92, 246)',
                                    'rgb(236, 72, 153)'
                                ],
                                borderWidth: 2
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    position: 'right',
                                },
                                title: {
                                    display: true,
                                    text: 'Profit Distribution by Plan'
                                },
                                tooltip: {
                                    callbacks: {
                                        label: function(context) {
                                            const label = context.label || '';
                                            const value = context.parsed || 0;
                                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                            const percentage = ((value / total) * 100).toFixed(1);
                                            return label + ': $' + value.toLocaleString() + ' (' + percentage + '%)';
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            }
        });
    }

    // User Registration Chart
    function loadUserRegistrationChart() {
        $.ajax({
            url: 'api/get-user-registrations.php',
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    const ctx = document.getElementById('user-registration-chart').getContext('2d');
                    new Chart(ctx, {
                        type: 'bar',
                        data: {
                            labels: response.labels,
                            datasets: [{
                                label: 'New Registrations',
                                data: response.registrations,
                                backgroundColor: 'rgba(59, 130, 246, 0.8)',
                                borderColor: 'rgb(59, 130, 246)',
                                borderWidth: 1
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    position: 'top',
                                },
                                title: {
                                    display: true,
                                    text: 'User Registrations Over Time'
                                }
                            },
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    ticks: {
                                        stepSize: 1
                                    }
                                }
                            }
                        }
                    });
                }
            }
        });
    }

    // Transaction Volume Chart
    function loadTransactionVolumeChart() {
        $.ajax({
            url: 'api/get-transaction-volume.php',
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    const ctx = document.getElementById('transaction-volume-chart').getContext('2d');
                    new Chart(ctx, {
                        type: 'line',
                        data: {
                            labels: response.labels,
                            datasets: [{
                                label: 'Deposits',
                                data: response.deposits,
                                borderColor: 'rgb(16, 185, 129)',
                                backgroundColor: 'rgba(16, 185, 129, 0.1)',
                                tension: 0.4
                            }, {
                                label: 'Withdrawals',
                                data: response.withdrawals,
                                borderColor: 'rgb(239, 68, 68)',
                                backgroundColor: 'rgba(239, 68, 68, 0.1)',
                                tension: 0.4
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    position: 'top',
                                },
                                title: {
                                    display: true,
                                    text: 'Transaction Volume'
                                }
                            },
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    ticks: {
                                        callback: function(value) {
                                            return '$' + value.toLocaleString();
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            }
        });
    }

    // Investment Plans Popularity Chart
    function loadPlansPopularityChart() {
        $.ajax({
            url: 'api/get-plans-popularity.php',
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    const ctx = document.getElementById('plans-popularity-chart').getContext('2d');
                    new Chart(ctx, {
                        type: 'horizontalBar',
                        data: {
                            labels: response.labels,
                            datasets: [{
                                label: 'Active Investments',
                                data: response.data,
                                backgroundColor: 'rgba(139, 92, 246, 0.8)',
                                borderColor: 'rgb(139, 92, 246)',
                                borderWidth: 1
                            }]
                        },
                        options: {
                            indexAxis: 'y',
                            responsive: true,
                            plugins: {
                                legend: {
                                    position: 'top',
                                },
                                title: {
                                    display: true,
                                    text: 'Investment Plans Popularity'
                                }
                            },
                            scales: {
                                x: {
                                    beginAtZero: true,
                                    ticks: {
                                        stepSize: 1
                                    }
                                }
                            }
                        }
                    });
                }
            }
        });
    }

    // Revenue Chart
    function loadRevenueChart() {
        $.ajax({
            url: 'api/get-revenue-data.php',
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    const ctx = document.getElementById('revenue-chart').getContext('2d');
                    new Chart(ctx, {
                        type: 'line',
                        data: {
                            labels: response.labels,
                            datasets: [{
                                label: 'Revenue',
                                data: response.revenue,
                                borderColor: 'rgb(245, 158, 11)',
                                backgroundColor: 'rgba(245, 158, 11, 0.1)',
                                tension: 0.4,
                                fill: true
                            }, {
                                label: 'Profit',
                                data: response.profit,
                                borderColor: 'rgb(16, 185, 129)',
                                backgroundColor: 'rgba(16, 185, 129, 0.1)',
                                tension: 0.4,
                                fill: true
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    position: 'top',
                                },
                                title: {
                                    display: true,
                                    text: 'Revenue & Profit Trends'
                                }
                            },
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    ticks: {
                                        callback: function(value) {
                                            return '$' + value.toLocaleString();
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            }
        });
    }

    // User Balance Distribution
    function loadBalanceDistributionChart() {
        $.ajax({
            url: 'api/get-balance-distribution.php',
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    const ctx = document.getElementById('balance-distribution-chart').getContext('2d');
                    new Chart(ctx, {
                        type: 'bar',
                        data: {
                            labels: response.labels,
                            datasets: [{
                                label: 'Number of Users',
                                data: response.data,
                                backgroundColor: 'rgba(236, 72, 153, 0.8)',
                                borderColor: 'rgb(236, 72, 153)',
                                borderWidth: 1
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    position: 'top',
                                },
                                title: {
                                    display: true,
                                    text: 'User Balance Distribution'
                                }
                            },
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    ticks: {
                                        stepSize: 1
                                    }
                                }
                            }
                        }
                    });
                }
            }
        });
    }

    // Country Distribution Chart
    function loadCountryDistributionChart() {
        $.ajax({
            url: 'api/get-country-distribution.php',
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    const ctx = document.getElementById('country-distribution-chart').getContext('2d');
                    new Chart(ctx, {
                        type: 'pie',
                        data: {
                            labels: response.labels,
                            datasets: [{
                                data: response.data,
                                backgroundColor: [
                                    'rgb(59, 130, 246)',
                                    'rgb(16, 185, 129)',
                                    'rgb(245, 158, 11)',
                                    'rgb(239, 68, 68)',
                                    'rgb(139, 92, 246)',
                                    'rgb(236, 72, 153)',
                                    'rgb(6, 182, 212)',
                                    'rgb(34, 197, 94)',
                                    'rgb(251, 146, 60)',
                                    'rgb(244, 63, 94)'
                                ],
                                borderWidth: 2
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    position: 'right',
                                },
                                title: {
                                    display: true,
                                    text: 'User Distribution by Country'
                                }
                            }
                        }
                    });
                }
            }
        });
    }

    // Utility function to format currency
    function formatCurrency(amount) {
        return '$' + parseFloat(amount).toLocaleString('en-US', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        });
    }

    // Utility function to format numbers
    function formatNumber(num) {
        return parseInt(num).toLocaleString();
    }

    // Export chart as image
    $('.export-chart').on('click', function() {
        const canvas = $(this).siblings('canvas')[0];
        const link = document.createElement('a');
        link.download = $(this).data('filename') || 'chart.png';
        link.href = canvas.toDataURL();
        link.click();
    });

    // Refresh chart data
    $('.refresh-chart').on('click', function() {
        const chartId = $(this).data('chart');
        const chartFunction = 'load' + chartId.charAt(0).toUpperCase() + chartId.slice(1) + 'Chart';
        if (typeof window[chartFunction] === 'function') {
            window[chartFunction]();
        }
    });

    console.log('Chart.js functionality loaded successfully');
});