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="statistics_' . 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', 'Type', 'Attributes', 'Combination', 'Target %', 'Panel %', 'Deviation %', 'Created By', 'Created Date']; fputcsv($output, $headers); // Get statistics data with combinations $query = $db->query(" SELECT s.name as statistic_name, s.type, u.full_name as creator_name, DATE_FORMAT(s.created_at, '%Y-%m-%d %H:%i:%S') as formatted_date, GROUP_CONCAT(DISTINCT a.name ORDER BY sa.id) as attribute_names, sc.combination_values, sc.percentage as target_percentage, sc.actual_percentage FROM statistics s LEFT JOIN users u ON s.created_by = u.id JOIN statistic_attributes sa ON s.id = sa.statistic_id JOIN attributes a ON a.id = sa.attribute_id JOIN statistic_combinations sc ON s.id = sc.statistic_id GROUP BY s.id, sc.id ORDER BY s.name, sc.id "); // Write data rows while ($stat = $query->fetch_assoc()) { $targetPct = floatval($stat['target_percentage']); $actualPct = floatval($stat['actual_percentage'] ?? 0); $deviation = $targetPct > 0 ? (($actualPct - $targetPct) / $targetPct) * 100 : 0; // Format the combination values $combinationValues = json_decode($stat['combination_values'], true); $combinationText = implode(' × ', $combinationValues); $row = [ $stat['statistic_name'], $stat['type'], $stat['attribute_names'], $combinationText, number_format($targetPct, 2), number_format($actualPct, 2), number_format($deviation, 2), $stat['creator_name'], $stat['formatted_date'] ]; fputcsv($output, $row); } fclose($output); exit;