<?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');
    }

    $id = intval($_POST['id'] ?? 0);
    if ($id <= 0) {
        throw new Exception('ID temuan tidak valid');
    }

    $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';

    // Update data sesuai skema tabel
    $stmt = $pdo->prepare("
        UPDATE audit_findings 
        SET finding_title = ?, description = ?, severity = ?, recommendation = ?, 
            responsible_unit = ?, due_date = ?, status = ?, 
            closed_at = CASE WHEN ? = 'closed' THEN NOW() ELSE NULL END
        WHERE id = ?
    ");
    $stmt->execute([
        $finding_title,
        $description,
        $severity,
        $recommendation,
        $responsible_unit,
        $due_date,
        $status,
        $status,
        $id
    ]);

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