<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['POST']);
$user = hw_auth_user();
if (!$user) hw_json(['message' => 'Unauthorized'], 401);
$input = hw_input_json();
$answers = $input['answers'] ?? null;
if (!is_array($answers)) hw_json(['message' => 'Invalid form payload'], 422);

try {
    $pdo = hw_db();
    $stmt = $pdo->prepare('INSERT INTO intake_forms (user_id, answers) VALUES (?, JSON_OBJECT())');
    $stmt->execute([(int)$user['sub']]);
    $id = (int)$pdo->lastInsertId();

    // Update answers as JSON (ensure proper encoding)
    $stmt = $pdo->prepare('UPDATE intake_forms SET answers = ? WHERE id = ?');
    $stmt->execute([json_encode($answers, JSON_UNESCAPED_SLASHES), $id]);

    // Audit
    $pdo->prepare('INSERT INTO audit_logs (user_id, action, meta) VALUES (?, ?, JSON_OBJECT("intake_id", ?, "fields", JSON_ARRAY()))')
        ->execute([(int)$user['sub'], 'intake_submitted', $id]);

    hw_json(['message' => 'Intake submitted', 'id' => $id]);
} catch (Throwable $e) {
    hw_json(['message' => 'Server error', 'error' => $e->getMessage()], 500);
}
