<?php

namespace FleekDash\Controllers\Analytics;

use WP_Error;

/**
 * Analytics Exporter
 *
 * Handles analytics data export functionality
 *
 * @package FleekDash\Controllers\Analytics
 */
class AnalyticsExporter
{
    /**
     * Export data as CSV
     *
     * @param array $data Data to export
     * @param string $filename Filename for download
     * @return void (sends headers and exits)
     */
    public function exportAsCSV($data, $filename)
    {
        if (empty($data)) {
            return new WP_Error('no_data', 'No data to export', ['status' => 404]);
        }

        // Create CSV content
        $csv_content = '';
        $headers = array_keys($data[0]);

        // Add headers
        $csv_content .= implode(',', array_map(function($header) {
            return '"' . str_replace('"', '""', $header) . '"';
        }, $headers)) . "\n";

        // Add data rows
        foreach ($data as $row) {
            $csv_row = [];
            foreach ($headers as $header) {
                $value = $row[$header] ?? '';
                $csv_row[] = '"' . str_replace('"', '""', $value) . '"';
            }
            $csv_content .= implode(',', $csv_row) . "\n";
        }

        // Set headers for download
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . strlen($csv_content));
        header('Cache-Control: no-cache, must-revalidate');
        header('Expires: 0');

        echo $csv_content;
        exit;
    }

    /**
     * Export data as JSON
     *
     * @param array $data Data to export
     * @param string $filename Filename for download
     * @return void (sends headers and exits)
     */
    public function exportAsJSON($data, $filename)
    {
        $json_content = json_encode([
            'export_info' => [
                'generated_at' => \current_time('mysql'),
                'total_records' => count($data),
                'format' => 'json'
            ],
            'data' => $data
        ], JSON_PRETTY_PRINT);

        // Set headers for download
        header('Content-Type: application/json');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . strlen($json_content));
        header('Cache-Control: no-cache, must-revalidate');
        header('Expires: 0');

        echo $json_content;
        exit;
    }
}
