<?php
/**
 * Dashboard Page - Main overview with statistics and charts
 */
?>

<!-- Dashboard Stats Cards -->
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-building"></i>
        </div>
        <div class="stat-info">
            <h3><?php echo format_number($stats['tenants']); ?></h3>
            <p>Active Tenants</p>
            <small class="stat-meta">Total: <?php echo format_number($stats['total_tenants']); ?></small>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-mobile-alt"></i>
        </div>
        <div class="stat-info">
            <h3><?php echo format_number($stats['apps']); ?></h3>
            <p>Active Applications</p>
            <small class="stat-meta">Total: <?php echo format_number($stats['total_apps']); ?></small>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-box"></i>
        </div>
        <div class="stat-info">
            <h3><?php echo format_number($stats['items']); ?></h3>
            <p>Content Items</p>
            <small class="stat-meta">Across all tenants</small>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-mouse-pointer"></i>
        </div>
        <div class="stat-info">
            <h3><?php echo format_number($stats['interactions_today']); ?></h3>
            <p>Interactions Today</p>
            <?php if (isset($growth_metrics['interactions'])): ?>
                <small class="stat-meta <?php echo $growth_metrics['interactions'] >= 0 ? 'positive' : 'negative'; ?>">
                    <?php echo $growth_metrics['interactions'] >= 0 ? '+' : ''; ?><?php echo $growth_metrics['interactions']; ?>% vs yesterday
                </small>
            <?php endif; ?>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-magic"></i>
        </div>
        <div class="stat-info">
            <h3><?php echo format_number($stats['recommendations_today']); ?></h3>
            <p>Recommendations Today</p>
            <small class="stat-meta">Served via API</small>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-database"></i>
        </div>
        <div class="stat-info">
            <h3><?php echo $db_stats['dataSize'] ?? 'N/A'; ?></h3>
            <p>Database Size</p>
            <small class="stat-meta">Storage: <?php echo $db_stats['storageSize'] ?? 'N/A'; ?></small>
        </div>
    </div>
</div>

<!-- Charts and Analytics Section -->
<div class="charts-section">
    <div class="charts-grid">
        <!-- Adapter Distribution Chart -->
        <div class="chart-card">
            <div class="chart-header">
                <h3>Adapter Distribution</h3>
                <div class="chart-meta">
                    <span class="chart-count"><?php echo array_sum($adapter_stats); ?> total apps</span>
                </div>
            </div>
            <div class="chart-container">
                <canvas id="adapterChart"></canvas>
            </div>
            <div class="chart-legend">
                <?php foreach ($adapter_stats as $adapter => $count): ?>
                    <div class="legend-item">
                        <?php echo get_adapter_badge($adapter); ?>
                        <span class="legend-count"><?php echo $count; ?></span>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        
        <!-- Interactions Trend Chart -->
        <div class="chart-card">
            <div class="chart-header">
                <h3>User Interactions (Last 7 Days)</h3>
                <div class="chart-actions">
                    <select class="chart-filter" data-chart="interactions">
                        <option value="7">Last 7 days</option>
                        <option value="30">Last 30 days</option>
                        <option value="90">Last 90 days</option>
                    </select>
                </div>
            </div>
            <div class="chart-container">
                <canvas id="interactionsChart"></canvas>
            </div>
        </div>
    </div>
</div>

<!-- Content Overview Section -->
<div class="content-overview">
    <div class="overview-grid">
        <!-- Top Tenants by Activity -->
        <div class="overview-card">
            <div class="card-header">
                <h3>Top Active Tenants</h3>
                <a href="?page=tenants" class="view-all">View All</a>
            </div>
            <div class="tenants-list">
                <?php if (!empty($top_tenants)): ?>
                    <?php foreach ($top_tenants as $tenant): ?>
                        <div class="tenant-item">
                            <div class="tenant-info">
                                <h4><?php echo h($tenant['name']); ?></h4>
                                <p>ID: <?php echo h($tenant['tenant_id']); ?></p>
                            </div>
                            <div class="tenant-stats">
                                <?php echo get_status_badge($tenant['status']); ?>
                                <span class="interaction-count"><?php echo format_number($tenant['interaction_count']); ?> interactions</span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="empty-state">
                        <i class="fas fa-building"></i>
                        <p>No tenants found</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Recent Activity -->
        <div class="overview-card">
            <div class="card-header">
                <h3>Recent Activity</h3>
                <span class="activity-count"><?php echo count($recent_activities); ?> recent</span>
            </div>
            <div class="activity-list">
                <?php if (!empty($recent_activities)): ?>
                    <?php foreach ($recent_activities as $activity): ?>
                        <div class="activity-item">
                            <div class="activity-icon">
                                <i class="<?php echo $activity['icon']; ?>"></i>
                            </div>
                            <div class="activity-content">
                                <p><?php echo h($activity['message']); ?></p>
                                <span class="activity-time"><?php echo time_ago($activity['timestamp']); ?></span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="empty-state">
                        <i class="fas fa-clock"></i>
                        <p>No recent activity</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- System Health -->
        <div class="overview-card">
            <div class="card-header">
                <h3>System Health</h3>
                <span class="health-status <?php echo $system_health['status']; ?>">
                    <i class="fas <?php echo $system_health['status'] === 'healthy' ? 'fa-check-circle' : 'fa-exclamation-triangle'; ?>"></i>
                    <?php echo ucfirst($system_health['status']); ?>
                </span>
            </div>
            <div class="health-metrics">
                <div class="health-item">
                    <span class="health-label">Database Connection</span>
                    <span class="health-value <?php echo $system_health['database_connection'] ? 'healthy' : 'error'; ?>">
                        <i class="fas <?php echo $system_health['database_connection'] ? 'fa-check' : 'fa-times'; ?>"></i>
                        <?php echo $system_health['database_connection'] ? 'Connected' : 'Failed'; ?>
                    </span>
                </div>
                
                <div class="health-item">
                    <span class="health-label">Collections</span>
                    <span class="health-value <?php echo $system_health['collections_accessible'] ? 'healthy' : 'error'; ?>">
                        <i class="fas <?php echo $system_health['collections_accessible'] ? 'fa-check' : 'fa-times'; ?>"></i>
                        <?php echo $db_stats['collections'] ?? 'N/A'; ?> accessible
                    </span>
                </div>
                
                <div class="health-item">
                    <span class="health-label">Recent Errors</span>
                    <span class="health-value <?php echo $system_health['recent_errors'] == 0 ? 'healthy' : 'warning'; ?>">
                        <i class="fas fa-exclamation-triangle"></i>
                        <?php echo $system_health['recent_errors']; ?> in last 24h
                    </span>
                </div>
                
                <div class="health-item">
                    <span class="health-label">Indexes</span>
                    <span class="health-value healthy">
                        <i class="fas fa-list"></i>
                        <?php echo $db_stats['indexes'] ?? 'N/A'; ?> indexes
                    </span>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Recent Issues/Alerts -->
