<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<main class="main-content" id="mainContent">
    <header class="main-header">
        <div>
            <h1>ANALYTICS & REPORTS</h1>
            <p class="welcome-text">Comprehensive analytics and performance metrics</p>
        </div>
        <div class="header-actions">
            <button class="btn btn-primary" onclick="refreshAnalytics()">
                <i class="fas fa-sync-alt"></i> Refresh Data
            </button>
            <button class="btn btn-secondary" onclick="exportAnalytics()">
                <i class="fas fa-download"></i> Export Report
            </button>
        </div>
    </header>

    <!-- Analytics Overview -->
    <div class="metrics-cards">
        <div class="card stat-card">
            <div class="card-icon">
                <i class="fas fa-folder"></i>
            </div>
            <div class="card-content">
                <p class="card-label">TOTAL PROJECTS</p>
                <div class="card-data">
                    <span class="value" id="totalProjects"><?php echo $analytics_data['total_projects']; ?></span>
                    <span class="change positive">+12%</span>
                </div>
            </div>
        </div>

        <div class="card stat-card">
            <div class="card-icon">
                <i class="fas fa-users"></i>
            </div>
            <div class="card-content">
                <p class="card-label">TOTAL MODELS</p>
                <div class="card-data">
                    <span class="value" id="totalModels"><?php echo $analytics_data['total_models']; ?></span>
                    <span class="change positive">+8%</span>
                </div>
            </div>
        </div>

        <div class="card stat-card">
            <div class="card-icon">
                <i class="fas fa-file-pdf"></i>
            </div>
            <div class="card-content">
                <p class="card-label">PDF FILES</p>
                <div class="card-data">
                    <span class="value" id="totalPdfs"><?php echo $analytics_data['total_pdfs']; ?></span>
                    <span class="change positive">+15%</span>
                </div>
            </div>
        </div>

        <div class="card stat-card">
            <div class="card-icon">
                <i class="fas fa-user-friends"></i>
            </div>
            <div class="card-content">
                <p class="card-label">ACTIVE USERS</p>
                <div class="card-data">
                    <span class="value" id="totalUsers"><?php echo $analytics_data['total_users']; ?></span>
                    <span class="change positive">+5%</span>
                </div>
            </div>
        </div>
    </div>

    <div class="analytics-grid">
        <!-- Left Column -->
        <div class="analytics-column">
            <!-- Project Status Distribution -->
            <div class="chart-card">
                <div class="chart-header">
                    <h3>Project Status Distribution</h3>
                    <div class="chart-legend">
                        <span class="legend-item"><span class="legend-color created"></span>Created</span>
                        <span class="legend-item"><span class="legend-color processing"></span>Processing</span>
                        <span class="legend-item"><span class="legend-color completed"></span>Completed</span>
                    </div>
                </div>
                <div class="chart-container">
                    <canvas id="projectStatusChart"></canvas>
                </div>
            </div>

            <!-- Monthly Growth Trend -->
            <div class="chart-card">
                <div class="chart-header">
                    <h3>Monthly Growth Trend</h3>
                    <select id="growthMetric" onchange="updateGrowthChart()" class="form-select" style="width: auto; padding: 5px 10px;">
                        <option value="both">Projects & Models</option>
                        <option value="projects">Projects Only</option>
                        <option value="models">Models Only</option>
                    </select>
                </div>
                <div class="chart-container">
                    <canvas id="growthChart"></canvas>
                </div>
            </div>
        </div>

        <!-- Right Column -->
        <div class="analytics-column">
            <!-- Models Distribution -->
            <div class="chart-card">
                <div class="chart-header">
                    <h3>Models Distribution</h3>
                    <span class="results-count" id="modelsCount"><?php echo count($analytics_data['models_distribution']['labels']); ?> projects</span>
                </div>
                <div class="chart-container">
                    <canvas id="modelsChart"></canvas>
                </div>
            </div>

            <!-- Agency Statistics -->
           <div class="chart-card">
                <div class="chart-header">
                    <h3>Agency Overview</h3>
                    <span class="agency-count"><?php echo $agency_stats['total_agencies']; ?> agencies</span>
                </div>
                <div class="agency-stats">
                    <?php if (!empty($agency_stats['agencies'])): ?>
                        <?php foreach ($agency_stats['agencies'] as $agency): ?>
                        <div class="agency-stat-item">
                            <div class="agency-info">
                                <strong><?php echo htmlspecialchars($agency->name); ?></strong>
                                <span><?php echo $agency->contact_email; ?></span>
                            </div>
                            <div class="agency-status <?php echo $agency->status; ?>">
                                <?php echo ucfirst($agency->status); ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="empty-state">
                            <i class="fas fa-building"></i>
                            <p>No agencies found</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>


            <!-- Quick Stats -->
            <div class="chart-card">
                <div class="chart-header">
                    <h3>Performance Metrics</h3>
                </div>
                <div class="performance-metrics">
                    <div class="metric-item">
                        <div class="metric-info">
                            <span class="metric-label">Success Rate</span>
                            <span class="metric-value">98.2%</span>
                        </div>
                        <div class="metric-bar">
                            <div class="metric-fill" style="width: 98.2%"></div>
                        </div>
                    </div>
                    <div class="metric-item">
                        <div class="metric-info">
                            <span class="metric-label">Avg. Processing Time</span>
                            <span class="metric-value">2.3s</span>
                        </div>
                        <div class="metric-bar">
                            <div class="metric-fill" style="width: 85%"></div>
                        </div>
                    </div>
                    <div class="metric-item">
                        <div class="metric-info">
                            <span class="metric-label">Data Accuracy</span>
                            <span class="metric-value">96.5%</span>
                        </div>
                        <div class="metric-bar">
                            <div class="metric-fill" style="width: 96.5%"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Detailed Reports -->
    <div class="content-area">
        <div class="section-header">
            <h2>Detailed Analytics</h2>
            <div class="report-controls">
                <select class="filter-select" id="reportPeriod" onchange="loadDetailedReports()">
                    <option value="7days">Last 7 Days</option>
                    <option value="30days">Last 30 Days</option>
                    <option value="90days">Last 90 Days</option>
                    <option value="1year">Last Year</option>
                </select>
            </div>
        </div>
        
        <div class="reports-grid" id="detailedReports">
            <div class="report-item loading">
                <div class="report-skeleton"></div>
            </div>
        </div>
    </div>
