<?php
require_once __DIR__ . '/includes/layout.php';
require_login();
require_department_access($conn, 'senarai_maklum_balas_audit', 'read');

$canRespondAudit = current_user_role() === 'Admin Audit';
$canViewAuditNote = current_user_role() === 'Admin Audit';

$feedbackId = (int) ($_GET['id'] ?? 0);
if ($feedbackId <= 0) {
    header('Location: senarai_maklum_balas_audit.php');
    exit();
}

$stmt = $conn->prepare("
    SELECT fb.id, fb.status_tindakan, fb.ringkasan, fb.maklum_balas, fb.catatan_audit, fb.catatan_audit_at,
           fb.attachment_path, fb.attachment_name, fb.created_at,
           af.perkara, f.nama, f.role, f.jabatan,
           audit_user.nama AS catatan_audit_nama
    FROM audit_feedbacks fb
    INNER JOIN audit_forms af ON af.id = fb.audit_form_id
    INNER JOIN users f ON f.id = fb.submitted_by
    LEFT JOIN users audit_user ON audit_user.id = fb.catatan_audit_by
    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();
}

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

$statusClass = 'perlu';
if (($feedback['status_tindakan'] ?? '') === 'Dalam Tindakan') {
    $statusClass = 'proses';
} elseif (($feedback['status_tindakan'] ?? '') === 'Selesai') {
    $statusClass = 'selesai';
}

$attachmentPath = trim((string) ($feedback['attachment_path'] ?? ''));
$attachmentName = trim((string) ($feedback['attachment_name'] ?? ''));
$attachmentStmt = $conn->prepare("
    SELECT attachment_path, attachment_name
    FROM audit_feedback_attachments
    WHERE audit_feedback_id = ?
    ORDER BY created_at DESC, id DESC
");
$attachmentStmt->bind_param('i', $feedbackId);
$attachmentStmt->execute();
$attachments = $attachmentStmt->get_result()->fetch_all(MYSQLI_ASSOC);
if (empty($attachments) && $attachmentPath !== '' && $attachmentName !== '') {
    $attachments[] = [
        'attachment_path' => $attachmentPath,
        'attachment_name' => $attachmentName,
    ];
}
render_layout_start('Detail Maklum Balas Audit - Dashboard Audit MAINPP');
?>
<style>
.feedback-status {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 10px;
    border-radius: 999px;
    font-size: 12px;
    font-weight: 700;
}
.feedback-status.perlu {
    background: #fee2e2;
    color: #b91c1c;
}
.feedback-status.proses {
    background: #fef3c7;
    color: #92400e;
}
.feedback-status.selesai {
    background: #dcfce7;
    color: #166534;
}
.audit-note-card {
    margin-top: 12px;
    border-top: 1px solid #e8eef5;
    padding-top: 14px;
}
.audit-note-meta {
    margin-top: 10px;
    font-size: 12px;
    color: #64748b;
}
</style>

<div class="content-card">
    <?php if (isset($_GET['success']) && $_GET['success'] === 'audit_note_saved'): ?>
    <div class="status-message status-success">Catatan Audit Berjaya Disimpan.</div>
    <?php endif; ?>
    <div style="display:flex; justify-content:space-between; gap:16px; flex-wrap:wrap; margin-bottom:22px; border-bottom:1px solid #e8eef5; padding-bottom:18px;">
        <div>
            <h3><i class="fa-solid fa-circle-info"></i> Detail Maklum Balas Audit</h3>
            <div class="button-row" style="margin-top:12px;">
                <span class="feedback-status <?= $statusClass ?>"><?= htmlspecialchars($feedback['status_tindakan']) ?></span>
            </div>
        </div>
    </div>

    <div class="form-grid">
        <div class="full-width"><label>Perkara Audit</label><input type="text" value="<?= htmlspecialchars($feedback['perkara']) ?>" readonly></div>
        <div><label>Nama</label><input type="text" value="<?= htmlspecialchars($feedback['nama']) ?>" readonly></div>
        <div><label>Bahagian / Unit</label><input type="text" value="<?= htmlspecialchars($feedback['jabatan']) ?>" readonly></div>
        <div class="full-width"><label>Ringkasan</label><input type="text" value="<?= htmlspecialchars($feedback['ringkasan']) ?>" readonly></div>
        <div class="full-width"><label>Maklum Balas</label><textarea rows="20" readonly><?= htmlspecialchars($feedback['maklum_balas']) ?></textarea></div>
        <div>
            <label>Lampiran</label>
            <?php if (!empty($attachments)): ?>
                <?php foreach ($attachments as $attachment): ?>
                <a href="<?= htmlspecialchars($attachment['attachment_path']) ?>" class="detail-link" onclick="openAttachmentPreview(event, '<?= htmlspecialchars($attachment['attachment_path'], ENT_QUOTES) ?>', '<?= htmlspecialchars($attachment['attachment_name'], ENT_QUOTES) ?>')"><?= htmlspecialchars($attachment['attachment_name']) ?></a><br>
                <?php endforeach; ?>
            <?php else: ?>
            <input type="text" value="-" readonly>
            <?php endif; ?>
        </div>
        <div><label>Tarikh Hantar</label><input type="text" value="<?= !empty($feedback['created_at']) ? date('d/m/Y h:i A', strtotime($feedback['created_at'])) : '-' ?>" readonly></div>
    </div>
    <?php if ($canViewAuditNote): ?>
    <div class="audit-note-card">
        <h3><i class="fa-solid fa-clipboard-pen"></i> Catatan Audit</h3>
        <?php if ($canRespondAudit): ?>
        <form method="POST" action="proses_catatan_audit.php">
            <input type="hidden" name="feedback_id" value="<?= (int) $feedback['id'] ?>">
            <div class="form-grid">
                <div class="full-width">
                    <label for="catatan_audit">Catatan Audit</label>
                    <textarea id="catatan_audit" name="catatan_audit" rows="15" placeholder="Masukkan semakan, ulasan, atau arahan lanjut pihak audit di sini."><?= htmlspecialchars((string) ($feedback['catatan_audit'] ?? '')) ?></textarea>
                </div>
            </div>
            <div class="button-row">
                <button type="submit" class="primary-btn">Simpan Catatan Audit</button>
            </div>
        </form>
        <?php else: ?>
        <div class="form-grid">
            <div class="full-width">
                <label>Catatan Audit</label>
                <textarea rows="6" readonly><?= htmlspecialchars((string) ($feedback['catatan_audit'] ?? '')) ?></textarea>
            </div>
        </div>
        <?php endif; ?>

        <?php if (!empty($feedback['catatan_audit_at'])): ?>
        <div class="audit-note-meta">
            Dikemaskini oleh <?= htmlspecialchars((string) ($feedback['catatan_audit_nama'] ?? 'Pihak Audit')) ?>
            pada <?= date('d/m/Y h:i A', strtotime((string) $feedback['catatan_audit_at'])) ?>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>
<?php render_layout_end(); ?>