<?php if (!empty($recent_issues)): ?>
<div class="alerts-section">
    <div class="alert-card">
        <div class="alert-header">
            <h3>Recent Issues</h3>
            <span class="alert-count"><?php echo count($recent_issues); ?> issues</span>
        </div>
        <div class="alert-list">
            <?php foreach ($recent_issues as $issue): ?>
                <div class="alert-item <?php echo $issue['type']; ?>">
                    <div class="alert-icon">
                        <i class="fas fa-exclamation-triangle"></i>
                    </div>
                    <div class="alert-content">
                        <h4><?php echo h($issue['message']); ?></h4>
                        <p><?php echo h($issue['details']); ?></p>
                        <span class="alert-time"><?php echo time_ago($issue['timestamp']); ?></span>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Quick Actions -->
<div class="quick-actions">
    <div class="actions-card">
        <h3>Quick Actions</h3>
        <div class="actions-grid">
            <a href="?page=tenants&action=add" class="action-btn">
                <i class="fas fa-plus"></i>
                <span>Add Tenant</span>
            </a>
            <a href="?page=apps&action=add" class="action-btn">
                <i class="fas fa-mobile-alt"></i>
                <span>Add Application</span>
            </a>
            <a href="?page=items&action=import" class="action-btn">
                <i class="fas fa-upload"></i>
                <span>Import Items</span>
            </a>
            <a href="?page=analytics" class="action-btn">
                <i class="fas fa-chart-line"></i>
                <span>View Analytics</span>
            </a>
        </div>
    </div>
</div>

<script>
// Dashboard-specific JavaScript
function initializeDashboardCharts() {
    // Adapter Distribution Chart
    const adapterCtx = document.getElementById('adapterChart');
    if (adapterCtx) {
        const adapterData = <?php echo json_encode($chart_data['adapter_distribution']); ?>;
        
        new Chart(adapterCtx, {
            type: 'doughnut',
            data: {
                labels: adapterData.labels.map(label => label.toUpperCase()),
                datasets: [{
                    data: adapterData.data,
                    backgroundColor: [
                        '#dc2626', // Red for first adapter
                        '#f97316', // Orange for second
                        '#059669', // Green for third
                        '#3b82f6'  // Blue for fourth
                    ],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false // We have custom legend
                    }
                }
            }
        });
    }
    
    // Interactions Trend Chart
    const interactionsCtx = document.getElementById('interactionsChart');
    if (interactionsCtx) {
        const interactionsData = <?php echo json_encode($chart_data['interactions_trend']); ?>;
        
        const dates = interactionsData.map(item => item.date);
        const views = interactionsData.map(item => item.views);
        const plays = interactionsData.map(item => item.plays);
        const purchases = interactionsData.map(item => item.purchases);
        
        new Chart(interactionsCtx, {
            type: 'line',
            data: {
                labels: dates,
                datasets: [{
                    label: 'Views',
                    data: views,
                    borderColor: '#dc2626',
                    backgroundColor: 'rgba(220, 38, 38, 0.1)',
                    tension: 0.4,
                    fill: false
                }, {
                    label: 'Plays',
                    data: plays,
                    borderColor: '#f97316',
                    backgroundColor: 'rgba(249, 115, 22, 0.1)',
                    tension: 0.4,
                    fill: false
                }, {
                    label: 'Purchases',
                    data: purchases,
                    borderColor: '#059669',
                    backgroundColor: 'rgba(5, 150, 105, 0.1)',
                    tension: 0.4,
                    fill: false
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }
}

function refreshDashboardData() {
    // Implement AJAX refresh for dashboard data
    fetch('api/dashboard-refresh.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Update stat cards
                updateStatCards(data.stats);
            }
        })
        .catch(error => {
            console.error('Error refreshing dashboard data:', error);
        });
}

function updateStatCards(stats) {
    // Update the stat card values
    document.querySelector('.stat-card:nth-child(1) h3').textContent = formatNumber(stats.tenants);
    document.querySelector('.stat-card:nth-child(2) h3').textContent = formatNumber(stats.apps);
    // ... update other stats
}
</script>
