<main class="main-content" id="mainContent">
    <header class="main-header">
        <div>
            <h1><?php echo strtoupper($page_title); ?></h1>
            <p class="welcome-text">Welcome to GO Productions Analytics Dashboard - Monitor your system performance</p>
        </div>
        <div class="header-actions">
            <button class="btn btn-primary" onclick="refreshDashboard()">
                <i class="fas fa-sync-alt"></i> Refresh Data
            </button>
        </div>
    </header>

    <!-- Quick Stats Cards -->
    <section 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">0</span>
                    <span class="change positive" id="projectsChange">+0%</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">0</span>
                    <span class="change positive" id="modelsChange">+0%</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">0</span>
                    <span class="change positive" id="pdfsChange">+0%</span>
                </div>
            </div>
        </div>

        <div class="card stat-card">
            <div class="card-icon">
                <i class="fas fa-images"></i>
            </div>
            <div class="card-content">
                <p class="card-label">EXTRACTED IMAGES</p>
                <div class="card-data">
                    <span class="value" id="totalImages">0</span>
                    <span class="change positive" id="imagesChange">+0%</span>
                </div>
            </div>
        </div>
    </section>

    <!-- Main Analytics Grid -->
    <div class="analytics-grid">
        <!-- Left Column -->
        <div class="analytics-column">
            <!-- Projects Overview Chart -->
            <div class="chart-card">
                <div class="chart-header">
                    <h3>Projects Overview</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="projectsChart"></canvas>
                </div>
            </div>

            <!-- Models per Project Distribution -->
            <div class="chart-card">
                <div class="chart-header">
                    <h3>Models Distribution</h3>
                    <select id="projectSelect" onchange="updateModelsChart()" style="padding: 5px 10px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--card-bg);">
                        <option value="all">All Projects</option>
                    </select>
                </div>
                <div class="chart-container">
                    <canvas id="modelsChart"></canvas>
                </div>
            </div>
        </div>

        <!-- Right Column -->
        <div class="analytics-column">
            <!-- System Status -->
            <div class="chart-card">
                <div class="chart-header">
                    <h3>System Status</h3>
                    <div class="status-indicator" id="systemStatus">
                        <span class="status-dot checking"></span>
                        <span>Checking...</span>
                    </div>
                </div>
                <div class="status-grid">
                    <div class="status-item">
                        <div class="status-info">
                            <span class="status-label">Python Service</span>
                            <span class="status-value" id="pythonServiceStatus">Checking...</span>
                        </div>
                        <div class="status-icon" id="pythonServiceIcon">
                            <i class="fas fa-question"></i>
                        </div>
                    </div>
                    <div class="status-item">
                        <div class="status-info">
                            <span class="status-label">Database</span>
                            <span class="status-value" id="databaseStatus">Checking...</span>
                        </div>
                        <div class="status-icon" id="databaseIcon">
                            <i class="fas fa-question"></i>
                        </div>
                    </div>
                    <div class="status-item">
                        <div class="status-info">
                            <span class="status-label">Storage</span>
                            <span class="status-value" id="storageStatus">Checking...</span>
                        </div>
                        <div class="status-icon" id="storageIcon">
                            <i class="fas fa-question"></i>
                        </div>
                    </div>
                    <div class="status-item">
                        <div class="status-info">
                            <span class="status-label">Last Backup</span>
                            <span class="status-value" id="lastBackup">Never</span>
                        </div>
                        <div class="status-icon">
                            <i class="fas fa-database"></i>
                        </div>
                    </div>
                </div>
            </div>
            

            <!-- Recent Activity -->
            <div class="chart-card">
                <div class="chart-header">
                    <h3>Recent Activity</h3>
                    <button class="btn btn-sm" onclick="loadRecentActivity()">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                </div>
                <div class="activity-list" id="recentActivity">
                    <div class="activity-item loading">
                        <i class="fas fa-spinner fa-spin"></i>
                        <span>Loading activities...</span>
                    </div>
                </div>
            </div>

            <!-- Storage Usage -->
            <div class="chart-card">
                <div class="chart-header">
                    <h3>Storage Usage</h3>
                    <span class="storage-total" id="storageTotal">0 MB</span>
                </div>
                <div class="storage-breakdown">
                    <div class="storage-item">
                        <span class="storage-label">PDF Files</span>
                        <div class="storage-bar">
                            <div class="storage-fill pdf-fill" style="width: 0%"></div>
                        </div>
                        <span class="storage-size" id="pdfStorage">0 MB</span>
                    </div>
                    <div class="storage-item">
                        <span class="storage-label">Images</span>
                        <div class="storage-bar">
                            <div class="storage-fill image-fill" style="width: 0%"></div>
                        </div>
                        <span class="storage-size" id="imageStorage">0 MB</span>
                    </div>
                    <div class="storage-item">
                        <span class="storage-label">Temporary Files</span>
                        <div class="storage-bar">
                            <div class="storage-fill temp-fill" style="width: 0%"></div>
                        </div>
                        <span class="storage-size" id="tempStorage">0 MB</span>
                        <button class="btn-cleanup" onclick="cleanupTempFiles()" title="Clean up temporary files">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
