<?php
require_once __DIR__ . '/../../config/secure_bootstrap.php';
header('Content-Type: application/json; charset=utf-8');

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Metode tidak valid');
    }

    $audit_id = intval($_POST['audit_id'] ?? 0);
    $finding_title = trim($_POST['finding_title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $severity = $_POST['severity'] ?? 'minor';
    $responsible_unit = trim($_POST['responsible_unit'] ?? '');
    $due_date = !empty($_POST['due_date']) ? $_POST['due_date'] : null;
    $recommendation = trim($_POST['recommendation'] ?? '');
    $status = $_POST['status'] ?? 'open';

    if ($audit_id <= 0 || $finding_title === '') {
        throw new Exception('Data tidak lengkap');
    }

    $stmt = $pdo->prepare("
        INSERT INTO audit_findings 
        (audit_id, finding_title, description, severity, recommendation, responsible_unit, due_date, status)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $audit_id,
        $finding_title,
        $description,
        $severity,
        $recommendation,
        $responsible_unit,
        $due_date,
        $status
    ]);

    echo json_encode(['success' => true, 'message' => 'Temuan berhasil ditambahkan']);
} catch (Throwable $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
