isLoggedIn()) { die('Unauthorized access'); } $db = Database::getInstance(); // Set headers for CSV download header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename="statistic_check_' . date('Y-m-d') . '.csv"'); // Create output stream $output = fopen('php://output', 'w'); // Add BOM for Excel UTF-8 compatibility fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF)); // Write headers $headers = ['Statistic Name', 'Combination', 'Target %', 'Panel %', 'Deviation %']; fputcsv($output, $headers); // Get all combinations data $query = $db->query(" SELECT s.name as statistic_name, sc.combination_values, sc.percentage as target_percentage, sc.actual_percentage as panel_percentage FROM statistics s JOIN statistic_combinations sc ON s.id = sc.statistic_id ORDER BY s.name, sc.id "); // Write data rows while ($row = $query->fetch_assoc()) { $target_percentage = floatval($row['target_percentage']); $panel_percentage = floatval($row['panel_percentage'] ?? 0); // Calculate deviation percentage $deviation = $target_percentage > 0 ? (($panel_percentage - $target_percentage) / $target_percentage) * 100 : 0; // Format the combination $values = json_decode($row['combination_values'], true); $combination = implode(' × ', $values); $csvRow = [ $row['statistic_name'], $combination, number_format($target_percentage, 2), number_format($panel_percentage, 2), number_format($deviation, 2) ]; fputcsv($output, $csvRow); } fclose($output); exit;