<?php
/**
 * API: Export Survey Data
 * Research Survey Management System
 */

require_once __DIR__ . '/../includes/functions.php';
requireAuth();

$surveyId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$format = isset($_GET['format']) ? $_GET['format'] : 'csv';

if (!$surveyId) {
    die('Survey ID required.');
}

$pdo = getDBConnection();
$survey = getSurveyWithQuestions($surveyId);

if (!$survey) {
    die('Survey not found.');
}

// Get all responses
$stmt = $pdo->prepare("
    SELECT sr.response_id, sr.completed_at, sr.time_spent_seconds,
           qr.question_id, qr.response_value, qr.response_numeric,
           q.question_text, q.question_type
    FROM survey_responses sr
    JOIN question_responses qr ON sr.response_id = qr.response_id
    JOIN survey_questions q ON qr.question_id = q.question_id
    WHERE sr.survey_id = :sid AND sr.status = 'completed'
    ORDER BY sr.response_id, q.question_order
");
$stmt->execute(['sid' => $surveyId]);
$rows = $stmt->fetchAll();

// Group by response
$responses = [];
foreach ($rows as $r) {
    $responses[$r['response_id']]['info'] = [
        'completed_at' => $r['completed_at'],
        'time_spent' => $r['time_spent_seconds']
    ];
    $responses[$r['response_id']]['answers'][$r['question_id']] = $r['response_numeric'] ?? $r['response_value'] ?? '';
}

if ($format === 'csv') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . preg_replace('/[^a-zA-Z0-9_]/', '_', $survey['title']) . '_export.csv"');
    
    $output = fopen('php://output', 'w');
    
    // Header row
    $headers = ['Response ID', 'Completed At', 'Time Spent (sec)'];
    foreach ($survey['questions'] as $q) {
        $headers[] = strip_tags($q['question_text']);
    }
    fputcsv($output, $headers);
    
    // Data rows
    foreach ($responses as $rid => $resp) {
        $row = [
            $rid,
            $resp['info']['completed_at'] ?? '',
            $resp['info']['time_spent'] ?? ''
        ];
        foreach ($survey['questions'] as $q) {
            $row[] = $resp['answers'][$q['question_id']] ?? '';
        }
        fputcsv($output, $row);
    }
    
    fclose($output);
    
} elseif ($format === 'excel') {
    // Simple HTML table export (opens in Excel)
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="' . preg_replace('/[^a-zA-Z0-9_]/', '_', $survey['title']) . '_export.xls"');
    
    echo '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel">';
    echo '<head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>Survey Data</x:Name></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>';
    echo '<body><table border="1">';
    
    // Header
    echo '<tr><th>Response ID</th><th>Completed At</th><th>Time Spent (sec)</th>';
    foreach ($survey['questions'] as $q) {
        echo '<th>' . htmlspecialchars(strip_tags($q['question_text'])) . '</th>';
    }
    echo '</tr>';
    
    // Data
    foreach ($responses as $rid => $resp) {
        echo '<tr>';
        echo '<td>' . $rid . '</td>';
        echo '<td>' . ($resp['info']['completed_at'] ?? '') . '</td>';
        echo '<td>' . ($resp['info']['time_spent'] ?? '') . '</td>';
        foreach ($survey['questions'] as $q) {
            echo '<td>' . htmlspecialchars($resp['answers'][$q['question_id']] ?? '') . '</td>';
        }
        echo '</tr>';
    }
    
    echo '</table></body></html>';
}

exit;