<?php
require_once __DIR__ . '/../config/cors.php';
require_once '../config/db.php';

header('Content-Type: application/json');

try {
    // Fetch all forms
    $stmt = $pdo->query("SELECT * FROM forms ORDER BY created_at DESC");
    $forms = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Fetch all attachments
    $stmtAtt = $pdo->query("SELECT * FROM form_attachments");
    $attachmentsRaw = $stmtAtt->fetchAll(PDO::FETCH_ASSOC);

    $attachments = [];
    foreach ($attachmentsRaw as $att) {
        $attachments[$att['form_id']][] = $att;
    }

    // Combine
    $data = [];
    foreach ($forms as $form) {
        $form['attachments'] = $attachments[$form['id']] ?? [];
        $data[] = $form;
    }

    echo json_encode(['status' => 'success', 'data' => $data]);

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
}
?>