<!-- PDF Storage Management -->
<div class="chart-card">
    <div class="chart-header">
        <h3>PDF Storage Management</h3>
        <button class="btn btn-warning btn-sm" onclick="loadPdfStorageInfo()">
            <i class="fas fa-sync-alt"></i> Refresh
        </button>
    </div>
    <div class="storage-info" id="pdfStorageInfo">
        <div class="loading-state">
            <div class="spinner"></div>
            <p>Loading PDF storage information...</p>
        </div>
    </div>
</div>
    <!-- Recent Projects Section -->
    <section class="content-area">
        <div class="section-header">
            <h2>Recent Projects</h2>
            <a href="<?php echo base_url('project'); ?>" class="btn btn-secondary">View All Projects</a>
        </div>
        <div class="projects-grid" id="recentProjects">
            <div class="project-card loading">
                <div class="project-skeleton"></div>
            </div>
            <div class="project-card loading">
                <div class="project-skeleton"></div>
            </div>
            <div class="project-card loading">
                <div class="project-skeleton"></div>
            </div>
        </div>
    </section>
</main>

<style>
/* Enhanced Card Styles */
.metrics-cards {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-bottom: 30px;
}

.stat-card {
    background: linear-gradient(135deg, var(--card-bg) 0%, #f8f9fa 100%);
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 8px 32px rgba(0,0,0,0.1);
    border: 1px solid rgba(255,255,255,0.2);
    display: flex;
    align-items: center;
    gap: 16px;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.stat-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
}

.stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 12px 40px rgba(0,0,0,0.15);
}

.card-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    background: linear-gradient(135deg, #000000ff 0%, #060507ff 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 24px;
}

.card-content {
    flex: 1;
}

.card-label {
    font-size: 14px;
    color: var(--light-text);
    margin-bottom: 8px;
    font-weight: 600;
}

.card-data {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.value {
    font-size: 32px;
    font-weight: 800;
    color: var(--text-color);
    letter-spacing: -0.5px;
}

.change {
    font-size: 12px;
    font-weight: 700;
    padding: 4px 8px;
    border-radius: 12px;
}

.change.positive {
    background: #e8f5e8;
    color: #2e7d32;
}

.change.negative {
    background: #ffebee;
    color: #c62828;
}

/* Analytics Grid */
.analytics-grid {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 24px;
    margin-bottom: 30px;
}

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

/* Chart Cards */
.chart-card {
    background-color: var(--card-bg);
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    border: 1px solid var(--border-color);
}

.chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.chart-header h3 {
    font-size: 18px;
    font-weight: 700;
    color: var(--text-color);
    margin: 0;
}

.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; }

.chart-container {
    height: 300px;
    position: relative;
}

/* Status Grid */
.status-grid {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

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

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

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

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

.status-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
}

