<?php
require_once 'includes/db.php';
// The route protection in index.php ensures only owner and manager can access this

$company_id = $_SESSION['company_id'] ?? 0;
?>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<div style="width: 100%; margin: 0 auto; padding: 0 0.5rem;">
    <!-- Report Navigation Tabs -->
    <div style="display: flex; gap: 1rem; border-bottom: 1px solid var(--border); margin-bottom: 2rem; overflow-x: auto;">
        <button id="tab-material_consumption" class="btn tab-btn active" onclick="switchReport('material_consumption')" style="background: transparent; color: var(--primary); border-bottom: 3px solid var(--primary); border-radius: 0; padding-bottom: 1rem; font-weight: 700; white-space: nowrap;">
            <i class="fas fa-boxes"></i> Material Consumption
        </button>
        <button id="tab-labor_cost" class="btn tab-btn" onclick="switchReport('labor_cost')" style="background: transparent; color: var(--text-muted); border-bottom: 3px solid transparent; border-radius: 0; padding-bottom: 1rem; font-weight: 600; white-space: nowrap;">
            <i class="fas fa-user-clock"></i> Labor Cost
        </button>
        <button id="tab-production_cost" class="btn tab-btn" onclick="switchReport('production_cost')" style="background: transparent; color: var(--text-muted); border-bottom: 3px solid transparent; border-radius: 0; padding-bottom: 1rem; font-weight: 600; white-space: nowrap;">
            <i class="fas fa-industry"></i> Production Cost
        </button>
        <button id="tab-product_build_cost" class="btn tab-btn" onclick="switchReport('product_build_cost')" style="background: transparent; color: var(--text-muted); border-bottom: 3px solid transparent; border-radius: 0; padding-bottom: 1rem; font-weight: 600; white-space: nowrap;">
            <i class="fas fa-tags"></i> Product Build Cost
        </button>
    </div>

    <!-- Report Container -->
    <div class="card" style="padding: 1.5rem;">
        <div style="display: flex; justify-content: space-between; align-items: flex-end; margin-bottom: 1.5rem; flex-wrap: wrap; gap: 1.5rem;">
            <div style="flex: 1; min-width: 280px;">
                <h2 id="report-title" style="font-size: 1.25rem; font-weight: 800; color: var(--text-main); margin-bottom: 0.25rem;">Material Consumption & Expenditure</h2>
                <p id="report-description" style="font-size: 0.85rem; color: var(--text-muted);">View the total quantity and financial cost of raw materials used in completed lines.</p>
            </div>
            <div style="display: flex; gap: 1rem; align-items: flex-end; justify-content: flex-end; flex: 1; min-width: 200px;">
                <div class="form-group" style="margin: 0; width: 220px;">
                    <label class="form-label" style="font-size: 0.75rem;">Time Period</label>
                    <select id="filter-preset" class="form-control" onchange="applyPresetFilter()">
                        <option value="daily">Daily (Today)</option>
                        <option value="weekly">Weekly (Last 7 Days)</option>
                        <option value="monthly" selected>Monthly (Last 30 Days)</option>
                        <option value="yearly">Yearly (Last 365 Days)</option>
                    </select>
                </div>
                <input type="hidden" id="filter-start" value="<?php echo date('Y-m-d', strtotime('-30 days')); ?>">
                <input type="hidden" id="filter-end" value="<?php echo date('Y-m-d'); ?>">
                <button id="btn-generate" style="display: none;"></button>
            </div>
        </div>

        <div id="summary-cards-container" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 1.5rem;">
            <!-- Loaded Dynamically -->
        </div>

        <!-- Chart Section (for Production Cost Breakdown) -->
        <div id="chart-section-container" style="display: none; margin-bottom: 2rem; background: var(--bg-card); padding: 1.5rem; border: 1px solid var(--border); border-radius: 16px;">
            <h3 style="font-size: 1rem; font-weight: 700; color: var(--text-main); margin-bottom: 1rem;">Cost Breakdown vs. Cost Per Unit</h3>
            <div style="position: relative; height: 350px; width: 100%;">
                <canvas id="production-cost-chart"></canvas>
            </div>
        </div>

        <div style="overflow-x: auto;">
            <table class="table" style="width: 100%;">
                <thead id="report-table-head">
                    <!-- Loaded Dynamically -->
                </thead>
                <tbody id="report-table-body">
                    <tr><td colspan="5" style="text-align: center; padding: 2rem; color: var(--text-muted);"><i class="fas fa-spinner fa-spin"></i> Loading report data...</td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
