<?php
require_once __DIR__ . '/includes/app.php';
require_login();
require_roles(['Admin Audit']);
require_department_access($conn, 'senarai_maklum_balas_audit', 'update');

$feedbackId = (int) ($_POST['feedback_id'] ?? 0);
$catatanAudit = trim((string) ($_POST['catatan_audit'] ?? ''));

if ($feedbackId <= 0) {
    header('Location: senarai_maklum_balas_audit.php');
    exit();
}

$stmt = $conn->prepare("
    SELECT fb.id, fb.submitted_unit, fb.submitted_by, af.perkara
    FROM audit_feedbacks fb
    INNER JOIN audit_forms af ON af.id = fb.audit_form_id
    WHERE fb.id = ?
    LIMIT 1
");
$stmt->bind_param('i', $feedbackId);
$stmt->execute();
$feedback = $stmt->get_result()->fetch_assoc();

if (!$feedback) {
    header('Location: senarai_maklum_balas_audit.php');
    exit();
}

$updateStmt = $conn->prepare("
    UPDATE audit_feedbacks
    SET catatan_audit = ?, catatan_audit_by = ?, catatan_audit_at = NOW()
    WHERE id = ?
    LIMIT 1
");
$currentUserId = current_user_id();
$updateStmt->bind_param('sii', $catatanAudit, $currentUserId, $feedbackId);
$updateStmt->execute();

add_current_user_log($conn, 'Mengemaskini catatan audit untuk maklum balas audit: ' . ($feedback['perkara'] ?? 'Tidak Diketahui'));

$submittedUnit = trim((string) ($feedback['submitted_unit'] ?? ''));
if ($submittedUnit !== '' && $catatanAudit !== '') {
    $title = 'Catatan Audit Baharu';
    $message = 'Admin Audit telah memberi catatan audit untuk "' . ($feedback['perkara'] ?? 'Audit') . '": ' . $catatanAudit;
    $link = 'dashboard.php';
    create_notifications_for_unit($conn, $submittedUnit, 'catatan_audit', $title, $message, $link);
}

header('Location: dashboard.php?success=audit_note_saved');
exit();