.status-icon.healthy { background: #e8f5e8; color: #4caf50; }
.status-icon.warning { background: #fff3e0; color: #ff9800; }
.status-icon.error { background: #ffebee; color: #f44336; }
.status-icon.checking { background: #f0f0f0; color: #666; }

.status-indicator {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    font-weight: 600;
}

.status-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
}

.status-dot.healthy { background: #4caf50; }
.status-dot.warning { background: #ff9800; }
.status-dot.error { background: #f44336; }
.status-dot.checking { 
    background: #666;
    animation: pulse 1.5s infinite;
}

@keyframes pulse {
    0% { opacity: 1; }
    50% { opacity: 0.5; }
    100% { opacity: 1; }
}

/* Activity List */
.activity-list {
    max-height: 200px;
    overflow-y: auto;
}

.activity-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 0;
    border-bottom: 1px solid var(--border-color);
}

.activity-item:last-child {
    border-bottom: none;
}

.activity-item.loading {
    justify-content: center;
    color: var(--light-text);
}

.activity-icon {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
}

.activity-content {
    flex: 1;
}

.activity-title {
    font-size: 14px;
    font-weight: 600;
    color: var(--text-color);
    margin-bottom: 2px;
}

.activity-time {
    font-size: 12px;
    color: var(--light-text);
}

/* Storage Breakdown */
.storage-breakdown {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.storage-item {
    display: flex;
    align-items: center;
    gap: 12px;
}

.storage-label {
    font-size: 14px;
    color: var(--text-color);
    font-weight: 600;
    min-width: 120px;
}

.storage-bar {
    flex: 1;
    height: 8px;
    background: #f0f0f0;
    border-radius: 4px;
    overflow: hidden;
}

.storage-fill {
    height: 100%;
    border-radius: 4px;
    transition: width 0.5s ease;
}

.storage-fill.pdf-fill { background: #667eea; }
.storage-fill.image-fill { background: #764ba2; }
.storage-fill.temp-fill { background: #f093fb; }

.storage-size {
    font-size: 12px;
    color: var(--light-text);
    min-width: 60px;
    text-align: right;
}

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

.btn-cleanup {
    background: none;
    border: none;
    color: #dc3545;
    cursor: pointer;
    padding: 4px;
    border-radius: 4px;
    transition: background 0.3s ease;
}

.btn-cleanup:hover {
    background: #ffebee;
}

/* Projects Grid */
.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}

.section-header h2 {
    font-size: 24px;
    font-weight: 700;
    color: var(--text-color);
    margin: 0;
}

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

.project-card {
    background: var(--card-bg);
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    border: 1px solid var(--border-color);
    transition: transform 0.3s ease;
}

.project-card:hover {
    transform: translateY(-2px);
}

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

.project-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;
}

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

.status-badge.created { background: #e8f5e8; color: #2e7d32; }
.status-badge.processing { background: #fff3e0; color: #ef6c00; }
.status-badge.completed { background: #e3f2fd; color: #1565c0; }

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

/* Responsive Design */
@media (max-width: 1200px) {
    .metrics-cards {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .analytics-grid {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 768px) {
    .metrics-cards {
        grid-template-columns: 1fr;
    }
    
    .stat-card {
        padding: 20px;
    }
    
    .chart-container {
        height: 250px;
    }
}

.btn-sm {
    padding: 6px 12px;
    font-size: 12px;
    background: none;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.btn-sm:hover {
    background: var(--border-color);
}
</style>

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

// Initialize dashboard
document.addEventListener('DOMContentLoaded', function() {
    loadDashboardData();
    initializeCharts();
    checkSystemStatus();
    loadRecentProjects();
    loadRecentActivity();
    loadPdfStorageInfo();
});

function initializeCharts() {
    // Destroy existing charts first
    if (projectsChart) {
        projectsChart.destroy();
    }
    if (modelsChart) {
        modelsChart.destroy();
    }

    // Projects Status Chart
    const projectsCtx = document.getElementById('projectsChart').getContext('2d');
    projectsChart = new Chart(projectsCtx, {
        type: 'doughnut',
        data: {
            labels: ['Created', 'Processing', 'Completed'],
            datasets: [{
                data: [0, 0, 0],
                backgroundColor: ['#4caf50', '#ff9800', '#2196f3'],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            cutout: '70%',
            plugins: {
                legend: {
                    display: false
                }
            }
        }
    });

    // Models Distribution Chart
    const modelsCtx = document.getElementById('modelsChart').getContext('2d');
    modelsChart = new Chart(modelsCtx, {
        type: 'bar',
        data: {
            labels: [],
            datasets: [{
                label: 'Models',
                data: [],
                backgroundColor: '#667eea',
                borderRadius: 8,
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            }
        }
    });
}

function refreshDashboard() {
    // Destroy charts before refreshing
    if (projectsChart) {
        projectsChart.destroy();
    }
    if (modelsChart) {
        modelsChart.destroy();
    }
    
    // Reinitialize everything
    loadDashboardData();
    initializeCharts();
    checkSystemStatus();
    loadRecentProjects();
    loadRecentActivity();
}

async function loadDashboardData() {
    try {
        const response = await fetch('<?php echo base_url('admin/get_dashboard_data'); ?>');
        const data = await response.json();
        
        if (data.success) {
            updateDashboardStats(data.data.stats);
            updateProjectsChart(data.data.projects);
            updateModelsChart(data.data.models);
            updateStorageInfo(data.data.storage);
        } else {
            console.error('Failed to load dashboard data:', data.error);
            // Set default values on error
            updateDashboardStats({
                total_projects: 0,
                total_models: 0,
                total_pdfs: 0,
                total_images: 0
            });
        }
    } catch (error) {
        console.error('Error loading dashboard data:', error);
        // Set default values on error
        updateDashboardStats({
            total_projects: 0,
            total_models: 0,
            total_pdfs: 0,
            total_images: 0
        });
    }
}

function updateModelsChart(models) {
    if (modelsChart && models && models.labels && models.data) {
        // Ensure we have valid data for the chart
        const validLabels = [];
        const validData = [];
        
        models.labels.forEach((label, index) => {
            if (label && label !== 'No Models Yet') {
                validLabels.push(label.length > 20 ? label.substring(0, 20) + '...' : label);
                validData.push(models.data[index] || 0);
            }
        });
        
        // If no valid data, show placeholder
        if (validLabels.length === 0) {
            validLabels.push('No Models Data');
            validData.push(0);
        }
        
        modelsChart.data.labels = validLabels;
        modelsChart.data.datasets[0].data = validData;
        modelsChart.update();
    }
}

async function cleanupTempFiles() {
    if (confirm('Are you sure you want to clean up all temporary PDF files? This will remove processing files but keep extracted data.')) {
        try {
            const response = await fetch('<?php echo base_url('admin/cleanup_temp_files'); ?>', {
                method: 'POST'
            });
            const data = await response.json();
            
            if (data.success) {
                let message = data.message;
                if (data.details) {
                    message += `\n\nDetails:\n- Temp files: ${data.details.temp_files}\n- Project temp files: ${data.details.project_temp_files}\n- Total cleaned: ${data.details.temp_files + data.details.project_temp_files} files`;
                }
                alert(message);
                loadDashboardData(); // Refresh data
            } else {
                alert('Failed to clean up temporary files: ' + (data.message || 'Unknown error'));
            }
        } catch (error) {
            alert('Error cleaning up temporary files: ' + error.message);
        }
    }
}

function updateDashboardStats(stats) {
    document.getElementById('totalProjects').textContent = stats.total_projects || 0;
    document.getElementById('totalModels').textContent = stats.total_models || 0;
    document.getElementById('totalPdfs').textContent = stats.total_pdfs || 0;
    document.getElementById('totalImages').textContent = stats.total_images || 0;
    
    // Update changes (you can implement real change calculations)
    document.getElementById('projectsChange').textContent = stats.total_projects > 0 ? '+12%' : '+0%';
    document.getElementById('modelsChange').textContent = stats.total_models > 0 ? '+8%' : '+0%';
    document.getElementById('pdfsChange').textContent = stats.total_pdfs > 0 ? '+15%' : '+0%';
    document.getElementById('imagesChange').textContent = stats.total_images > 0 ? '+20%' : '+0%';
}

function updateProjectsChart(projects) {
    if (projectsChart && projects) {
        projectsChart.data.datasets[0].data = [
            projects.created || 0,
            projects.processing || 0,
            projects.completed || 0
        ];
        projectsChart.update();
    }
}
async function loadPdfStorageInfo() {
    try {
        const response = await fetch('<?php echo base_url('admin/get_pdf_storage_info'); ?>');
        const data = await response.json();
        
        if (data.success) {
            displayPdfStorageInfo(data.storage);
        } else {
            throw new Error(data.error || 'Failed to load PDF storage info');
        }
    } catch (error) {
        document.getElementById('pdfStorageInfo').innerHTML = `
            <div class="error-state">
                <i class="fas fa-exclamation-triangle"></i>
                <p>Error loading PDF storage information</p>
            </div>
        `;
    }
}

function displayPdfStorageInfo(storage) {
    const pdfStorageInfo = document.getElementById('pdfStorageInfo');
    
    let html = `
        <div class="storage-summary">
            <div class="storage-total">
                <strong>Total PDF Storage:</strong> ${storage.total_display}
            </div>
            <div class="storage-files">
                <strong>Total PDF Files:</strong> ${storage.total_files_display}
            </div>
        </div>
    `;
    
    if (storage.projects && storage.projects.length > 0) {
        html += `<div class="projects-storage">`;
        
        storage.projects.forEach(project => {
            const projectSize = formatBytes(project.total_bytes);
            html += `
                <div class="project-storage-item">
                    <div class="project-info">
                        <strong>${project.project_name}</strong>
                        <span>${project.file_count} files - ${projectSize}</span>
                    </div>
                    <div class="project-actions">
                        <button class="btn btn-danger btn-sm" onclick="cleanupProjectPdfs('${project.project_id}')">
                            <i class="fas fa-trash"></i> Cleanup
                        </button>
                    </div>
                </div>
            `;
        });
        
        html += `</div>`;
        
        // Add cleanup all button
        html += `
            <div class="cleanup-actions" style="margin-top: 20px; padding-top: 20px; border-top: 1px solid var(--border-color);">
                <button class="btn btn-danger" onclick="cleanupAllPdfs()">
                    <i class="fas fa-broom"></i> Cleanup All PDF Files
                </button>
                <small style="display: block; margin-top: 8px; color: var(--light-text);">
                    This will delete all PDF files from all projects. Extracted data will be preserved.
                </small>
            </div>
        `;
    } else {
        html += `<div class="empty-state">No PDF files found</div>`;
    }
    
    pdfStorageInfo.innerHTML = html;
}

async function cleanupProjectPdfs(projectId) {
    if (confirm('Are you sure you want to delete all PDF files for this project? The extracted model data will be preserved.')) {
        try {
            const response = await fetch('<?php echo base_url('admin/cleanup_pdf_files'); ?>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `project_id=${projectId}`
            });
            
            const data = await response.json();
            
            if (data.success) {
                alert(data.message);
                loadPdfStorageInfo(); // Refresh the display
            } else {
                throw new Error(data.message || 'Failed to cleanup PDF files');
            }
        } catch (error) {
            alert('Error cleaning up PDF files: ' + error.message);
        }
    }
}

async function cleanupAllPdfs() {
    if (confirm('WARNING: This will delete ALL PDF files from ALL projects. This action cannot be undone. Are you sure?')) {
        try {
            const response = await fetch('<?php echo base_url('admin/cleanup_pdf_files'); ?>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'project_id=all'
            });
            
            const data = await response.json();
            
            if (data.success) {
                alert(data.message);
                loadPdfStorageInfo(); // Refresh the display
            } else {
                throw new Error(data.message || 'Failed to cleanup PDF files');
            }
        } catch (error) {
            alert('Error cleaning up PDF files: ' + error.message);
        }
    }
}

function formatBytes(bytes, decimals = 2) {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

// Initialize dashboard - only ONE DOMContentLoaded listener
document.addEventListener('DOMContentLoaded', function() {
    loadDashboardData();
    initializeCharts();
    checkSystemStatus();
    loadRecentProjects();
    loadRecentActivity();
    loadPdfStorageInfo(); // Ensure PDF storage info is loaded
});

// Load PDF storage info when page loads
document.addEventListener('DOMContentLoaded', function() {
    loadPdfStorageInfo();
});



async function checkSystemStatus() {
    try {
        // Check Python service with proper error handling
        let pythonStatus = 'Unavailable';
        let pythonHealthy = false;
        
        try {
            const pythonResponse = await fetch('http://127.0.0.1:5000/health');
            if (pythonResponse.ok) {
                const pythonData = await pythonResponse.json();
                pythonStatus = pythonData.status === 'healthy' ? 'Healthy' : 'Unavailable';
                pythonHealthy = pythonData.status === 'healthy';
            }
        } catch (pythonError) {
            console.log('Python service check failed:', pythonError);
            pythonStatus = 'Unavailable';
            pythonHealthy = false;
        }
        
        document.getElementById('pythonServiceStatus').textContent = pythonStatus;
        document.getElementById('pythonServiceIcon').className = `status-icon ${pythonHealthy ? 'healthy' : 'error'}`;
        document.getElementById('pythonServiceIcon').innerHTML = `<i class="fas ${pythonHealthy ? 'fa-check' : 'fa-times'}"></i>`;
        
        // Database status (assume healthy if we got this far)
        document.getElementById('databaseStatus').textContent = 'Healthy';
        document.getElementById('databaseIcon').className = 'status-icon healthy';
        document.getElementById('databaseIcon').innerHTML = '<i class="fas fa-check"></i>';
        
        // Storage status
        document.getElementById('storageStatus').textContent = 'Healthy';
        document.getElementById('storageIcon').className = 'status-icon healthy';
        document.getElementById('storageIcon').innerHTML = '<i class="fas fa-check"></i>';
        
        // Update overall system status
        const allHealthy = pythonHealthy;
        document.getElementById('systemStatus').innerHTML = `
            <span class="status-dot ${allHealthy ? 'healthy' : 'error'}"></span>
            <span>${allHealthy ? 'All Systems Operational' : 'Service Issues Detected'}</span>
        `;
        
    } catch (error) {
        console.error('System status check error:', error);
        document.getElementById('systemStatus').innerHTML = `
            <span class="status-dot error"></span>
            <span>Status Check Failed</span>
        `;
    }
}

async function loadRecentProjects() {
    try {
        const response = await fetch('<?php echo base_url('admin/get_recent_projects'); ?>');
        const data = await response.json();
        
        const projectsGrid = document.getElementById('recentProjects');
        
        if (data.success && data.projects && data.projects.length > 0) {
            projectsGrid.innerHTML = data.projects.map(project => `
                <div class="project-card">
                    <h4>${project.name || 'Unnamed Project'}</h4>
                    <p style="color: var(--light-text); margin: 8px 0; font-size: 14px;">${project.description || 'No description'}</p>
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 16px;">
                        <span class="status-badge ${project.status || 'created'}">${project.status || 'created'}</span>
                        <small style="color: var(--light-text);">${new Date(project.created_at).toLocaleDateString()}</small>
                    </div>
                </div>
            `).join('');
        } else {
            projectsGrid.innerHTML = '<div class="project-card" style="text-align: center; color: var(--light-text);">No recent projects found</div>';
        }
    } catch (error) {
        console.error('Error loading recent projects:', error);
        const projectsGrid = document.getElementById('recentProjects');
        projectsGrid.innerHTML = '<div class="project-card" style="text-align: center; color: var(--light-text);">Error loading projects</div>';
    }
}

async function loadRecentActivity() {
    try {
        const response = await fetch('<?php echo base_url('admin/get_recent_activity'); ?>');
        const data = await response.json();
        
        const activityList = document.getElementById('recentActivity');
        
        if (data.success && data.activities && data.activities.length > 0) {
            activityList.innerHTML = data.activities.map(activity => `
                <div class="activity-item">
                    <div class="activity-icon" style="background: ${activity.color || '#f0f0f0'};">
                        <i class="${activity.icon || 'fas fa-info'}"></i>
                    </div>
                    <div class="activity-content">
                        <div class="activity-title">${activity.title}</div>
                        <div class="activity-time">${activity.time}</div>
                    </div>
                </div>
            `).join('');
        } else {
            activityList.innerHTML = '<div class="activity-item" style="justify-content: center; color: var(--light-text);">No recent activity</div>';
        }
    } catch (error) {
        console.error('Error loading recent activity:', error);
        const activityList = document.getElementById('recentActivity');
        activityList.innerHTML = '<div class="activity-item" style="justify-content: center; color: var(--light-text);">Error loading activity</div>';
    }
}

function updateStorageInfo(storage) {
    if (storage) {
        const totalMB = (storage.total / 1024 / 1024).toFixed(1);
        const pdfMB = (storage.pdfs / 1024 / 1024).toFixed(1);
        const imageMB = (storage.images / 1024 / 1024).toFixed(1);
        const tempMB = (storage.temp / 1024 / 1024).toFixed(1);
        
        document.getElementById('storageTotal').textContent = `${totalMB} MB`;
        document.getElementById('pdfStorage').textContent = `${pdfMB} MB`;
        document.getElementById('imageStorage').textContent = `${imageMB} MB`;
        document.getElementById('tempStorage').textContent = `${tempMB} MB`;
        
        // Update storage bars
        const total = storage.total || 1;
        document.querySelector('.pdf-fill').style.width = `${(storage.pdfs / total) * 100}%`;
        document.querySelector('.image-fill').style.width = `${(storage.images / total) * 100}%`;
        document.querySelector('.temp-fill').style.width = `${(storage.temp / total) * 100}%`;
    }
}



function refreshDashboard() {
    loadDashboardData();
    checkSystemStatus();
    loadRecentProjects();
    loadRecentActivity();
}

// Auto-refresh every 2 minutes
setInterval(refreshDashboard, 120000);
</script>