<?php
require __DIR__ . '/db.php';

$formId = $_GET['formId'] ?? '';
$ownerToken = $_GET['ownerToken'] ?? '';
if (!$formId || !$ownerToken) { http_response_code(400); exit('Missing fields'); }

try {
    $db = fill_db();
    $check = $db->prepare("SELECT owner_token, schema_json, title FROM fill_forms WHERE id = :id");
    $check->execute([':id' => $formId]);
    $form = $check->fetch();
    if (!$form) { http_response_code(404); exit('Not found'); }
    if ($form['owner_token'] !== $ownerToken) { http_response_code(403); exit('Forbidden'); }

    $schema = json_decode($form['schema_json'], true);
    $questions = $schema['questions'] ?? [];

    $stmt = $db->prepare("SELECT answers_json, submitted_at FROM fill_responses WHERE form_id = :id ORDER BY submitted_at ASC");
    $stmt->execute([':id' => $formId]);
    $rows = $stmt->fetchAll();

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . preg_replace('/[^a-z0-9\-_ ]/i', '', $form['title']) . '-responses.csv"');

    $out = fopen('php://output', 'w');
    $headerRow = ['Submitted at'];
    foreach ($questions as $q) { $headerRow[] = $q['label']; }
    fputcsv($out, $headerRow);

    foreach ($rows as $row) {
        $answers = json_decode($row['answers_json'], true);
        $line = [$row['submitted_at']];
        foreach ($questions as $q) {
            $val = $answers[$q['id']] ?? '';
            if (is_array($val)) $val = implode('; ', $val);
            $line[] = $val;
        }
        fputcsv($out, $line);
    }
    fclose($out);
} catch (Exception $e) {
    http_response_code(500);
    exit('Server error');
}
