<?php
// pages/dashboard.php
require_once __DIR__ . '/../config/auth_check.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - AdMob Analytics</title>
    <link rel="stylesheet" href="/assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
    <?php include __DIR__ . '/../includes/sidebar.php'; ?>
    
    <div class="main-content">
        <?php include __DIR__ . '/../includes/header.php'; ?>
        
        <div class="content-wrapper">
            <div class="page-header">
                <h1>Dashboard</h1>
                <div class="page-actions">
                    <button class="btn btn-primary" onclick="refreshDashboard()">
                        <i class="fas fa-sync-alt"></i> Refresh
                    </button>
                </div>
            </div>

            <!-- Quick Stats -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon" style="background: #4CAF50;">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                    <div class="stat-content">
                        <h3 id="total-earnings">Loading...</h3>
                        <p>Total Earnings (Today)</p>
                        <span class="stat-change positive" id="earnings-change">--</span>
                    </div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon" style="background: #2196F3;">
                        <i class="fas fa-eye"></i>
                    </div>
                    <div class="stat-content">
                        <h3 id="total-impressions">Loading...</h3>
                        <p>Total Impressions</p>
                        <span class="stat-change" id="impressions-change">--</span>
                    </div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon" style="background: #FF9800;">
                        <i class="fas fa-mouse-pointer"></i>
                    </div>
                    <div class="stat-content">
                        <h3 id="total-clicks">Loading...</h3>
                        <p>Total Clicks</p>
                        <span class="stat-change" id="clicks-change">--</span>
                    </div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon" style="background: #9C27B0;">
                        <i class="fas fa-percentage"></i>
                    </div>
                    <div class="stat-content">
                        <h3 id="avg-ctr">Loading...</h3>
                        <p>Average CTR</p>
                        <span class="stat-change" id="ctr-change">--</span>
                    </div>
                </div>
            </div>

            <!-- Charts Row -->
            <div class="dashboard-row">
                <div class="card" style="flex: 2;">
                    <div class="card-header">
                        <h2>Earnings Trend</h2>
                        <select id="earnings-period" onchange="updateEarningsChart()">
                            <option value="7">Last 7 Days</option>
                            <option value="14">Last 14 Days</option>
                            <option value="30" selected>Last 30 Days</option>
                        </select>
                    </div>
                    <div class="card-body">
                        <canvas id="earnings-chart" height="80"></canvas>
                    </div>
                </div>

                <div class="card" style="flex: 1;">
                    <div class="card-header">
                        <h2>Top Performing Apps</h2>
                    </div>
                    <div class="card-body">
                        <div id="top-apps-list" class="top-items-list">
                            <div class="loading-spinner">
                                <i class="fas fa-spinner fa-spin"></i> Loading...
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Performance Table -->
            <div class="card">
                <div class="card-header">
                    <h2>Recent Performance</h2>
                    <div class="card-actions">
                        <button class="btn btn-sm btn-secondary" onclick="exportDashboardData()">
                            <i class="fas fa-download"></i> Export
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Impressions</th>
                                    <th>Clicks</th>
                                    <th>CTR</th>
                                    <th>Earnings</th>
                                    <th>eCPM</th>
                                </tr>
                            </thead>
                            <tbody id="performance-table-body">
                                <tr>
                                    <td colspan="6" class="text-center">
                                        <i class="fas fa-spinner fa-spin"></i> Loading...
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    <script>
        let earningsChart = null;

        // Initialize Dashboard
        document.addEventListener('DOMContentLoaded', function() {
            loadDashboardData();
            initEarningsChart();
        });

        // Load Dashboard Data
        async function loadDashboardData() {
            try {
                const response = await fetch('/api/reports.php?action=dashboard&period=today');
                const data = await response.json();

                if (data.success) {
                    updateQuickStats(data.data.stats);
                    updatePerformanceTable(data.data.daily);
                    updateTopApps(data.data.top_apps);
                }
            } catch (error) {
                console.error('Error loading dashboard:', error);
                showNotification('Failed to load dashboard data', 'error');
            }
        }

        // Update Quick Stats
        function updateQuickStats(stats) {
            document.getElementById('total-earnings').textContent = '$' + (stats.earnings || 0).toFixed(2);
            document.getElementById('total-impressions').textContent = formatNumber(stats.impressions || 0);
            document.getElementById('total-clicks').textContent = formatNumber(stats.clicks || 0);
            document.getElementById('avg-ctr').textContent = (stats.ctr || 0).toFixed(2) + '%';

            // Update change indicators
            updateChangeIndicator('earnings-change', stats.earnings_change || 0);
            updateChangeIndicator('impressions-change', stats.impressions_change || 0);
            updateChangeIndicator('clicks-change', stats.clicks_change || 0);
            updateChangeIndicator('ctr-change', stats.ctr_change || 0);
        }

        // Update Change Indicator
        function updateChangeIndicator(elementId, change) {
            const element = document.getElementById(elementId);
            const isPositive = change >= 0;
            
            element.textContent = (isPositive ? '+' : '') + change.toFixed(1) + '%';
            element.className = 'stat-change ' + (isPositive ? 'positive' : 'negative');
        }

        // Update Performance Table
        function updatePerformanceTable(dailyData) {
            const tbody = document.getElementById('performance-table-body');
            
            if (!dailyData || dailyData.length === 0) {
                tbody.innerHTML = '<tr><td colspan="6" class="text-center">No data available</td></tr>';
                return;
            }

            tbody.innerHTML = dailyData.map(row => `
                <tr>
                    <td>${formatDate(row.date)}</td>
                    <td>${formatNumber(row.impressions)}</td>
                    <td>${formatNumber(row.clicks)}</td>
                    <td>${(row.ctr || 0).toFixed(2)}%</td>
                    <td>$${(row.earnings || 0).toFixed(2)}</td>
                    <td>$${(row.ecpm || 0).toFixed(2)}</td>
                </tr>
            `).join('');
        }

        // Update Top Apps
        function updateTopApps(apps) {
            const container = document.getElementById('top-apps-list');
            
            if (!apps || apps.length === 0) {
                container.innerHTML = '<p class="text-center text-muted">No data available</p>';
                return;
            }

            container.innerHTML = apps.slice(0, 5).map((app, index) => `
                <div class="top-item">
                    <div class="top-item-rank">${index + 1}</div>
                    <div class="top-item-info">
                        <div class="top-item-name">${app.app_name}</div>
                        <div class="top-item-value">$${(app.earnings || 0).toFixed(2)}</div>
                    </div>
                </div>
            `).join('');
        }

        // Initialize Earnings Chart
        function initEarningsChart() {
            const ctx = document.getElementById('earnings-chart').getContext('2d');
            
            earningsChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'Earnings',
                        data: [],
                        borderColor: '#4CAF50',
                        backgroundColor: 'rgba(76, 175, 80, 0.1)',
                        tension: 0.4,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function(value) {
                                    return '$' + value;
                                }
                            }
                        }
                    }
                }
            });

            updateEarningsChart();
        }

        // Update Earnings Chart
        async function updateEarningsChart() {
            const period = document.getElementById('earnings-period').value;
            
            try {
                const response = await fetch(`/api/reports.php?action=earnings_trend&period=${period}`);
                const data = await response.json();

                if (data.success && earningsChart) {
                    earningsChart.data.labels = data.data.labels;
                    earningsChart.data.datasets[0].data = data.data.values;
                    earningsChart.update();
                }
            } catch (error) {
                console.error('Error updating chart:', error);
            }
        }

        // Refresh Dashboard
        function refreshDashboard() {
            loadDashboardData();
            updateEarningsChart();
            showNotification('Dashboard refreshed', 'success');
        }

        // Export Dashboard Data
        function exportDashboardData() {
            window.location.href = '/api/reports.php?action=export&format=csv&type=dashboard';
        }

        // Utility Functions
        function formatNumber(num) {
            if (num >= 1000000) return (num / 1000000).toFixed(2) + 'M';
            if (num >= 1000) return (num / 1000).toFixed(2) + 'K';
            return num.toString();
        }

        function formatDate(dateStr) {
            const date = new Date(dateStr);
            return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
        }

        function showNotification(message, type) {
            // Simple notification (you can enhance this)
            alert(message);
        }
    </script>
</body>
</html>