<?php
require_once __DIR__ . '/includes/layout.php';
require_login();
require_roles(['Pengguna Biasa', 'Admin Audit', 'Pentadbir Sistem']);
require_department_access($conn, 'senarai_maklumat_audit', 'read');

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

$assignFeedbackStatusMap = [];
$assignStatusStmt = $conn->query("
    SELECT audit_form_id, submitted_unit, created_at, updated_at
    FROM audit_feedbacks
");
if ($assignStatusStmt) {
    while ($statusRow = $assignStatusStmt->fetch_assoc()) {
        $auditFormId = (int) ($statusRow['audit_form_id'] ?? 0);
        $submittedUnit = trim((string) ($statusRow['submitted_unit'] ?? ''));
        if ($auditFormId <= 0 || $submittedUnit === '') {
            continue;
        }

        $hasUpdated = strtotime((string) ($statusRow['updated_at'] ?? '')) > strtotime((string) ($statusRow['created_at'] ?? ''));
        if (!isset($assignFeedbackStatusMap[$auditFormId])) {
            $assignFeedbackStatusMap[$auditFormId] = [];
        }

        if ($hasUpdated) {
            $assignFeedbackStatusMap[$auditFormId][$submittedUnit] = 'updated';
            continue;
        }

        if (!isset($assignFeedbackStatusMap[$auditFormId][$submittedUnit])) {
            $assignFeedbackStatusMap[$auditFormId][$submittedUnit] = 'submitted';
        }
    }
}

$stmt = $conn->prepare("
    SELECT af.id, af.perkara, af.tarikh_mula, af.tarikh_akhir, af.remarks, af.created_at,
           GROUP_CONCAT(afa.assigned_unit ORDER BY afa.assigned_unit SEPARATOR '||') AS assigned_units
    FROM audit_forms af
    LEFT JOIN audit_form_assignments afa ON afa.audit_form_id = af.id
    WHERE af.id = ?
    GROUP BY af.id
    LIMIT 1
");
$stmt->bind_param('i', $auditId);
$stmt->execute();
$audit = $stmt->get_result()->fetch_assoc();

if (!$audit) {
    header('Location: senarai_maklumat_audit.php');
    exit();
}

$assignedUnits = array_values(array_filter(array_map('trim', explode('||', (string) ($audit['assigned_units'] ?? '')))));

$attachmentStmt = $conn->prepare("
    SELECT attachment_path, attachment_name
    FROM audit_form_attachments
    WHERE audit_form_id = ?
    ORDER BY created_at DESC, id DESC
");
$attachmentStmt->bind_param('i', $auditId);
$attachmentStmt->execute();
$attachments = $attachmentStmt->get_result()->fetch_all(MYSQLI_ASSOC);

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

render_layout_start('Detail Maklumat Audit - Dashboard Audit MAINPP');
?>
<style>
.assign-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
}
.assign-pill {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 7px 12px;
    border-radius: 999px;
    font-size: 13px;
    font-weight: 700;
    line-height: 1.2;
}
.assign-pill.assign-pending {
    background: #fee2e2;
    color: #b91c1c;
}
.assign-pill.assign-submitted {
    background: #dcfce7;
    color: #166534;
}
.assign-pill.assign-updated {
    background: #fef3c7;
    color: #92400e;
}
.attachment-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
}
.attachment-link {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: #0d6efd;
    font-weight: 700;
    text-decoration: none;
    width: fit-content;
}
.attachment-link:hover {
    text-decoration: underline;
}
</style>

<div class="content-card">
    <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 Maklumat Audit</h3>
        </div>
    </div>

    <div class="form-grid">
        <div class="full-width"><label>Perkara</label><input type="text" value="<?= htmlspecialchars($audit['perkara']) ?>" readonly></div>
        <div><label>Tarikh Mula</label><input type="text" value="<?= !empty($audit['tarikh_mula']) ? date('d/m/Y', strtotime($audit['tarikh_mula'])) : '-' ?>" readonly></div>
        <div><label>Tarikh Akhir</label><input type="text" value="<?= !empty($audit['tarikh_akhir']) ? date('d/m/Y', strtotime($audit['tarikh_akhir'])) : '-' ?>" readonly></div>
        <div><label>Tarikh Daftar</label><input type="text" value="<?= !empty($audit['created_at']) ? date('d/m/Y h:i A', strtotime($audit['created_at'])) : '-' ?>" readonly></div>
        <div class="full-width">
            <label>Lampiran Fail</label>
            <?php if (!empty($attachments)): ?>
            <div class="attachment-list">
                <?php foreach ($attachments as $attachment): ?>
                <a href="<?= htmlspecialchars($attachment['attachment_path']) ?>" class="attachment-link" onclick="openAttachmentPreview(event, '<?= htmlspecialchars($attachment['attachment_path'], ENT_QUOTES) ?>', '<?= htmlspecialchars($attachment['attachment_name'], ENT_QUOTES) ?>')">
                    <i class="fa-solid fa-paperclip"></i>
                    <?= htmlspecialchars($attachment['attachment_name']) ?>
                </a>
                <?php endforeach; ?>
            </div>
            <?php else: ?>
            <input type="text" value="-" readonly>
            <?php endif; ?>
        </div>
        <div class="full-width">
            <label>Ditugaskan Kepada</label>
            <div class="assign-list">
                <?php if (!empty($assignedUnits)): ?>
                    <?php foreach ($assignedUnits as $unit): ?>
                        <?php
                        $assignStatus = $assignFeedbackStatusMap[(int) $audit['id']][$unit] ?? 'pending';
                        $assignClass = 'assign-pending';
                        if ($assignStatus === 'submitted') {
                            $assignClass = 'assign-submitted';
                        } elseif ($assignStatus === 'updated') {
                            $assignClass = 'assign-updated';
                        }
                        ?>
                        <span class="assign-pill <?= $assignClass ?>">
                            <i class="fa-solid fa-building"></i>
                            <?= htmlspecialchars($unit) ?>
                        </span>
                    <?php endforeach; ?>
                <?php else: ?>
                    <input type="text" value="-" readonly>
                <?php endif; ?>
            </div>
        </div>
        <div class="full-width"><label>Ringkasan Perkara Audit</label><textarea rows="15" readonly><?= htmlspecialchars($audit['remarks'] ?: '-') ?></textarea></div>
    </div>
    <div class="button-row">
        <a href="senarai_maklumat_audit.php" class="primary-btn">Kembali ke Senarai Maklumat Audit</a>
    </div>
</div>
<?php render_layout_end(); ?>