const SYSTEM_CURRENCY = '<?php echo $_SESSION['company_currency'] ?? '$'; ?>';
let currentReport = 'material_consumption';
let productionChartInstance = null;

function formatDate(date) {
    const yyyy = date.getFullYear();
    let mm = date.getMonth() + 1;
    let dd = date.getDate();
    if (dd < 10) dd = '0' + dd;
    if (mm < 10) mm = '0' + mm;
    return yyyy + '-' + mm + '-' + dd;
}

function applyPresetFilter() {
    const preset = document.getElementById('filter-preset').value;
    const startInput = document.getElementById('filter-start');
    const endInput = document.getElementById('filter-end');
    
    const today = new Date();
    let start = new Date();
    
    if (preset === 'daily') {
        // start is today
    } else if (preset === 'weekly') {
        start.setDate(today.getDate() - 7);
    } else if (preset === 'monthly') {
        start.setDate(today.getDate() - 30);
    } else if (preset === 'yearly') {
        start.setDate(today.getDate() - 365);
    }
    
    startInput.value = formatDate(start);
    endInput.value = formatDate(today);
    
    loadReport();
}

function switchReport(type) {
    currentReport = type;
    
    // Toggle active classes on tab buttons
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
        btn.style.color = 'var(--text-muted)';
        btn.style.borderBottomColor = 'transparent';
        btn.style.fontWeight = '600';
    });
    
    const activeTab = document.getElementById(`tab-${type}`);
    if (activeTab) {
        activeTab.classList.add('active');
        activeTab.style.color = 'var(--primary)';
        activeTab.style.borderBottomColor = 'var(--primary)';
        activeTab.style.fontWeight = '700';
    }
    
    // Show/hide chart container
    const chartContainer = document.getElementById('chart-section-container');
    if (type === 'production_cost') {
        chartContainer.style.display = 'block';
    } else {
        chartContainer.style.display = 'none';
        if (productionChartInstance) {
            productionChartInstance.destroy();
            productionChartInstance = null;
        }
    }
    
    // Update title and description
    const titleEl = document.getElementById('report-title');
    const descEl = document.getElementById('report-description');
    
    if (type === 'material_consumption') {
        titleEl.innerText = 'Material Consumption & Expenditure';
        descEl.innerText = 'View the total quantity and financial cost of raw materials used in completed lines.';
    } else if (type === 'labor_cost') {
        titleEl.innerText = 'Employee Productivity & Labor Cost Analysis';
        descEl.innerText = 'View performance and wage summary per employee across completed production jobs.';
    } else if (type === 'production_cost') {
        titleEl.innerText = 'Production Run Cost Breakdown';
        descEl.innerText = 'Compare labor vs. material costs per production run and view average cost per unit.';
    } else if (type === 'product_build_cost') {
        titleEl.innerText = 'Product Build-Cost Average & Margins';
        descEl.innerText = 'Analyze manufacturing averages, selling prices, and profit margins per garment style.';
    }
    
    loadReport();
}

