<?php
require_once __DIR__ . '/includes/layout.php';
require_login();

$userUnit = current_user_unit();
$isManagement = is_management_role();

$stmt = $conn->query("
    SELECT af.id, af.perkara, af.tarikh_mula, af.tarikh_akhir, af.remarks, af.audit_approval_status, 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
    GROUP BY af.id
    ORDER BY af.created_at DESC, af.id DESC
");

$records = $stmt instanceof mysqli_stmt ? $stmt->get_result()->fetch_all(MYSQLI_ASSOC) : ($stmt ? $stmt->fetch_all(MYSQLI_ASSOC) : []);
$assignFeedbackStatusMap = [];
$unitFeedbackMap = [];
$assignmentApprovalMap = [];
$todayDate = date('Y-m-d');

$currentUserId = current_user_id();
$issueChartRows = [];
$issueChartMax = 10;

foreach (audit_bahagian_list() as $bahagian) {
    preg_match('/\(([^)]+)\)/', $bahagian, $unitMatch);
    $issueChartRows[$bahagian] = [
        'label' => $unitMatch[1] ?? $bahagian,
        'belum' => 0,
        'selesai' => 0,
    ];
}

$assignmentApprovalStmt = $conn->query("
    SELECT audit_form_id, assigned_unit, audit_approval_status
    FROM audit_form_assignments
");
if ($assignmentApprovalStmt) {
    while ($approvalRow = $assignmentApprovalStmt->fetch_assoc()) {
        $auditFormId = (int) ($approvalRow['audit_form_id'] ?? 0);
        $assignedUnit = trim((string) ($approvalRow['assigned_unit'] ?? ''));
        if ($auditFormId <= 0 || $assignedUnit === '') {
            continue;
        }
        if (!isset($assignmentApprovalMap[$auditFormId])) {
            $assignmentApprovalMap[$auditFormId] = [];
        }
        $assignmentApprovalMap[$auditFormId][$assignedUnit] = (string) ($approvalRow['audit_approval_status'] ?? 'perlu_kemaskini');
        if (!isset($issueChartRows[$assignedUnit])) {
            preg_match('/\(([^)]+)\)/', $assignedUnit, $unitMatch);
            $issueChartRows[$assignedUnit] = [
                'label' => $unitMatch[1] ?? $assignedUnit,
                'belum' => 0,
                'selesai' => 0,
            ];
        }
        if (($approvalRow['audit_approval_status'] ?? '') === 'lulus_diaudit') {
            $issueChartRows[$assignedUnit]['selesai']++;
        } else {
            $issueChartRows[$assignedUnit]['belum']++;
        }
    }
}

$assignStatusStmt = $conn->query("
    SELECT fb.id, fb.audit_form_id, fb.submitted_unit, fb.assigned_to_user_id, fb.catatan_audit, fb.created_at, fb.updated_at,
           u.nama AS assigned_to_name
    FROM audit_feedbacks fb
    LEFT JOIN users u ON u.id = fb.assigned_to_user_id
");
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;
        }

        if (!isset($unitFeedbackMap[$auditFormId])) {
            $unitFeedbackMap[$auditFormId] = [];
        }
        $unitFeedbackMap[$auditFormId][$submittedUnit] = [
            'id' => (int) ($statusRow['id'] ?? 0),
            'assigned_to_user_id' => (int) ($statusRow['assigned_to_user_id'] ?? 0),
            'assigned_to_name' => trim((string) ($statusRow['assigned_to_name'] ?? '')),
            'catatan_audit' => trim((string) ($statusRow['catatan_audit'] ?? '')),
        ];

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

if ($isManagement) {
    $totalAuditResult = $conn->query("SELECT COUNT(*) AS total FROM audit_forms");
    $resolvedIssuesResult = $conn->query("
        SELECT COUNT(*) AS total
        FROM (
            SELECT af.id
            FROM audit_forms af
            INNER JOIN audit_form_assignments afa ON afa.audit_form_id = af.id
            GROUP BY af.id
            HAVING COUNT(afa.id) > 0
               AND SUM(afa.audit_approval_status <> 'lulus_diaudit') = 0
        ) resolved_audits
    ");
    $unresolvedIssuesResult = $conn->query("
        SELECT COUNT(*) AS total
        FROM (
            SELECT af.id
            FROM audit_forms af
            LEFT JOIN audit_form_assignments afa ON afa.audit_form_id = af.id
            GROUP BY af.id
            HAVING SUM(
                CASE
                    WHEN afa.id IS NULL OR afa.audit_approval_status <> 'lulus_diaudit' THEN 1
                    ELSE 0
                END
            ) > 0
        ) unresolved_audits
    ");
    $resolvedIssueCount = (int) ($resolvedIssuesResult ? ($resolvedIssuesResult->fetch_assoc()['total'] ?? 0) : 0);
    $unresolvedIssueCount = (int) ($unresolvedIssuesResult ? ($unresolvedIssuesResult->fetch_assoc()['total'] ?? 0) : 0);
    $unresolvedByUnit = [];
    foreach (audit_bahagian_list() as $bahagian) {
        $unresolvedByUnit[$bahagian] = 0;
    }
    $unresolvedByUnitResult = $conn->query("
        SELECT assigned_unit, COUNT(DISTINCT audit_form_id) AS total
        FROM audit_form_assignments
        WHERE audit_approval_status <> 'lulus_diaudit'
        GROUP BY assigned_unit
    ");
    if ($unresolvedByUnitResult) {
        while ($unitRow = $unresolvedByUnitResult->fetch_assoc()) {
            $unitName = trim((string) ($unitRow['assigned_unit'] ?? ''));
            if ($unitName !== '') {
                $unresolvedByUnit[$unitName] = (int) ($unitRow['total'] ?? 0);
            }
        }
    }
    $unresolvedByUnit = array_filter($unresolvedByUnit, static function (int $total): bool {
        return $total > 0;
    });
    $topUnresolvedRows = array_values($issueChartRows);
    usort($topUnresolvedRows, static function (array $a, array $b): int {
        return (int) ($b['belum'] ?? 0) <=> (int) ($a['belum'] ?? 0);
    });
    $topUnresolvedMax = 10;
    $issuePieTotal = max(1, $resolvedIssueCount + $unresolvedIssueCount);
    $issuePieDonePercent = round(($resolvedIssueCount / $issuePieTotal) * 100);
    $issuePiePendingPercent = 100 - $issuePieDonePercent;
    $assignedToCurrentUnitStmt = $conn->prepare("
        SELECT COUNT(DISTINCT af.id) AS total
        FROM audit_forms af
        INNER JOIN audit_form_assignments afa ON afa.audit_form_id = af.id
        WHERE afa.assigned_unit = ?
    ");
    $assignedToCurrentUnitStmt->bind_param('s', $userUnit);
    $assignedToCurrentUnitStmt->execute();
    $assignedToCurrentUnitResult = $assignedToCurrentUnitStmt->get_result()->fetch_assoc();

    $stats = [
        [
            'icon' => 'fa-clipboard-list',
            'number' => (int) ($totalAuditResult ? ($totalAuditResult->fetch_assoc()['total'] ?? 0) : 0),
            'label' => 'Jumlah Audit',
            'tone' => 'primary',
            'hint' => 'Rekod audit berdaftar',
        ],
        [
            'icon' => 'fa-triangle-exclamation',
            'number' => $unresolvedIssueCount,
            'label' => 'Bilangan Isu Belum Selesai',
            'details' => $unresolvedByUnit,
            'tone' => 'warning',
            'hint' => 'Masih memerlukan tindakan',
        ],
        [
            'icon' => 'fa-circle-check',
            'number' => $resolvedIssueCount,
            'label' => 'Bilangan Isu Selesai',
            'tone' => 'success',
            'hint' => 'Semua bahagian selesai audit',
        ],
        [
            'icon' => 'fa-thumbtack',
            'number' => (int) ($assignedToCurrentUnitResult['total'] ?? 0),
            'label' => 'Ditugaskan Kepada Anda',
            'tone' => 'info',
            'hint' => htmlspecialchars($userUnit),
        ],
    ];
} else {
    $assignedAuditStmt = $conn->prepare("
        SELECT COUNT(DISTINCT af.id) AS total
        FROM audit_forms af
        INNER JOIN audit_form_assignments afa ON afa.audit_form_id = af.id
        WHERE afa.assigned_unit = ?
    ");
    $assignedAuditStmt->bind_param('s', $userUnit);
    $assignedAuditStmt->execute();
    $assignedAuditResult = $assignedAuditStmt->get_result()->fetch_assoc();

    $unitUnresolvedIssueStmt = $conn->prepare("
        SELECT COUNT(DISTINCT af.id) AS total
        FROM audit_forms af
        INNER JOIN audit_form_assignments afa ON afa.audit_form_id = af.id
        WHERE afa.assigned_unit = ?
          AND afa.audit_approval_status <> 'lulus_diaudit'
    ");
    $unitUnresolvedIssueStmt->bind_param('s', $userUnit);
    $unitUnresolvedIssueStmt->execute();
    $unitUnresolvedIssueResult = $unitUnresolvedIssueStmt->get_result()->fetch_assoc();

    $unitResolvedIssueStmt = $conn->prepare("
        SELECT COUNT(DISTINCT af.id) AS total
        FROM audit_forms af
        INNER JOIN audit_form_assignments afa ON afa.audit_form_id = af.id
        WHERE afa.assigned_unit = ?
          AND afa.audit_approval_status = 'lulus_diaudit'
    ");
    $unitResolvedIssueStmt->bind_param('s', $userUnit);
    $unitResolvedIssueStmt->execute();
    $unitResolvedIssueResult = $unitResolvedIssueStmt->get_result()->fetch_assoc();

    preg_match('/\(([^)]+)\)/', $userUnit, $userUnitMatch);
    $userUnitShort = $userUnitMatch[1] ?? $userUnit;

    $stats = [
        [
            'icon' => 'fa-clipboard-list',
            'number' => (int) ($assignedAuditResult['total'] ?? 0),
            'label' => 'Jumlah Audit Yang Ditugaskan kepada Bahagian',
            'tone' => 'primary',
            'hint' => 'Mengikut bahagian pengguna sahaja',
        ],
        [
            'icon' => 'fa-triangle-exclamation',
            'number' => (int) ($unitUnresolvedIssueResult['total'] ?? 0),
            'label' => 'Isu Belum Selesai',
            'tone' => 'warning',
            'hint' => 'Belum selesai untuk bahagian ini',
        ],
        [
            'icon' => 'fa-circle-check',
            'number' => (int) ($unitResolvedIssueResult['total'] ?? 0),
            'label' => 'Isu Yang Telah Selesai',
            'tone' => 'success',
            'hint' => 'Selesai audit untuk bahagian ini',
        ],
        [
            'icon' => 'fa-building',
            'number' => $userUnitShort,
            'label' => 'Bahagian / Unit',
            'tone' => 'info',
            'hint' => htmlspecialchars($userUnit),
        ],
    ];
}

render_layout_start('Dashboard - Dashboard Audit MAINPP');
?>
<style>
.stats-grid {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    align-items: stretch;
    gap: 18px;
    margin-bottom: 24px;
}
.stat-card {
    position: relative;
    overflow: hidden;
    background: linear-gradient(180deg, #ffffff 0%, #fbfdff 100%);
    border: 1px solid #e5edf7;
    border-radius: 14px;
    box-shadow: 0 12px 30px rgba(15, 23, 42, 0.06);
    padding: 20px;
    display: grid;
    grid-template-columns: 48px minmax(0, 1fr);
    grid-template-rows: auto 1fr;
    gap: 14px 14px;
    align-items: start;
    min-height: 154px;
}
.stat-card::before {
    content: "";
    position: absolute;
    inset: 0 0 auto 0;
    height: 3px;
    background: #0d6efd;
}
.stat-card::after {
    content: "";
    position: absolute;
    right: -36px;
    top: -40px;
    width: 118px;
    height: 118px;
    border-radius: 999px;
    background: rgba(13, 110, 253, 0.055);
    pointer-events: none;
}
.stat-card.primary::before { background: #0d6efd; }
.stat-card.warning::before { background: #f59e0b; }
.stat-card.success::before { background: #16a34a; }
.stat-card.info::before { background: #0891b2; }
.stat-card.warning::after { background: rgba(245, 158, 11, 0.07); }
.stat-card.success::after { background: rgba(22, 163, 74, 0.07); }
.stat-card.info::after { background: rgba(8, 145, 178, 0.07); }
.stat-head {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top: 4px;
}
.stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 14px;
    background: #eef5ff;
    color: #0d6efd;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    flex-shrink: 0;
}
.stat-card.warning .stat-icon {
    background: #fff7ed;
    color: #d97706;
}
.stat-card.success .stat-icon {
    background: #ecfdf5;
    color: #16a34a;
}
.stat-card.info .stat-icon {
    background: #ecfeff;
    color: #0891b2;
}
.stat-number {
    font-size: 32px;
    font-weight: 900;
    color: #0f172a;
    line-height: 1;
    word-break: break-word;
    letter-spacing: 0;
}
.stat-label {
    margin-top: 8px;
    font-size: 13px;
    font-weight: 900;
    color: #334155;
    text-transform: uppercase;
    letter-spacing: 0.03em;
}
.stat-main {
    min-width: 0;
    padding-top: 2px;
}
.stat-footer {
    grid-column: 1 / -1;
    min-height: 44px;
    padding-top: 12px;
    border-top: 1px solid #edf2f7;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
}
.stat-hint {
    color: #64748b;
    font-size: 12px;
    font-weight: 700;
    line-height: 1.4;
}
.stat-detail-list {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin-top: 8px;
    max-height: 62px;
    overflow-y: auto;
    padding-right: 2px;
}
.stat-detail-chip {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 5px 9px;
    border-radius: 8px;
    background: #fff7ed;
    color: #9a3412;
    font-size: 12px;
    font-weight: 900;
    border: 1px solid #fed7aa;
}
.stat-detail-chip i {
    font-size: 10px;
}
@media (max-width: 1200px) {
    .stats-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }
}
@media (max-width: 640px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }
}
html[data-theme="dark"] .stat-footer {
    border-color: #263244;
}
html[data-theme="dark"] .stat-detail-chip {
    background: #431407;
    color: #fdba74;
    border-color: #7c2d12;
}
.issue-chart-card {
    margin-bottom: 24px;
    padding: 24px;
    border-radius: 16px;
    border: 1px solid #e5edf7;
    box-shadow: 0 14px 36px rgba(15, 23, 42, 0.06);
}
.issue-chart-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    margin-bottom: 18px;
}
.issue-chart-head h3 {
    margin: 0;
    display: inline-flex;
    align-items: center;
    gap: 10px;
    color: #0f172a;
    font-size: 18px;
    font-weight: 900;
}
.issue-chart-legend {
    display: flex;
    align-items: center;
    gap: 14px;
    flex-wrap: wrap;
}
.issue-chart-legend span {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    color: #64748b;
    font-size: 12px;
    font-weight: 800;
}
.legend-dot {
    width: 10px;
    height: 10px;
    border-radius: 50%;
}
.legend-dot.pending {
    background: #f59e0b;
}
.legend-dot.done {
    background: #16a34a;
}
.issue-chart-wrap {
    display: grid;
    grid-template-columns: 44px minmax(0, 1fr);
    gap: 12px;
    min-height: 410px;
    padding: 4px 0 0;
}
.issue-chart-axis {
    display: flex;
    flex-direction: column-reverse;
    justify-content: space-between;
    padding-bottom: 34px;
    color: #94a3b8;
    font-size: 11px;
    font-weight: 800;
    text-align: right;
}
.issue-chart-plot {
    position: relative;
    display: grid;
    grid-template-columns: repeat(10, minmax(54px, 1fr));
    align-items: end;
    gap: 12px;
    min-width: 760px;
    padding: 14px 8px 34px;
    border-left: 1px solid #dde7f2;
    border-bottom: 1px solid #dde7f2;
    background:
        repeating-linear-gradient(
            to top,
            transparent 0,
            transparent calc(10% - 1px),
            #eef3f8 calc(10% - 1px),
            #eef3f8 10%
        );
}
.issue-chart-scroll {
    overflow-x: auto;
}
.issue-bar-group {
    height: 340px;
    display: flex;
    align-items: end;
    justify-content: center;
    gap: 7px;
    position: relative;
}
.issue-bar {
    width: 18px;
    min-height: 2px;
    border-radius: 8px 8px 0 0;
    position: relative;
}
.issue-bar.pending {
    background: linear-gradient(180deg, #fbbf24, #f59e0b);
}
.issue-bar.done {
    background: linear-gradient(180deg, #34d399, #16a34a);
}
.issue-bar-value {
    position: absolute;
    left: 50%;
    bottom: calc(100% + 5px);
    transform: translateX(-50%);
    color: #475569;
    font-size: 10px;
    font-weight: 900;
}
.issue-chart-label {
    position: absolute;
    left: 50%;
    bottom: -28px;
    transform: translateX(-50%);
    color: #64748b;
    font-size: 12px;
    font-weight: 900;
}
html[data-theme="dark"] .issue-chart-plot {
    border-color: #334155;
    background:
        repeating-linear-gradient(
            to top,
            transparent 0,
            transparent calc(10% - 1px),
            #1f2937 calc(10% - 1px),
            #1f2937 10%
        );
}
html[data-theme="dark"] .issue-bar-value,
html[data-theme="dark"] .issue-chart-label,
html[data-theme="dark"] .issue-chart-legend span {
    color: #cbd5e1;
}
.analytics-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    align-items: stretch;
    gap: 18px;
    margin-bottom: 24px;
}
.analytics-card {
    padding: 24px;
    height: 100%;
    display: flex;
    flex-direction: column;
    border-radius: 16px;
    border: 1px solid #e5edf7;
    box-shadow: 0 14px 36px rgba(15, 23, 42, 0.06);
}
.analytics-card h3 {
    margin: 0 0 18px;
    display: inline-flex;
    align-items: center;
    gap: 10px;
    color: #0f172a;
    font-size: 18px;
    font-weight: 900;
}
.issue-pie-layout {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    flex: 1;
    gap: 16px;
}
.issue-pie {
    width: min(260px, 72vw);
    aspect-ratio: 1;
    border-radius: 50%;
    background: <?= (int) ($issuePieTotal ?? 0) > 0 ? 'conic-gradient(#e11d48 0 ' . (int) ($issuePiePendingPercent ?? 0) . '%, #16a34a ' . (int) ($issuePiePendingPercent ?? 0) . '% 100%)' : '#e5e7eb' ?>;
    box-shadow: 0 18px 40px rgba(15, 23, 42, 0.12);
    border: 8px solid #ffffff;
}
.issue-pie-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 18px;
}
.issue-pie-item {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: #64748b;
    font-size: 13px;
    font-weight: 800;
}
.issue-pie-item .legend-dot {
    width: 38px;
    height: 12px;
    border-radius: 0;
}
.issue-pie-item .legend-dot.pending {
    background: #e11d48;
}
.issue-pie-summary {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 14px;
    width: 100%;
    margin-top: 8px;
}
.issue-pie-summary-card {
    min-height: 92px;
    padding: 16px 12px;
    border: 1px solid #e3ebf5;
    border-radius: 12px;
    background: linear-gradient(180deg, #ffffff 0%, #f8fbff 100%);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
}
.issue-pie-summary-card i {
    color: #0d6efd;
    font-size: 20px;
    margin-bottom: 8px;
}
.issue-pie-summary-card strong {
    color: #0d6efd;
    font-size: 24px;
    line-height: 1;
}
.issue-pie-summary-card span {
    margin-top: 8px;
    color: #334155;
    font-size: 12px;
    font-weight: 900;
    text-transform: uppercase;
}
.rank-bar-list {
    display: grid;
    gap: 11px;
    padding-top: 6px;
    flex: 1;
    align-content: stretch;
}
.rank-bar-row {
    display: grid;
    grid-template-columns: 58px minmax(0, 1fr) 24px;
    gap: 10px;
    align-items: center;
    min-height: 26px;
}
.rank-bar-label {
    color: #334155;
    font-size: 13px;
    font-weight: 900;
    text-align: right;
}
.rank-bar-track {
    height: 100%;
    min-height: 22px;
    border-radius: 4px;
    background: #f1f5f9;
    overflow: hidden;
    background-image: repeating-linear-gradient(
        to right,
        transparent 0,
        transparent calc(10% - 1px),
        rgba(148, 163, 184, 0.22) calc(10% - 1px),
        rgba(148, 163, 184, 0.22) 10%
    );
}
.rank-bar-fill {
    display: block;
    height: 100%;
    border-radius: inherit;
    background: linear-gradient(90deg, #0891b2, #0e7490);
    box-shadow: inset 0 -1px 0 rgba(255, 255, 255, 0.22);
}
.rank-bar-value {
    color: #0f172a;
    font-size: 13px;
    font-weight: 900;
    text-align: right;
}
.rank-bar-axis {
    display: grid;
    grid-template-columns: 58px minmax(0, 1fr) 24px;
    gap: 10px;
    margin-top: 4px;
}
.rank-bar-axis-scale {
    display: grid;
    grid-template-columns: repeat(11, 1fr);
    color: #94a3b8;
    font-size: 10px;
    font-weight: 800;
}
.rank-bar-axis-scale span {
    text-align: center;
}
.rank-empty {
    color: #64748b;
    font-size: 13px;
    font-weight: 700;
}
html[data-theme="dark"] .issue-pie-summary-card,
html[data-theme="dark"] .analytics-card {
    background: #111827;
    border-color: #263244;
}
html[data-theme="dark"] .issue-pie-summary-card strong,
html[data-theme="dark"] .rank-bar-value,
html[data-theme="dark"] .rank-bar-label {
    color: #e5e7eb;
}
html[data-theme="dark"] .issue-pie-summary-card i {
    color: #60a5fa;
}
html[data-theme="dark"] .issue-pie-summary-card span,
html[data-theme="dark"] .issue-pie-item,
html[data-theme="dark"] .rank-empty {
    color: #94a3b8;
}
html[data-theme="dark"] .rank-bar-track {
    background: #1f2937;
    background-image: repeating-linear-gradient(
        to right,
        transparent 0,
        transparent calc(10% - 1px),
        rgba(148, 163, 184, 0.18) calc(10% - 1px),
        rgba(148, 163, 184, 0.18) 10%
    );
}
@media (max-width: 1100px) {
    .analytics-grid {
        grid-template-columns: 1fr;
    }
}
@media (max-width: 640px) {
    .issue-pie-summary {
        grid-template-columns: 1fr;
    }
}






.table-container table {
    table-layout: fixed;
    border-collapse: separate;
    border-spacing: 0;
}
.table-container {
    border: 1px solid #e5edf7;
    border-radius: 16px;
    box-shadow: 0 14px 36px rgba(15, 23, 42, 0.06);
}
.table-container th {
    background: #f8fbff;
    color: #0f172a;
    font-size: 12px;
    font-weight: 900;
    text-transform: uppercase;
    letter-spacing: 0.02em;
    border-bottom: 1px solid #e2e8f0;
}
.table-container td {
    vertical-align: top;
    border-bottom: 1px solid #edf2f7;
}
.table-container th:nth-child(1),
.table-container td:nth-child(1) {
    width: 70px;
}
.table-container th:nth-child(2),
.table-container td:nth-child(2) {
    width: 20%;
}
.table-container th:nth-child(3),
.table-container td:nth-child(3) {
    width: 24%;
}
.table-container th:nth-child(4),
.table-container td:nth-child(4) {
    width: 17%;
}
.table-container th:nth-child(5),
.table-container td:nth-child(5) {
    width: 22%;
}
.table-container th:nth-child(6),
.table-container td:nth-child(6) {
    width: 170px;
}
.table-container th:nth-child(7),
.table-container td:nth-child(7) {
    width: 120px;
}
.assign-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
}
.assign-pill {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 8px 12px;
    border-radius: 12px;
    background: #edf4ff;
    color: #1560ff;
    font-size: 13px;
    font-weight: 800;
    line-height: 1.2;
    border: 1px solid transparent;
}
.assign-pill.assign-pending {
    background: #fee2e2;
    color: #b91c1c;
    border-color: #fecaca;
}
.assign-pill.assign-submitted {
    background: #fef3c7;
    color: #92400e;
    border-color: #fde68a;
}
.assign-pill.assign-updated {
    background: #fef3c7;
    color: #92400e;
    border-color: #fde68a;
}
.assign-pill.assign-approved {
    background: #dcfce7;
    color: #166534;
    border-color: #bbf7d0;
}
.audit-approval-cell { min-width: 170px; }
.approval-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
}
.approval-unit-name {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    max-width: 230px;
    margin-bottom: 6px;
    color: #334155;
    font-size: 12px;
    font-weight: 800;
    line-height: 1.35;
}
.approval-unit-name i {
    color: #0d6efd;
}
.dropdown-form { margin: 0; position: relative; display: inline-block; }
.dropdown-pill {
    position: relative;
    display: inline-flex;
    align-items: center;
    min-width: 146px;
    border-radius: 12px;
    padding: 7px 28px 7px 10px;
    border: 1px solid transparent;
    overflow: hidden;
}
.dropdown-pill.static { padding-right: 10px; }
.dropdown-pill.approval-needs-update { background: #fef3c7; color: #92400e; }
.dropdown-pill.approval-approved { background: #dcfce7; color: #166534; }
.dropdown-dot,
.dropdown-option-dot {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    margin-right: 8px;
    flex-shrink: 0;
}
.dropdown-pill.approval-needs-update .dropdown-dot,
.dropdown-option-dot.approval-needs-update { background: #92400e; }
.dropdown-pill.approval-approved .dropdown-dot,
.dropdown-option-dot.approval-approved { background: #166534; }
.dropdown-label { font-size: 12px; font-weight: 700; line-height: 1.1; }
.dropdown-arrow-btn {
    position: absolute;
    right: 0;
    top: 0;
    bottom: 0;
    width: 26px;
    border: none;
    background: transparent;
    color: inherit;
    cursor: pointer;
}
.dropdown-menu {
    display: none;
    position: absolute;
    top: calc(100% + 8px);
    left: 0;
    min-width: 146px;
    background: #fff;
    border: 1px solid #d9e2ec;
    border-radius: 12px;
    box-shadow: 0 12px 30px rgba(18,52,88,0.12);
    padding: 6px;
    z-index: 20;
}
.dropdown-menu.show { display: block; }
.dropdown-option-btn {
    width: 100%;
    border: none;
    background: transparent;
    border-radius: 10px;
    padding: 8px 10px;
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 12px;
    font-weight: 700;
    text-align: left;
    cursor: pointer;
}
.dropdown-option-btn:hover { background: #f8fbff; }
.assign-extra {
    display: none;
}
.assign-extra.show {
    display: flex;
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
}
.assign-more-btn {
    border: none;
    background: #f1f5f9;
    color: #0d6efd;
    font-size: 13px;
    font-weight: 700;
    cursor: pointer;
    padding: 7px 10px;
    border-radius: 10px;
}
.assign-more-btn:hover {
    background: #eaf2ff;
    text-decoration: none;
}
.assign-pill i {
    font-size: 12px;
}
.audit-note-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
}
.feedback-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
}
.feedback-item {
    width: 100%;
    max-width: 230px;
    min-height: 84px;
    padding: 10px 12px;
    border-radius: 12px;
    background: #ffffff;
    border: 1px solid #dbeafe;
    box-shadow: 0 8px 18px rgba(15, 23, 42, 0.04);
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
}
.feedback-unit {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    font-weight: 700;
    color: #0d6efd;
    margin-bottom: 8px;
    width: 100%;
    line-height: 1.35;
    word-break: break-word;
}
.feedback-extra {
    display: none;
}
.feedback-extra.show {
    display: flex;
    flex-direction: column;
    gap: 10px;
    width: 100%;
}
.feedback-more-btn {
    border: none;
    background: transparent;
    color: #0d6efd;
    font-size: 13px;
    font-weight: 700;
    cursor: pointer;
    padding: 0;
}
.feedback-more-btn:hover {
    text-decoration: underline;
}
.audit-note-item {
    width: 100%;
    max-width: 230px;
    min-height: 84px;
    padding: 10px 12px;
    border-radius: 12px;
    background: #ffffff;
    border: 1px solid #dbeafe;
    box-shadow: 0 8px 18px rgba(15, 23, 42, 0.04);
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
}
.audit-note-unit {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    font-weight: 700;
    color: #0d6efd;
    margin-bottom: 8px;
}
.audit-note-text {
    font-size: 13px;
    line-height: 1.45;
    color: #334155;
    white-space: pre-line;
}
.aligned-feedback-btn {
    max-width: 210px;
}
.audit-hidden-row {
    display: none;
}
.audit-hidden-row.show {
    display: table-row;
}
.audit-extra-spacer {
    background: #fff;
}
.audit-row-more-inline {
    margin-top: 8px;
}
.audit-row-more-btn {
    border: none;
    background: #f1f5f9;
    color: #0d6efd;
    font-size: 13px;
    font-weight: 800;
    cursor: pointer;
    padding: 7px 10px;
    border-radius: 10px;
}
.audit-row-more-btn:hover {
    background: #eaf2ff;
    text-decoration: none;
}
.audit-note-empty {
    color: #94a3b8;
    font-style: italic;
}
.audit-note-extra {
    display: none;
}
.audit-note-extra.show {
    display: flex;
    flex-direction: column;
    gap: 10px;
    width: 100%;
}
.audit-note-more-btn {
    border: none;
    background: transparent;
    color: #0d6efd;
    font-size: 13px;
    font-weight: 700;
    cursor: pointer;
    padding: 0;
}
.audit-note-more-btn:hover {
    text-decoration: underline;
}
.action-stack {
    display: inline-flex;
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
}
.action-btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 6px 12px;
    border-radius: 999px;
    font-size: 12px;
    font-weight: 700;
    text-decoration: none;
    white-space: nowrap;
}
.action-btn.edit-btn {
    background: #edf4ff;
    color: #1560ff;
    padding: 8px 14px;
    font-size: 14px;
}
.action-btn.feedback-btn {
    background: #e6fffb;
    color: #0f766e;
    width: 100%;
    justify-content: center;
    text-align: center;
    white-space: normal;
    line-height: 1.3;
    gap: 6px;
}
.assign-legend {
    margin: 4px 0 18px;
    display: flex;
    flex-direction: row;
    gap: 10px;
    align-items: center;
    flex-wrap: wrap;
}




.assign-legend-item {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    font-weight: 700;
    color: #334155;
}
.assign-legend-dot {
    width: 13px;
    height: 13px;
    border-radius: 999px;
    display: inline-block;
}
.assign-legend-dot.red {
    background: #b91c1c;
}
.assign-legend-dot.green {
    background: #166534;
}
.assign-legend-dot.yellow {
    background: #d97706;
}
.dashboard-title-card {
    padding: 22px 24px;
    margin-bottom: 18px;
    border-radius: 16px;
    border: 1px solid #e5edf7;
    background:
        radial-gradient(circle at 8% 12%, rgba(13, 110, 253, 0.14), transparent 28%),
        linear-gradient(135deg, rgba(13, 110, 253, 0.08), rgba(22, 163, 74, 0.06)),
        #ffffff;
    box-shadow: 0 12px 30px rgba(15, 23, 42, 0.05);
    overflow: hidden;
}
.dashboard-title-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 18px;
    flex-wrap: wrap;
}
.dashboard-title-main {
    min-width: 260px;
}
.dashboard-title-row h3 {
    margin: 0;
    display: inline-flex;
    align-items: center;
    gap: 10px;
    color: #0f172a;
    font-size: 22px;
    font-weight: 900;
}
.dashboard-subtitle {
    margin-top: 8px;
    color: #475569;
    font-size: 14px;
    font-weight: 700;
    line-height: 1.45;
}
.dashboard-title-meta {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 10px;
    flex-wrap: wrap;
}
.dashboard-meta-pill {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    min-height: 38px;
    padding: 8px 12px;
    border-radius: 999px;
    background: rgba(255, 255, 255, 0.82);
    border: 1px solid #e2e8f0;
    color: #334155;
    font-size: 12px;
    font-weight: 900;
    box-shadow: 0 8px 18px rgba(15, 23, 42, 0.04);
}
.dashboard-meta-pill i {
    color: #0d6efd;
}
.dashboard-date-pill {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    border-radius: 999px;
    background: #ffffff;
    border: 1px solid #e2e8f0;
    color: #475569;
    font-size: 13px;
    font-weight: 800;
}
html[data-theme="dark"] .dashboard-date-pill {
    background: #1e293b;
    color: #cbd5e1;
}
html[data-theme="dark"] .dashboard-subtitle {
    color: #94a3b8;
}
html[data-theme="dark"] .dashboard-meta-pill {
    background: #1e293b;
    border-color: #334155;
    color: #cbd5e1;
}
html[data-theme="dark"] .dashboard-meta-pill i {
    color: #60a5fa;
}
html[data-theme="dark"] .dashboard-title-card,
html[data-theme="dark"] .stat-card,
html[data-theme="dark"] .issue-chart-card,
html[data-theme="dark"] .table-container {
    background: #111827;
    border-color: #263244;
}
html[data-theme="dark"] .dashboard-title-row h3,
html[data-theme="dark"] .issue-chart-head h3,
html[data-theme="dark"] .analytics-card h3,
html[data-theme="dark"] .stat-number,
html[data-theme="dark"] .stat-label {
    color: #e5e7eb;
}
html[data-theme="dark"] .stat-hint {
    color: #94a3b8;
}
html[data-theme="dark"] .table-container th {
    background: #172033;
    color: #e5e7eb;
    border-color: #263244;
}
html[data-theme="dark"] .table-container td {
    border-color: #263244;
}
html[data-theme="dark"] .feedback-item,
html[data-theme="dark"] .audit-note-item {
    background: #172033;
    border-color: #263244;
}
</style>
<?php if (isset($_GET['success']) && $_GET['success'] === 'audit_saved'): ?>
    <div class="status-message status-success">Maklumat audit berjaya disimpan.</div>
<?php elseif (isset($_GET['success']) && $_GET['success'] === 'audit_deleted'): ?>
    <div class="status-message status-success">Maklumat audit berjaya dipadam.</div>
<?php elseif (isset($_GET['success']) && $_GET['success'] === 'feedback_saved'): ?>
    <div class="status-message status-success">Maklum balas audit berjaya disimpan.</div>
<?php elseif (isset($_GET['success']) && $_GET['success'] === 'audit_note_saved'): ?>
    <div class="status-message status-success">Catatan audit berjaya disimpan.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'feedback_assigned'): ?>
    <div class="status-message status-warning">Maklum balas audit ini telah ditugaskan kepada pengguna lain dalam bahagian anda.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'audit_approval_incomplete'): ?>
    <div class="status-message status-warning">Kelulusan audit hanya boleh dibuat selepas semua bahagian selesai menghantar maklum balas.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'feedback_not_started'): ?>
    <div class="status-message status-warning">Maklum balas belum boleh diisi kerana tarikh mula audit masih belum bermula.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'feedback_closed'): ?>
    <div class="status-message status-warning">Tempoh maklum balas audit telah tamat. Maklum balas tidak boleh diisi atau dikemaskini.</div>
<?php endif; ?>

<div class="page-card dashboard-title-card">
    <div class="dashboard-title-row">
        <div class="dashboard-title-main">
            <h3><i class="fa-solid fa-gauge-high"></i> Dashboard</h3>
        </div>
        <div class="dashboard-title-meta">
            <span class="dashboard-meta-pill"><i class="fa-solid fa-user-shield"></i> <?= htmlspecialchars(current_user_role()) ?></span>
            <span class="dashboard-meta-pill"><i class="fa-solid fa-building"></i> <?= htmlspecialchars($userUnit) ?></span>
            <span class="dashboard-date-pill"><i class="fa-solid fa-calendar-day"></i> <?= date('d/m/Y') ?></span>
        </div>
    </div>
</div>

<div class="stats-grid">
    <?php foreach ($stats as $stat): ?>
    <div class="stat-card <?= htmlspecialchars($stat['tone'] ?? 'primary') ?>">
        <div class="stat-head">
            <div class="stat-icon"><i class="fa-solid <?= htmlspecialchars($stat['icon']) ?>"></i></div>
        </div>
        <div class="stat-main">
            <div class="stat-number"><?= htmlspecialchars((string) $stat['number']) ?></div>
            <div class="stat-label"><?= htmlspecialchars($stat['label']) ?></div>
        </div>
        <div class="stat-footer">
            <?php if (!empty($stat['hint'])): ?>
            <div class="stat-hint"><?= htmlspecialchars((string) $stat['hint']) ?></div>
            <?php endif; ?>
            <?php if (!empty($stat['details']) && is_array($stat['details'])): ?>
            <div class="stat-detail-list">
                <?php foreach ($stat['details'] as $unitName => $unitTotal): ?>
                <span class="stat-detail-chip">
                    <i class="fa-solid fa-building"></i>
                    <?= htmlspecialchars(preg_match('/\(([^)]+)\)/', (string) $unitName, $match) ? $match[1] : $unitName) ?>
                    <?= (int) $unitTotal ?>
                </span>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<?php if ($isManagement): ?>
<div class="page-card issue-chart-card">
    <div class="issue-chart-head">
        <h3><i class="fa-solid fa-chart-column"></i> Bilangan Isu Mengikut Bahagian / Unit</h3>
        <div class="issue-chart-legend">
            <span><i class="legend-dot pending"></i> Belum Selesai</span>
            <span><i class="legend-dot done"></i> Selesai</span>
        </div>
    </div>
    <div class="issue-chart-wrap">
        <div class="issue-chart-axis">
            <?php for ($tick = 0; $tick <= $issueChartMax; $tick += 1): ?>
                <span><?= $tick ?></span>
            <?php endfor; ?>
        </div>
        <div class="issue-chart-scroll">
            <div class="issue-chart-plot">
                <?php foreach ($issueChartRows as $chartRow): ?>
                    <?php
                    $belum = min((int) ($chartRow['belum'] ?? 0), $issueChartMax);
                    $selesai = min((int) ($chartRow['selesai'] ?? 0), $issueChartMax);
                    $belumHeight = ($belum / $issueChartMax) * 100;
                    $selesaiHeight = ($selesai / $issueChartMax) * 100;
                    ?>
                    <div class="issue-bar-group">
                        <div class="issue-bar pending" style="height: <?= $belumHeight ?>%;" title="Belum Selesai: <?= (int) ($chartRow['belum'] ?? 0) ?>">
                            <?php if ((int) ($chartRow['belum'] ?? 0) > 0): ?>
                            <span class="issue-bar-value"><?= (int) $chartRow['belum'] ?></span>
                            <?php endif; ?>
                        </div>
                        <div class="issue-bar done" style="height: <?= $selesaiHeight ?>%;" title="Selesai: <?= (int) ($chartRow['selesai'] ?? 0) ?>">
                            <?php if ((int) ($chartRow['selesai'] ?? 0) > 0): ?>
                            <span class="issue-bar-value"><?= (int) $chartRow['selesai'] ?></span>
                            <?php endif; ?>
                        </div>
                        <span class="issue-chart-label"><?= htmlspecialchars($chartRow['label']) ?></span>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>
<div class="analytics-grid">
    <div class="page-card analytics-card">
        <h3><i class="fa-solid fa-chart-pie"></i> Pecahan Status Isu</h3>
        <div class="issue-pie-layout">
            <div class="issue-pie" aria-label="Carta pai isu selesai dan belum selesai"></div>
            <div class="issue-pie-list">
                <div class="issue-pie-item">
                    <i class="legend-dot pending"></i> Belum Selesai
                </div>
                <div class="issue-pie-item">
                    <i class="legend-dot done"></i> Selesai
                </div>
            </div>
            <div class="issue-pie-summary">
                <div class="issue-pie-summary-card">
                    <i class="fa-solid fa-list-check"></i>
                    <strong><?= (int) ($resolvedIssueCount + $unresolvedIssueCount) ?></strong>
                    <span>Jumlah Isu</span>
                </div>
                <div class="issue-pie-summary-card">
                    <i class="fa-solid fa-clock"></i>
                    <strong><?= (int) $unresolvedIssueCount ?></strong>
                    <span>Belum Selesai</span>
                </div>
                <div class="issue-pie-summary-card">
                    <i class="fa-solid fa-circle-check"></i>
                    <strong><?= (int) $resolvedIssueCount ?></strong>
                    <span>Selesai</span>
                </div>
            </div>
        </div>
    </div>
    <div class="page-card analytics-card">
        <h3><i class="fa-solid fa-chart-bar"></i> Isu Belum Selesai Mengikut Bahagian</h3>
        <?php if (!empty($topUnresolvedRows)): ?>
        <div class="rank-bar-list">
            <?php foreach ($topUnresolvedRows as $rankRow): ?>
                <?php
                $rankCount = min((int) ($rankRow['belum'] ?? 0), $topUnresolvedMax);
                $rankWidth = ($rankCount / $topUnresolvedMax) * 100;
                ?>
                <div class="rank-bar-row">
                    <span class="rank-bar-label"><?= htmlspecialchars($rankRow['label']) ?></span>
                    <span class="rank-bar-track"><span class="rank-bar-fill" style="width: <?= $rankWidth ?>%;"></span></span>
                    <span class="rank-bar-value"><?= $rankCount ?></span>
                </div>
            <?php endforeach; ?>
            <div class="rank-bar-axis" aria-hidden="true">
                <span></span>
                <div class="rank-bar-axis-scale">
                    <?php for ($tick = 0; $tick <= $topUnresolvedMax; $tick++): ?>
                        <span><?= $tick ?></span>
                    <?php endfor; ?>
                </div>
                <span></span>
            </div>
        </div>
        <?php else: ?>
        <div class="rank-empty">Tiada isu belum selesai buat masa ini.</div>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<div class="table-container">
    <div class="assign-legend">
        <span class="assign-legend-item"><span class="assign-legend-dot red"></span>Merah : Belum Ambil Tindakan</span>
            <span class="assign-legend-item"><span class="assign-legend-dot yellow"></span>Kuning : Dikemaskini oleh Bahagian</span>
            <span class="assign-legend-item"><span class="assign-legend-dot green"></span>Hijau : Selesai di Audit</span>
    </div>

    <table>
        <thead>
            <tr>
                <th style="width:70px;">Bil</th>
                <th>Perkara</th>
                <th>Tindakan Bahagian</th>
                <th>Maklum Balas</th>
                <th>Catatan Audit</th>
                <th>Kelulusan Audit</th>
                <?php if ($isManagement): ?>
                <th>Tindakan</th>
                <?php endif; ?>
            </tr>
        </thead>
        <tbody>
            <?php if (!empty($records)): ?>
                <?php $bil = 1; foreach ($records as $row): ?>
                <?php
                $auditId = (int) $row['id'];
                $assignedUnits = array_values(array_filter(array_map('trim', explode(',', (string) ($row['assigned_units'] ?? '')))));
                $approvalValue = (string) ($row['audit_approval_status'] ?? 'perlu_kemaskini');
                $tarikhMula = trim((string) ($row['tarikh_mula'] ?? ''));
                $tarikhAkhir = trim((string) ($row['tarikh_akhir'] ?? ''));
                $isBeforeAuditStart = $tarikhMula !== '' && $todayDate < $tarikhMula;
                $isAfterAuditEnd = $tarikhAkhir !== '' && $todayDate > $tarikhAkhir;
                $isFeedbackWindowOpen = !$isBeforeAuditStart && !$isAfterAuditEnd;
                $rowUnits = !empty($assignedUnits) ? $assignedUnits : [''];
                $visibleLimit = 3;
                $visibleRowCount = min(count($rowUnits), $visibleLimit);
                $hasMoreRows = count($rowUnits) > $visibleLimit;
                $rowspan = $visibleRowCount;
                ?>
                <?php foreach ($rowUnits as $unitIndex => $unit): ?>
                <?php
                $hasUnit = $unit !== '';
                $unitFeedback = $hasUnit ? ($unitFeedbackMap[$auditId][$unit] ?? null) : null;
                $unitFeedbackId = (int) ($unitFeedback['id'] ?? 0);
                $assignedFeedbackUserId = (int) ($unitFeedback['assigned_to_user_id'] ?? 0);
                $assignedFeedbackUserName = trim((string) ($unitFeedback['assigned_to_name'] ?? ''));
                $canGiveFeedback = $hasUnit && $userUnit === $unit;
                $isAssignedFeedbackUser = $assignedFeedbackUserId === 0 || $assignedFeedbackUserId === $currentUserId;
                $auditNote = trim((string) ($unitFeedback['catatan_audit'] ?? ''));
                $assignStatus = $hasUnit ? ($assignFeedbackStatusMap[$auditId][$unit] ?? 'pending') : 'pending';
                $assignClass = 'assign-pending';
                if ($assignStatus === 'submitted') {
                    $assignClass = 'assign-submitted';
                } elseif ($assignStatus === 'updated') {
                    $assignClass = 'assign-updated';
                }
                $unitApprovalValue = $hasUnit ? ($assignmentApprovalMap[$auditId][$unit] ?? $approvalValue) : $approvalValue;
                if ($unitApprovalValue === 'lulus_diaudit') {
                    $assignClass = 'assign-approved';
                }
                $unitApprovalClass = $unitApprovalValue === 'lulus_diaudit' ? 'approval-approved' : 'approval-needs-update';
                ?>
                <tr class="<?= $unitIndex >= $visibleLimit ? 'audit-hidden-row audit-extra-' . $auditId : '' ?>">
                    <?php if ($unitIndex === 0): ?>
                    <td rowspan="<?= $rowspan ?>"><?= $bil++ ?></td>
                    <td rowspan="<?= $rowspan ?>"><strong><?= nl2br(htmlspecialchars($row['perkara'])) ?></strong></td>
                    <?php elseif ($unitIndex >= $visibleLimit): ?>
                    <td class="audit-extra-spacer"></td>
                    <td class="audit-extra-spacer"></td>
                    <?php endif; ?>

                    <td>
                        <?php if ($hasUnit): ?>
                        <span class="assign-pill <?= $assignClass ?>">
                            <i class="fa-solid fa-building"></i>
                            <?= htmlspecialchars($unit) ?>
                        </span>
                        <?php if ($hasMoreRows && $unitIndex === ($visibleLimit - 1)): ?>
                        <div class="audit-row-more-inline audit-more-control-<?= $auditId ?>">
                            <button type="button" class="audit-row-more-btn" onclick="toggleAuditRows(<?= $auditId ?>, this)">
                                Lihat Lagi
                            </button>
                        </div>
                        <?php endif; ?>
                        <?php else: ?>
                        -
                        <?php endif; ?>
                    </td>

                    <td>
                        <?php if ($hasUnit): ?>
                            <?php if ($canGiveFeedback && $isAssignedFeedbackUser && $isFeedbackWindowOpen): ?>
                            <a href="maklum_balas_audit.php?id=<?= $auditId ?>" class="action-btn feedback-btn aligned-feedback-btn">
                                <i class="fa-solid fa-comment-dots"></i>
                                <?= isset($unitFeedbackMap[$auditId][$unit]) ? 'Kemaskini Maklum Balas' : 'Isi Maklum Balas' ?>
                            </a>
                            <?php elseif ($unitFeedbackId > 0): ?>
                            <a href="detail_maklum_balas_audit.php?id=<?= $unitFeedbackId ?>" class="action-btn feedback-btn aligned-feedback-btn">
                                <i class="fa-solid fa-comment-dots"></i>
                                View Maklum Balas
                            </a>
                            <?php elseif ($canGiveFeedback): ?>
                                <?php if ($isBeforeAuditStart): ?>
                                <span class="field-note">Belum boleh diisi. Tarikh mula: <?= htmlspecialchars(date('d/m/Y', strtotime($tarikhMula))) ?></span>
                                <?php elseif ($isAfterAuditEnd): ?>
                                <span class="field-note">Tempoh maklum balas telah tamat pada <?= htmlspecialchars(date('d/m/Y', strtotime($tarikhAkhir))) ?></span>
                                <?php else: ?>
                                <span class="field-note">Ditugaskan kepada <?= htmlspecialchars($assignedFeedbackUserName !== '' ? $assignedFeedbackUserName : 'pengguna lain') ?></span>
                                <?php endif; ?>
                            <?php else: ?>
                            <span class="field-note">Belum ada maklum balas</span>
                            <?php endif; ?>
                        <?php else: ?>
                        -
                        <?php endif; ?>
                    </td>

                    <td>
                        <?php if ($hasUnit): ?>
                        <div class="audit-note-text <?= $auditNote === '' ? 'audit-note-empty' : '' ?>">
                            <?= nl2br(htmlspecialchars($auditNote !== '' ? $auditNote : 'Belum ada catatan audit')) ?>
                        </div>
                        <?php else: ?>
                        -
                        <?php endif; ?>
                    </td>

                    <td class="audit-approval-cell">
                        <?php if ($hasUnit): ?>
                            <?php if ($isManagement): ?>
                            <form method="POST" action="proses_kelulusan_audit.php" class="dropdown-form">
                                <input type="hidden" name="audit_id" value="<?= $auditId ?>">
                                <input type="hidden" name="assigned_unit" value="<?= htmlspecialchars($unit) ?>">
                                <input type="hidden" name="audit_approval_status" value="" class="target-audit-approval-input">
                                <div class="dropdown-pill <?= $unitApprovalClass ?>">
                                    <span class="dropdown-dot"></span>
                                    <span class="dropdown-label"><?= $unitApprovalValue === 'lulus_diaudit' ? 'Selesai Audit' : 'Perlu Kemaskini' ?></span>
                                    <button type="button" class="dropdown-arrow-btn" onclick="openDropdownMenu(event, this)">
                                        <i class="fa-solid fa-chevron-down"></i>
                                    </button>
                                </div>
                                <div class="dropdown-menu">
                                    <button type="button" class="dropdown-option-btn" onclick="submitAuditApprovalOption(this, 'perlu_kemaskini')">
                                        <span class="dropdown-option-dot approval-needs-update"></span>
                                        <span>Perlu Kemaskini</span>
                                    </button>
                                    <button type="button" class="dropdown-option-btn" onclick="submitAuditApprovalOption(this, 'lulus_diaudit')">
                                        <span class="dropdown-option-dot approval-approved"></span>
                                        <span>Selesai Audit</span>
                                    </button>
                                </div>
                            </form>
                            <?php else: ?>
                            <div class="dropdown-pill static <?= $unitApprovalClass ?>">
                                <span class="dropdown-dot"></span>
                                <span class="dropdown-label"><?= $unitApprovalValue === 'lulus_diaudit' ? 'Selesai Audit' : 'Perlu Kemaskini' ?></span>
                            </div>
                            <?php endif; ?>
                        <?php else: ?>
                        -
                        <?php endif; ?>
                    </td>

                    <?php if ($isManagement && $unitIndex === 0): ?>
                    <td rowspan="<?= $rowspan ?>">
                        <div class="action-stack">
                            <a href="senarai_maklumat_audit.php" class="action-btn edit-btn"><i class="fa-solid fa-eye"></i> View More</a>
                        </div>
                    </td>
                    <?php elseif ($isManagement && $unitIndex >= $visibleLimit): ?>
                    <td class="audit-extra-spacer"></td>
                    <?php endif; ?>
                </tr>
                <?php endforeach; ?>
                <?php if ($hasMoreRows): ?>
                <tr class="audit-hidden-row audit-extra-<?= $auditId ?> audit-row-less">
                    <td class="audit-extra-spacer"></td>
                    <td class="audit-extra-spacer"></td>
                    <td colspan="<?= $isManagement ? '5' : '4' ?>">
                        <button type="button" class="audit-row-more-btn" onclick="toggleAuditRows(<?= $auditId ?>, this)">
                            Lihat Kurang
                        </button>
                    </td>
                </tr>
                <?php endif; ?>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="<?= $isManagement ? '7' : '6' ?>" class="empty-state">Tiada maklumat audit ditemui.</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>

</div>

<?php render_layout_end(<<<'HTML'
<script>
function openDropdownMenu(event, button) {
    event.preventDefault();
    event.stopPropagation();
    document.querySelectorAll('.dropdown-menu.show').forEach((menu) => {
        if (!button.closest('.dropdown-form').contains(menu)) {
            menu.classList.remove('show');
        }
    });
    const form = button.closest('.dropdown-form');
    const menu = form ? form.querySelector('.dropdown-menu') : null;
    if (menu) {
        menu.classList.toggle('show');
    }
}

function submitAuditApprovalOption(button, targetStatus) {
    const form = button.closest('.dropdown-form');
    const input = form ? form.querySelector('.target-audit-approval-input') : null;
    if (!form || !input) {
        return;
    }
    input.value = targetStatus;
    form.submit();
}

function toggleAuditRows(id, button) {
    const rows = document.querySelectorAll('.audit-extra-' + id);
    const shouldShow = Array.from(rows).some((row) => !row.classList.contains('show'));
    rows.forEach((row) => {
        row.classList.toggle('show', shouldShow);
    });
    document.querySelectorAll('.audit-more-control-' + id).forEach((control) => {
        control.style.display = shouldShow ? 'none' : '';
    });
}

function toggleAssignMore(id, button) {
    const extra = document.getElementById('assign-extra-' + id);
    if (!extra) {
        return;
    }
    extra.classList.toggle('show');
    button.textContent = extra.classList.contains('show') ? 'View Less' : 'View More';
}

function toggleFeedbackMore(id, button) {
    const extra = document.getElementById('feedback-extra-' + id);
    if (!extra) {
        return;
    }
    extra.classList.toggle('show');
    button.textContent = extra.classList.contains('show') ? 'View Less' : 'View More';
}

function toggleAuditNoteMore(id, button) {
    const extra = document.getElementById('audit-note-extra-' + id);
    if (!extra) {
        return;
    }
    extra.classList.toggle('show');
    button.textContent = extra.classList.contains('show') ? 'View Less' : 'View More';
}

document.addEventListener('click', function (event) {
    document.querySelectorAll('.dropdown-menu.show').forEach((menu) => {
        if (!menu.closest('.dropdown-form').contains(event.target)) {
            menu.classList.remove('show');
        }
    });
});
</script>
HTML); ?>