</main>

<style>
.analytics-grid {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 24px;
    margin-bottom: 30px;
}

.analytics-column {
    display: flex;
    flex-direction: column;
    gap: 24px;
}

.chart-legend {
    display: flex;
    gap: 16px;
    font-size: 12px;
}

.legend-item {
    display: flex;
    align-items: center;
    gap: 6px;
}

.legend-color {
    width: 12px;
    height: 12px;
    border-radius: 50%;
}

.legend-color.created { background: #4caf50; }
.legend-color.processing { background: #ff9800; }
.legend-color.completed { background: #2196f3; }

.agency-stats {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.agency-stat-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px solid var(--border-color);
}

.agency-info {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.agency-info strong {
    font-size: 14px;
    color: var(--text-color);
}

.agency-info span {
    font-size: 12px;
    color: var(--light-text);
}

.agency-status {
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
}

.agency-status.active { background: #e8f5e8; color: #2e7d32; }
.agency-status.inactive { background: #ffebee; color: #c62828; }

.performance-metrics {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.metric-item {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.metric-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.metric-label {
    font-size: 14px;
    color: var(--text-color);
    font-weight: 600;
}

.metric-value {
    font-size: 14px;
    font-weight: 700;
    color: var(--text-color);
}

.metric-bar {
    height: 6px;
    background: #f0f0f0;
    border-radius: 3px;
    overflow: hidden;
}

.metric-fill {
    height: 100%;
    background: linear-gradient(90deg, #667eea, #764ba2);
    border-radius: 3px;
    transition: width 0.5s ease;
}

.reports-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
}

.report-item {
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    padding: 20px;
}

.report-item.loading {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 120px;
}

.report-skeleton {
    width: 100%;
    height: 20px;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: loading 1.5s infinite;
    border-radius: 4px;
}

@keyframes loading {
    0% { background-position: 200% 0; }
    100% { background-position: -200% 0; }
}

.results-count, .agency-count {
    font-size: 12px;
    color: var(--light-text);
    font-weight: 600;
}

.empty-state {
    text-align: center;
    padding: 40px 20px;
    color: var(--light-text);
}

.empty-state i {
    font-size: 48px;
    margin-bottom: 16px;
    opacity: 0.5;
}

@media (max-width: 768px) {
    .analytics-grid {
        grid-template-columns: 1fr;
    }
}
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Chart instances
let projectStatusChart, growthChart, modelsChart;

// Analytics data from PHP
const analyticsData = <?php echo json_encode($analytics_data); ?>;

document.addEventListener('DOMContentLoaded', function() {
    initializeCharts();
    loadDetailedReports();
});

function initializeCharts() {
    // Project Status Chart
    const statusCtx = document.getElementById('projectStatusChart').getContext('2d');
    projectStatusChart = new Chart(statusCtx, {
        type: 'doughnut',
        data: {
            labels: ['Created', 'Processing', 'Completed'],
            datasets: [{
                data: [
                    analyticsData.project_status.created || 0,
                    analyticsData.project_status.processing || 0,
                    analyticsData.project_status.completed || 0
                ],
                backgroundColor: ['#4caf50', '#ff9800', '#2196f3'],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            cutout: '70%',
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return `${context.label}: ${context.raw}`;
                        }
                    }
                }
            }
        }
    });

    // Growth Chart
    const growthCtx = document.getElementById('growthChart').getContext('2d');
    growthChart = new Chart(growthCtx, {
        type: 'line',
        data: {
            labels: analyticsData.monthly_growth.map(item => item.month),
            datasets: [
                {
                    label: 'Projects',
                    data: analyticsData.monthly_growth.map(item => item.projects),
                    borderColor: '#667eea',
                    backgroundColor: 'rgba(102, 126, 234, 0.1)',
                    tension: 0.4,
                    fill: true
                },
                {
                    label: 'Models',
                    data: analyticsData.monthly_growth.map(item => item.models),
                    borderColor: '#764ba2',
                    backgroundColor: 'rgba(118, 75, 162, 0.1)',
                    tension: 0.4,
                    fill: true
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                intersect: false,
                mode: 'index'
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.1)'
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            }
        }
    });

    // Models Distribution Chart
    const modelsCtx = document.getElementById('modelsChart').getContext('2d');
    modelsChart = new Chart(modelsCtx, {
        type: 'bar',
        data: {
            labels: analyticsData.models_distribution.labels,
            datasets: [{
                label: 'Models',
                data: analyticsData.models_distribution.data,
                backgroundColor: '#667eea',
                borderRadius: 8,
                borderSkipped: false,
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0,0,0,0.1)'
                    }
                },
                x: {
                    grid: {
                        display: false
                    },
                    ticks: {
                        maxRotation: 45,
                        minRotation: 45
                    }
                }
            }
        }
    });
}

function updateGrowthChart() {
    const metric = document.getElementById('growthMetric').value;
    
    growthChart.data.datasets[0].hidden = metric === 'models';
    growthChart.data.datasets[1].hidden = metric === 'projects';
    
    growthChart.update();
}

function loadDetailedReports() {
    const period = document.getElementById('reportPeriod').value;
    const reportsGrid = document.getElementById('detailedReports');
    
    // Simulate loading
    reportsGrid.innerHTML = `
        <div class="report-item loading">
            <div class="report-skeleton"></div>
        </div>
        <div class="report-item loading">
            <div class="report-skeleton"></div>
        </div>
    `;
    
    // Simulate API call
    setTimeout(() => {
        reportsGrid.innerHTML = `
            <div class="report-item">
                <h4>Processing Efficiency</h4>
                <div class="metric-value" style="font-size: 24px; margin: 10px 0;">98.2%</div>
                <p style="color: var(--light-text); font-size: 14px;">Successful PDF processing rate</p>
            </div>
            <div class="report-item">
                <h4>Average Processing Time</h4>
                <div class="metric-value" style="font-size: 24px; margin: 10px 0;">2.3s</div>
                <p style="color: var(--light-text); font-size: 14px;">Per PDF file</p>
            </div>
            <div class="report-item">
                <h4>Data Extraction Accuracy</h4>
                <div class="metric-value" style="font-size: 24px; margin: 10px 0;">96.5%</div>
                <p style="color: var(--light-text); font-size: 14px;">Model information accuracy</p>
            </div>
            <div class="report-item">
                <h4>System Uptime</h4>
                <div class="metric-value" style="font-size: 24px; margin: 10px 0;">99.9%</div>
                <p style="color: var(--light-text); font-size: 14px;">Last 30 days</p>
            </div>
        `;
    }, 1000);
}

function refreshAnalytics() {
    location.reload();
}

function exportAnalytics() {
    // Create a simple CSV export
    const csvContent = [
        ['Metric', 'Value'],
        ['Total Projects', analyticsData.total_projects],
        ['Total Models', analyticsData.total_models],
        ['Total PDFs', analyticsData.total_pdfs],
        ['Total Users', analyticsData.total_users],
        ['Created Projects', analyticsData.project_status.created],
        ['Processing Projects', analyticsData.project_status.processing],
        ['Completed Projects', analyticsData.project_status.completed]
    ].map(row => row.join(',')).join('\n');
    
    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `analytics-report-${new Date().toISOString().split('T')[0]}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    alert('Analytics report exported successfully!');
}
</script>