function renderProductionCostChart(data) {
    const ctx = document.getElementById('production-cost-chart').getContext('2d');
    
    if (productionChartInstance) {
        productionChartInstance.destroy();
    }
    
    // Sort chronological (oldest to newest) for chart timeline
    const chartData = [...data].reverse();
    
    const labels = chartData.map(item => item.line_name);
    
    const laborCosts = chartData.map(item => {
        const val = parseFloat(item.total_labor_cost || 0);
        return val > 0 ? val : null;
    });
    const materialCosts = chartData.map(item => {
        const val = parseFloat(item.total_material_cost || 0);
        return val > 0 ? val : null;
    });
    const costsPerUnit = chartData.map(item => parseFloat(item.cost_per_unit || 0));
    
    productionChartInstance = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [
                {
                    label: 'Labor Cost',
                    data: laborCosts,
                    backgroundColor: '#7c3aed', // Purple/Indigo
                    stack: 'costStack',
                    yAxisID: 'y',
                    minBarLength: 8
                },
                {
                    label: 'Material Cost',
                    data: materialCosts,
                    backgroundColor: '#10b981', // Emerald/Green
                    stack: 'costStack',
                    yAxisID: 'y',
                    minBarLength: 8
                },
                {
                    label: 'Cost Per Unit',
                    data: costsPerUnit,
                    type: 'line',
                    borderColor: '#f59e0b', // Warning Orange
                    borderWidth: 3,
                    pointBackgroundColor: '#f59e0b',
                    pointRadius: 4,
                    fill: false,
                    tension: 0.3,
                    yAxisID: 'y1'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false,
            },
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        color: getComputedStyle(document.documentElement).getPropertyValue('--text-main').trim() || '#1f2937',
                        font: {
                            family: 'Outfit, Inter, sans-serif',
                            weight: '600'
                        }
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            let label = context.dataset.label || '';
                            if (label) {
                                label += ': ';
                            }
                            if (context.parsed.y !== null) {
                                label += SYSTEM_CURRENCY + context.parsed.y.toFixed(2);
                            }
                            return label;
                        }
                    }
                }
            },
            scales: {
                x: {
                    stacked: true,
                    grid: {
                        display: false
                    },
                    ticks: {
                        color: getComputedStyle(document.documentElement).getPropertyValue('--text-muted').trim() || '#6b7280',
                        font: {
                            family: 'Outfit, Inter, sans-serif'
                        }
                    }
                },
                y: {
                    stacked: true,
                    position: 'left',
                    grid: {
                        color: getComputedStyle(document.documentElement).getPropertyValue('--border').trim() || '#e5e7eb'
                    },
                    title: {
                        display: true,
                        text: 'Total Cost (' + SYSTEM_CURRENCY + ')',
                        color: getComputedStyle(document.documentElement).getPropertyValue('--text-main').trim() || '#1f2937',
                        font: {
                            family: 'Outfit, Inter, sans-serif',
                            weight: '600'
                        }
                    },
                    ticks: {
                        color: getComputedStyle(document.documentElement).getPropertyValue('--text-muted').trim() || '#6b7280',
                        font: {
                            family: 'Outfit, Inter, sans-serif'
                        },
                        callback: function(value) {
                            return SYSTEM_CURRENCY + value;
                        }
                    }
                },
                y1: {
                    position: 'right',
                    grid: {
                        drawOnChartArea: false
                    },
                    title: {
                        display: true,
                        text: 'Cost Per Unit (' + SYSTEM_CURRENCY + ')',
                        color: '#f59e0b',
                        font: {
                            family: 'Outfit, Inter, sans-serif',
                            weight: '600'
                        }
                    },
                    ticks: {
                        color: '#f59e0b',
                        font: {
                            family: 'Outfit, Inter, sans-serif'
                        },
                        callback: function(value) {
                            return SYSTEM_CURRENCY + value.toFixed(2);
                        }
                    }
                }
            }
        }
    });
}

async function loadReport() {
    const btn = document.getElementById('btn-generate');
    const tbody = document.getElementById('report-table-body');
    const thead = document.getElementById('report-table-head');
    const cardsContainer = document.getElementById('summary-cards-container');
    const start = document.getElementById('filter-start').value;
    const end = document.getElementById('filter-end').value;
    
    btn.classList.add('btn-loading');
    
    const getColsCount = () => {
        if (currentReport === 'material_consumption') return 5;
        if (currentReport === 'labor_cost') return 4;
        if (currentReport === 'production_cost') return 8;
        if (currentReport === 'product_build_cost') return 8;
        return 4;
    };
    const cols = getColsCount();
    
    // Set headers and loading states
    if (currentReport === 'material_consumption') {
        thead.innerHTML = `
            <tr>
                <th>Material</th>
                <th>SKU</th>
                <th style="text-align: right;">Avg. Unit Price (${SYSTEM_CURRENCY})</th>
                <th style="text-align: right;">Total Quantity Used</th>
                <th style="text-align: right;">Total Cost (Subtotal) (${SYSTEM_CURRENCY})</th>
            </tr>
        `;
        tbody.innerHTML = '<tr><td colspan="5" style="text-align: center; padding: 2rem; color: var(--text-muted);"><i class="fas fa-spinner fa-spin"></i> Generating report...</td></tr>';
    } else if (currentReport === 'labor_cost') {
        thead.innerHTML = `
            <tr>
                <th>Employee Name</th>
                <th style="text-align: right;">Total Hours Logged</th>
                <th style="text-align: right;">Avg. Hourly Rate (${SYSTEM_CURRENCY})</th>
                <th style="text-align: right;">Total Wages Paid (${SYSTEM_CURRENCY})</th>
            </tr>
        `;
        tbody.innerHTML = '<tr><td colspan="4" style="text-align: center; padding: 2rem; color: var(--text-muted);"><i class="fas fa-spinner fa-spin"></i> Generating report...</td></tr>';
    } else if (currentReport === 'production_cost') {
        thead.innerHTML = `
            <tr>
                <th>Run / Line Name</th>
                <th>Finished At</th>
                <th>Products Produced</th>
                <th style="text-align: right;">Material Cost (${SYSTEM_CURRENCY})</th>
                <th style="text-align: right;">Labor Cost (${SYSTEM_CURRENCY})</th>
                <th style="text-align: right;">Total Cost (${SYSTEM_CURRENCY})</th>
                <th style="text-align: right;">Units (Total / Defect-Free)</th>
                <th style="text-align: right;">Cost Per Unit (${SYSTEM_CURRENCY})</th>
            </tr>
        `;
        tbody.innerHTML = '<tr><td colspan="8" style="text-align: center; padding: 2rem; color: var(--text-muted);"><i class="fas fa-spinner fa-spin"></i> Generating report...</td></tr>';
    } else if (currentReport === 'product_build_cost') {
        thead.innerHTML = `
            <tr>
                <th>Product Name</th>
                <th>SKU</th>
                <th style="text-align: right;">Total Batches</th>
                <th style="text-align: right;">Units Produced</th>
                <th style="text-align: right;">Avg. Labor Time</th>
                <th style="text-align: right;">Avg. Labor Cost (${SYSTEM_CURRENCY})</th>
                <th style="text-align: right;">Avg. Material Cost (${SYSTEM_CURRENCY})</th>
                <th style="text-align: right;">Avg. Total Build Cost (${SYSTEM_CURRENCY})</th>
            </tr>
        `;
        tbody.innerHTML = '<tr><td colspan="8" style="text-align: center; padding: 2rem; color: var(--text-muted);"><i class="fas fa-spinner fa-spin"></i> Generating report...</td></tr>';
    }
    
    try {
        const basePath = window.APP_CONFIG ? window.APP_CONFIG.BASE_PATH : '/';
        const res = await fetch(`${basePath}api/reports.php?action=${currentReport}&start_date=${start}&end_date=${end}`);
        const json = await res.json();
        
        if (json.success) {
            if (json.data.length === 0) {
                tbody.innerHTML = `<tr><td colspan="${cols}" style="text-align: center; padding: 2rem; color: var(--text-muted);">No records found in this period.</td></tr>`;
                
                if (productionChartInstance) {
                    productionChartInstance.destroy();
                    productionChartInstance = null;
                }
                
                if (currentReport === 'material_consumption') {
                    cardsContainer.innerHTML = `
                        <div style="background: rgba(124, 58, 237, 0.05); border: 1px solid rgba(124, 58, 237, 0.2); padding: 1rem; border-radius: 12px;">
                            <div style="font-size: 0.7rem; color: var(--primary); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Total Material Cost (${SYSTEM_CURRENCY})</div>
                            <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">0.00</div>
                        </div>
                        <div style="background: rgba(16, 185, 129, 0.05); border: 1px solid rgba(16, 185, 129, 0.2); padding: 1rem; border-radius: 12px;">
                            <div style="font-size: 0.7rem; color: var(--success); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Unique Materials Used</div>
                            <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">0</div>
                        </div>
                    `;
                } else if (currentReport === 'labor_cost') {
                    cardsContainer.innerHTML = `
                        <div style="background: rgba(124, 58, 237, 0.05); border: 1px solid rgba(124, 58, 237, 0.2); padding: 1rem; border-radius: 12px;">
                            <div style="font-size: 0.7rem; color: var(--primary); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Total Labor Cost (${SYSTEM_CURRENCY})</div>
                            <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">0.00</div>
                        </div>
                        <div style="background: rgba(16, 185, 129, 0.05); border: 1px solid rgba(16, 185, 129, 0.2); padding: 1rem; border-radius: 12px;">
                            <div style="font-size: 0.7rem; color: var(--success); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Total Hours Logged</div>
                            <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">0.00 <span style="font-size: 0.8rem; font-weight: 500; color: var(--text-muted);">hrs</span></div>
                        </div>
                        <div style="background: rgba(245, 158, 11, 0.05); border: 1px solid rgba(245, 158, 11, 0.2); padding: 1rem; border-radius: 12px;">
                            <div style="font-size: 0.7rem; color: var(--warning); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Active Staff Count</div>
                            <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">0</div>
                        </div>
                    `;
                } else if (currentReport === 'production_cost') {
                    cardsContainer.innerHTML = `
                        <div style="background: rgba(124, 58, 237, 0.05); border: 1px solid rgba(124, 58, 237, 0.2); padding: 1rem; border-radius: 12px;">
                            <div style="font-size: 0.7rem; color: var(--primary); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Total Production Cost (${SYSTEM_CURRENCY})</div>
                            <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">0.00</div>
                        </div>
                        <div style="background: rgba(16, 185, 129, 0.05); border: 1px solid rgba(16, 185, 129, 0.2); padding: 1rem; border-radius: 12px;">
                            <div style="font-size: 0.7rem; color: var(--success); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Total Units Produced</div>
                            <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">0</div>
                        </div>
                        <div style="background: rgba(245, 158, 11, 0.05); border: 1px solid rgba(245, 158, 11, 0.2); padding: 1rem; border-radius: 12px;">
                            <div style="font-size: 0.7rem; color: var(--warning); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Avg Cost Per Unit (${SYSTEM_CURRENCY})</div>
                            <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">0.00</div>
                        </div>
                    `;
                } else if (currentReport === 'product_build_cost') {
                    cardsContainer.innerHTML = `
                        <div style="background: rgba(124, 58, 237, 0.05); border: 1px solid rgba(124, 58, 237, 0.2); padding: 1rem; border-radius: 12px;">
                            <div style="font-size: 0.7rem; color: var(--primary); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Total Styles Manufactured</div>
                            <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">0</div>
                        </div>
                        <div style="background: rgba(16, 185, 129, 0.05); border: 1px solid rgba(16, 185, 129, 0.2); padding: 1rem; border-radius: 12px;">
                            <div style="font-size: 0.7rem; color: var(--success); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Total Output</div>
                            <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">0 <span style="font-size: 0.8rem; font-weight: 500; color: var(--text-muted);">pcs</span></div>
                        </div>
                        <div style="background: rgba(245, 158, 11, 0.05); border: 1px solid rgba(245, 158, 11, 0.2); padding: 1rem; border-radius: 12px;">
                            <div style="font-size: 0.7rem; color: var(--warning); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Avg Global Unit Cost (${SYSTEM_CURRENCY})</div>
                            <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">0.00</div>
                        </div>
                    `;
                }
                return;
            }
            
            let html = '';
            
            if (currentReport === 'material_consumption') {
                let grandTotal = 0;
                json.data.forEach(item => {
                    const totalCost = parseFloat(item.total_cost);
                    grandTotal += totalCost;
                    
                    html += `
                        <tr>
                            <td style="font-weight: 700; color: var(--text-main);">${item.name}</td>
                            <td style="font-family: monospace; font-size: 0.85rem; color: var(--text-muted);">${item.sku}</td>
                            <td style="text-align: right; color: var(--text-muted);">${parseFloat(item.avg_unit_price).toFixed(2)}</td>
                            <td style="text-align: right; font-weight: 700;">${parseFloat(item.total_quantity).toFixed(2)} <small style="color: var(--text-muted); font-size: 0.7rem;">${item.unit}</small></td>
                            <td style="text-align: right; font-weight: 800; color: var(--primary);">${totalCost.toFixed(2)}</td>
                        </tr>
                    `;
                });
                tbody.innerHTML = html;
                
                cardsContainer.innerHTML = `
                    <div style="background: rgba(124, 58, 237, 0.05); border: 1px solid rgba(124, 58, 237, 0.2); padding: 1rem; border-radius: 12px;">
                        <div style="font-size: 0.7rem; color: var(--primary); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Total Material Cost (${SYSTEM_CURRENCY})</div>
                        <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">${grandTotal.toFixed(2)}</div>
                    </div>
                    <div style="background: rgba(16, 185, 129, 0.05); border: 1px solid rgba(16, 185, 129, 0.2); padding: 1rem; border-radius: 12px;">
                        <div style="font-size: 0.7rem; color: var(--success); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Unique Materials Used</div>
                        <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">${json.data.length}</div>
                    </div>
                `;
            } else if (currentReport === 'labor_cost') {
                let grandTotalCost = 0;
                let grandTotalHours = 0;
                
                json.data.forEach(item => {
                    const totalCost = parseFloat(item.total_cost);
                    const totalHours = parseFloat(item.total_hours);
                    grandTotalCost += totalCost;
                    grandTotalHours += totalHours;
                    
                    html += `
                        <tr>
                            <td style="font-weight: 700; color: var(--text-main);">${item.employee_name}</td>
                            <td style="text-align: right; font-weight: 700; color: var(--text-main);">${totalHours.toFixed(2)} <span style="font-size: 0.75rem; color: var(--text-muted); font-weight: 500;">hrs</span></td>
                            <td style="text-align: right; color: var(--text-muted);">${parseFloat(item.avg_hourly_rate).toFixed(2)}</td>
                            <td style="text-align: right; font-weight: 800; color: var(--primary);">${totalCost.toFixed(2)}</td>
                        </tr>
                    `;
                });
                tbody.innerHTML = html;
                
                cardsContainer.innerHTML = `
                    <div style="background: rgba(124, 58, 237, 0.05); border: 1px solid rgba(124, 58, 237, 0.2); padding: 1rem; border-radius: 12px;">
                        <div style="font-size: 0.7rem; color: var(--primary); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Total Labor Cost (${SYSTEM_CURRENCY})</div>
                        <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">${grandTotalCost.toFixed(2)}</div>
                    </div>
                    <div style="background: rgba(16, 185, 129, 0.05); border: 1px solid rgba(16, 185, 129, 0.2); padding: 1rem; border-radius: 12px;">
                        <div style="font-size: 0.7rem; color: var(--success); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Total Hours Logged</div>
                        <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">${grandTotalHours.toFixed(2)} <span style="font-size: 0.8rem; font-weight: 500; color: var(--text-muted);">hrs</span></div>
                    </div>
                    <div style="background: rgba(245, 158, 11, 0.05); border: 1px solid rgba(245, 158, 11, 0.2); padding: 1rem; border-radius: 12px;">
                        <div style="font-size: 0.7rem; color: var(--warning); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Active Staff Count</div>
                        <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">${json.data.length}</div>
                    </div>
                `;
            } else if (currentReport === 'production_cost') {
                let grandTotalCost = 0;
                let grandTotalUnits = 0;
                
                json.data.forEach(item => {
                    const matCost = parseFloat(item.total_material_cost || 0);
                    const labCost = parseFloat(item.total_labor_cost || 0);
                    const totalCost = parseFloat(item.grand_total_cost || 0);
                    const units = parseInt(item.total_units_produced || 0);
                    const unitsNoDefect = parseInt(item.total_units_produced_nodefects || 0);
                    const cpu = parseFloat(item.cost_per_unit || 0);
                    
                    grandTotalCost += totalCost;
                    grandTotalUnits += units;
                    
                    const finishedDate = new Date(item.finished_at).toLocaleString();
                    
                    html += `
                        <tr>
                            <td style="font-weight: 700; color: var(--text-main);">${item.line_name}</td>
                            <td style="color: var(--text-muted); font-size: 0.85rem;">${finishedDate}</td>
                            <td style="color: var(--text-main); font-size: 0.85rem;">${item.products_produced || '-'}</td>
                            <td style="text-align: right; color: var(--text-muted);">${matCost.toFixed(2)}</td>
                            <td style="text-align: right; color: var(--text-muted);">${labCost.toFixed(2)}</td>
                            <td style="text-align: right; font-weight: 700; color: var(--text-main);">${totalCost.toFixed(2)}</td>
                            <td style="text-align: right; font-weight: 700; color: var(--text-main);">${units} <span style="font-size: 0.75rem; color: var(--success); font-weight: 600; margin-left: 0.25rem;">(${unitsNoDefect} OK)</span></td>
                            <td style="text-align: right; font-weight: 800; color: var(--primary);">${cpu.toFixed(2)}</td>
                        </tr>
                    `;
                });
                tbody.innerHTML = html;
                
                const avgCpu = grandTotalUnits > 0 ? (grandTotalCost / grandTotalUnits) : 0;
                
                cardsContainer.innerHTML = `
                    <div style="background: rgba(124, 58, 237, 0.05); border: 1px solid rgba(124, 58, 237, 0.2); padding: 1rem; border-radius: 12px;">
                        <div style="font-size: 0.7rem; color: var(--primary); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Total Production Cost (${SYSTEM_CURRENCY})</div>
                        <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">${grandTotalCost.toFixed(2)}</div>
                    </div>
                    <div style="background: rgba(16, 185, 129, 0.05); border: 1px solid rgba(16, 185, 129, 0.2); padding: 1rem; border-radius: 12px;">
                        <div style="font-size: 0.7rem; color: var(--success); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Total Units Produced</div>
                        <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">${grandTotalUnits}</div>
                    </div>
                    <div style="background: rgba(245, 158, 11, 0.05); border: 1px solid rgba(245, 158, 11, 0.2); padding: 1rem; border-radius: 12px;">
                        <div style="font-size: 0.7rem; color: var(--warning); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Avg Cost Per Unit (${SYSTEM_CURRENCY})</div>
                        <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">${avgCpu.toFixed(2)}</div>
                    </div>
                `;
                
                renderProductionCostChart(json.data);
            } else if (currentReport === 'product_build_cost') {
                let grandTotalCost = 0;
                let grandTotalUnits = 0;
                
                json.data.forEach(item => {
                    const runs = parseInt(item.total_runs || 0);
                    const qty = parseInt(item.total_quantity_produced || 0);
                    const laborHours = parseFloat(item.avg_labor_hours_per_unit || 0);
                    const laborCost = parseFloat(item.avg_labor_cost_per_unit || 0);
                    const matCost = parseFloat(item.avg_material_cost_per_unit || 0);
                    const buildCost = parseFloat(item.avg_total_build_cost || 0);
                    
                    grandTotalCost += (buildCost * qty);
                    grandTotalUnits += qty;
                    
                    html += `
                        <tr>
                            <td style="font-weight: 700; color: var(--text-main);">${item.product_name}</td>
                            <td style="font-family: monospace; font-size: 0.85rem; color: var(--text-muted);">${item.product_sku}</td>
                            <td style="text-align: right; font-weight: 600;">${runs}</td>
                            <td style="text-align: right; font-weight: 600;">${qty} <span style="font-size: 0.75rem; color: var(--text-muted); font-weight: 500;">pcs</span></td>
                            <td style="text-align: right; color: var(--text-muted);">${laborHours.toFixed(2)} <span style="font-size: 0.75rem; color: var(--text-muted);">hrs/pc</span></td>
                            <td style="text-align: right; color: var(--text-muted);">${laborCost.toFixed(2)}</td>
                            <td style="text-align: right; color: var(--text-muted);">${matCost.toFixed(2)}</td>
                            <td style="text-align: right; font-weight: 700; color: var(--text-main);">${buildCost.toFixed(2)}</td>
                        </tr>
                    `;
                });
                tbody.innerHTML = html;
                
                const globalAvgUnitCost = grandTotalUnits > 0 ? (grandTotalCost / grandTotalUnits) : 0;
                
                cardsContainer.innerHTML = `
                    <div style="background: rgba(124, 58, 237, 0.05); border: 1px solid rgba(124, 58, 237, 0.2); padding: 1rem; border-radius: 12px;">
                        <div style="font-size: 0.7rem; color: var(--primary); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Total Styles Manufactured</div>
                        <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">${json.data.length}</div>
                    </div>
                    <div style="background: rgba(16, 185, 129, 0.05); border: 1px solid rgba(16, 185, 129, 0.2); padding: 1rem; border-radius: 12px;">
                        <div style="font-size: 0.7rem; color: var(--success); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Total Output</div>
                        <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">${grandTotalUnits} <span style="font-size: 0.8rem; font-weight: 500; color: var(--text-muted);">pcs</span></div>
                    </div>
                    <div style="background: rgba(245, 158, 11, 0.05); border: 1px solid rgba(245, 158, 11, 0.2); padding: 1rem; border-radius: 12px;">
                        <div style="font-size: 0.7rem; color: var(--warning); text-transform: uppercase; font-weight: 800; margin-bottom: 0.25rem;">Avg Global Unit Cost (${SYSTEM_CURRENCY})</div>
                        <div style="font-size: 1.5rem; font-weight: 900; color: var(--text-main);">${globalAvgUnitCost.toFixed(2)}</div>
                    </div>
                `;
            }
            
        } else {
            tbody.innerHTML = `<tr><td colspan="${cols}" style="text-align: center; padding: 2rem; color: var(--danger);">${json.message || 'Error loading report'}</td></tr>`;
        }
    } catch (e) {
        tbody.innerHTML = `<tr><td colspan="${cols}" style="text-align: center; padding: 2rem; color: var(--danger);">Failed to communicate with server.</td></tr>`;
    } finally {
        btn.classList.remove('btn-loading');
    }
}

document.addEventListener('DOMContentLoaded', loadReport);
</script>
