<?php
require_once 'auth.php';
include 'db.php';
requireLogin($conn);

$role = $_SESSION['role'] ?? 'user';
$user_department = currentUserDepartment($conn);

$draft_id = (int) ($_GET['id'] ?? 0);
if ($draft_id <= 0) {
    header("Location: draft_letters.php?error=not_found");
    exit();
}

$draft_sql = "SELECT ld.*, f.folder_name, f.folder_code, d.id AS active_document_id, d.file_numbering, d.file_path AS active_document_file_path,
        ld.preparer_signed_at,
        department_officer.position AS department_officer_position,
        creator.short_name AS created_by_short_name,
        creator.fullname AS created_by_fullname,
        creator.fullname AS created_by_name,
        (SELECT COUNT(*) FROM documents d2 WHERE d2.folder_id = ld.folder_id AND d2.deleted_at IS NULL AND d2.id <= ld.document_id) AS computed_file_numbering
    FROM letter_drafts ld
    INNER JOIN folders f ON f.id = ld.folder_id
    LEFT JOIN documents d ON d.id = ld.document_id AND d.deleted_at IS NULL
    LEFT JOIN users department_officer ON department_officer.id = ld.department_officer_user_id
    LEFT JOIN users creator ON creator.id = ld.created_by
    WHERE ld.id = ? AND ld.deleted_at IS NULL
    LIMIT 1";
$draft_stmt = mysqli_prepare($conn, $draft_sql);
mysqli_stmt_bind_param($draft_stmt, "i", $draft_id);
mysqli_stmt_execute($draft_stmt);
$draft = mysqli_fetch_assoc(mysqli_stmt_get_result($draft_stmt));

if (!$draft) {
    header("Location: draft_letters.php?error=not_found");
    exit();
}

$current_user_id = (int) ($_SESSION['user_id'] ?? 0);
$current_user = null;
if ($current_user_id > 0) {
    $current_user_stmt = mysqli_prepare($conn, "SELECT id, fullname, department, position, role, status FROM users WHERE id = ? LIMIT 1");
    if ($current_user_stmt) {
        mysqli_stmt_bind_param($current_user_stmt, "i", $current_user_id);
        mysqli_stmt_execute($current_user_stmt);
        $current_user = mysqli_fetch_assoc(mysqli_stmt_get_result($current_user_stmt)) ?: null;
    }
}
$is_draft_creator = (int) ($draft['created_by'] ?? 0) === $current_user_id;
$draft_approval_status = $draft['approval_status'] ?? 'draft';
$draft_has_entered_workflow = $draft_approval_status !== '' && $draft_approval_status !== 'draft';
$current_recipient_rows = getLetterApprovalRecipients($conn, $draft_id, $current_user_id);
$current_recipient = $current_recipient_rows[0] ?? null;
$is_workflow_participant = $draft_has_entered_workflow && (
    (int) ($draft['support_user_id'] ?? 0) === $current_user_id
    || (int) ($draft['department_officer_user_id'] ?? 0) === $current_user_id
    || (int) ($draft['memo_preparer_head_user_id'] ?? 0) === $current_user_id
    || !empty($current_recipient)
);
$draft_same_department = isSameDepartmentDb($conn, $draft['department'] ?? '', $user_department);
$can_manage_this_draft = $is_draft_creator || ($role === 'superadmin' && $draft_same_department);
$is_private_draft = ($draft['status'] ?? 'draf') === 'draf' || ($draft['approval_status'] ?? 'draft') === 'draft';
if ($is_private_draft && !$is_draft_creator && $role !== 'superadmin' && !$is_workflow_participant) {
    header("Location: draft_letters.php?error=unauthorized");
    exit();
}
$approval_stage = (int) ($draft['approval_stage'] ?? 1);
$approval_status_key = $draft['approval_status'] ?? (($draft['support_status'] ?? '') === 'disokong' ? 'lulus' : 'menunggu_pelulus');
$is_surat_rasmi = strcasecmp(trim((string) ($draft['doc_type'] ?? '')), 'Surat Rasmi') === 0;
$is_memo = strcasecmp(trim((string) ($draft['doc_type'] ?? '')), 'Memo') === 0;
if (($is_memo || $is_surat_rasmi)
    && (int) ($draft['include_distribution_page'] ?? 0) === 1
    && function_exists('isStaffDistributionPageContentInvalid')
    && isStaffDistributionPageContentInvalid($draft['distribution_page_content'] ?? '')
) {
    $rebuilt_distribution_content = buildStaffDistributionPageContent($conn, $draft['distribution_staff_list'] ?? '[]');
    if (!isStaffDistributionPageContentInvalid($rebuilt_distribution_content)) {
        $draft['distribution_page_content'] = $rebuilt_distribution_content;
    }
}
$document_preview_label = 'Paparan ' . ucwords(strtolower(trim((string) ($draft['doc_type'] ?? 'Dokumen'))));
$document_status_label = 'Status ' . ucwords(strtolower(trim((string) ($draft['doc_type'] ?? 'Dokumen'))));
$draft_edit_page = $is_surat_rasmi
    ? 'Surat_Rasmi.php'
    : (strcasecmp(trim((string) ($draft['doc_type'] ?? '')), 'Memo') === 0 ? 'Memo.php' : 'Memo_Kelulusan.php');
$approval_recipients = getLetterApprovalRecipients($conn, $draft_id);
$max_approval_route_order = 0;
foreach ($approval_recipients as $approval_route) {
    $max_approval_route_order = max($max_approval_route_order, (int) ($approval_route['route_order'] ?? 0));
}
$can_print_or_export_pdf = canDraftLetterBePrinted($conn, $draft, $approval_recipients, $current_user_id);
$can_replace_letter_file = $is_draft_creator
    && $approval_status_key === 'lulus'
    && (int) ($draft['document_id'] ?? 0) > 0;
$can_edit_this_draft = currentUserCan($conn, 'draft_letter', 'update')
    && $can_manage_this_draft
    && $approval_status_key !== 'lulus'
    && !$can_print_or_export_pdf;
$can_edit_this_draft = false;
$is_department_officer_actor = $approval_stage === 1
    && (int) ($draft['department_officer_user_id'] ?? 0) === $current_user_id
    && in_array($draft['department_officer_status'] ?? '', ['menunggu', 'menunggu_tandatangan'], true);
$is_memo_preparer_head_review_actor = ($is_memo || $is_surat_rasmi)
    && $approval_stage === 1
    && (int) ($draft['memo_preparer_head_user_id'] ?? 0) === $current_user_id
    && ($draft['memo_preparer_head_status'] ?? '') === 'menunggu';
$is_routing_actor = $approval_stage >= 2
    && $current_recipient
    && in_array($current_recipient['status'] ?? '', ['menunggu', 'menunggu_tandatangan'], true);
$is_current_approver = $is_memo_preparer_head_review_actor || $is_department_officer_actor || $is_routing_actor;
$current_user_is_management = isSameDepartmentDb($conn, $current_user['department'] ?? '', 'Pengurusan');
$current_user_is_head_officer = isHeadOfficerPosition($current_user['position'] ?? '');
$can_self_edit_revision = $is_memo_preparer_head_review_actor
    || (($is_memo || $is_surat_rasmi) && $is_department_officer_actor && $current_user_is_head_officer && !$current_user_is_management);
$can_resume_department_officer_revision = $approval_status_key === 'sedang_dipinda_ketua_bahagian'
    && $approval_stage === 1
    && ((int) ($draft['department_officer_user_id'] ?? 0) === $current_user_id
        || (int) ($draft['memo_preparer_head_user_id'] ?? 0) === $current_user_id);
$current_action_status = $is_department_officer_actor
    ? ($draft['department_officer_status'] ?? '')
    : ($is_memo_preparer_head_review_actor ? ($draft['memo_preparer_head_status'] ?? '') : ($current_recipient['status'] ?? ''));
$current_action_decision = $is_department_officer_actor
    ? ($draft['department_officer_decision'] ?? 'belum_diputuskan')
    : ($is_memo_preparer_head_review_actor ? 'belum_diputuskan' : ($current_recipient['decision'] ?? 'belum_diputuskan'));
$current_action_is_final_recipient = $is_routing_actor
    && $max_approval_route_order > 0
    && (int) ($current_recipient['route_order'] ?? 0) === $max_approval_route_order;
$current_action_positive_label = ($is_department_officer_actor || $is_memo_preparer_head_review_actor)
    ? 'Sahkan'
    : ($current_action_is_final_recipient ? 'Diluluskan' : 'Disokong');
$current_action_negative_label = ($is_department_officer_actor || $is_memo_preparer_head_review_actor)
    ? 'Mohon Pindaan'
    : ($current_action_is_final_recipient ? 'Tidak Diluluskan' : 'Tidak Disokong');
$current_action_instruction = ($is_department_officer_actor || $is_memo_preparer_head_review_actor)
    ? 'Semak kandungan surat di bawah. Anda boleh sahkan surat atau mohon pindaan dengan ulasan.'
    : ($current_action_is_final_recipient
        ? 'Semak kandungan surat di bawah. Anda boleh meluluskan surat atau tidak meluluskannya dengan ulasan.'
        : 'Semak kandungan surat di bawah. Anda boleh menyokong surat atau tidak menyokongnya dengan ulasan.');
$current_user_signature_path = getUserSignaturePath($conn, $current_user_id);
$department_officer_signature_in_pages = $current_user_signature_path !== ''
    && strpos((string) ($draft['letter_pages'] ?? ''), $current_user_signature_path) !== false;
$department_officer_already_signed_revision = $is_department_officer_actor
    && (
        (
            trim((string) ($draft['department_officer_signature_path'] ?? '')) !== ''
            && is_file(__DIR__ . '/' . trim((string) ($draft['department_officer_signature_path'] ?? '')))
        )
        || $department_officer_signature_in_pages
    );
$is_support_user = $is_current_approver || $is_workflow_participant || (int) ($draft['support_user_id'] ?? 0) === $current_user_id;
if (!currentUserCan($conn, 'draft_letter', 'read') && !$is_support_user) {
    echo "<script>alert('Anda tidak mempunyai kebenaran untuk melihat surat ini.'); window.location='dashboard.php';</script>";
    exit();
}
if ($role !== 'superadmin' && !$is_support_user && !isSameDepartmentDb($conn, $draft['department'] ?? '', $user_department)) {
    header("Location: draft_letters.php?error=unauthorized");
    exit();
}

$status_message = '';
if (isset($_GET['success'])) {
    if ($_GET['success'] === 'created') {
        $status_message = 'Draf surat berjaya diwujudkan. Anda boleh semak, cetak, atau simpan sebagai PDF melalui pelayar.';
    } elseif ($_GET['success'] === 'updated') {
        $status_message = 'Draf surat berjaya dikemaskini.';
    } elseif ($_GET['success'] === 'letter_replaced') {
        $status_message = 'Fail surat berjaya diganti. No. rujukan dan maklumat surat dikekalkan.';
    }
} elseif (isset($_GET['replace_error'])) {
    $replace_error = (string) $_GET['replace_error'];
    if ($replace_error === 'permission') {
        $status_message = 'Hanya penyedia surat boleh menggantikan fail surat yang telah lulus.';
    } elseif ($replace_error === 'status') {
        $status_message = 'Fail surat hanya boleh diganti selepas status surat lulus.';
    } elseif ($replace_error === 'format') {
        $status_message = 'Format fail tidak dibenarkan. Sila pilih fail PDF, DOC atau DOCX sahaja.';
    } elseif ($replace_error === 'size') {
        $status_message = 'Saiz fail melebihi 10MB.';
    } elseif ($replace_error === 'missing') {
        $status_message = 'Sila pilih fail surat untuk diganti.';
    } else {
        $status_message = 'Fail surat tidak dapat diganti. Sila cuba semula.';
    }
} elseif (isset($_GET['support_success'])) {
    $support_success = (string) $_GET['support_success'];
    if (in_array($support_success, ['disokong', 'approved'], true)) {
        $status_message = 'Surat telah diluluskan. Sila lengkapkan tandatangan untuk meneruskan edaran.';
    } elseif ($support_success === 'rejected_pending_signature' || $support_success === 'ditolak') {
        $status_message = 'Penolakan dan ulasan telah direkodkan. Sila lengkapkan tandatangan untuk mengesahkan penolakan.';
    } elseif ($support_success === 'tandatangan') {
        $status_message = 'Tandatangan berjaya direkodkan pada surat.';
    } elseif ($support_success === 'revision_returned') {
        $status_message = 'Permohonan pindaan telah dihantar semula kepada penyedia surat.';
    } elseif ($support_success === 'revision_saved') {
        $status_message = 'Pindaan surat berjaya disimpan. Sila semak semula dan tandatangan untuk meneruskan flow.';
    } else {
        $status_message = 'Surat ini telah ditolak dan ulasan telah direkodkan.';
    }
} elseif (isset($_GET['support_error'])) {
    $support_error = (string) $_GET['support_error'];
    if ($support_error === 'signature_required') {
        $status_message = 'Tandatangan anda belum didaftarkan dalam database sistem.';
    } elseif ($support_error === 'note_required') {
        $status_message = 'Sila isi catatan sebelum meneruskan tindakan ini.';
    } elseif ($support_error === 'revision_locked') {
        $status_message = 'Surat sedang dipinda oleh Ketua Bahagian. Anda hanya boleh melihat status buat masa ini.';
    } elseif ($support_error === 'export_not_ready') {
        $status_message = 'Surat hanya boleh dicetak atau diexport selepas semua pelulus selesai menandatangani dan surat kembali kepada penyedia.';
    } elseif ($support_error === 'export_disabled') {
        $status_message = 'Export Word tidak disediakan untuk surat ini.';
    } elseif ($support_error === 'pdf_export_failed') {
        $status_message = 'Export PDF tidak dapat dijana. Sila pastikan Chrome atau Edge tersedia pada komputer server.';
    } else {
        $status_message = 'Tindakan sokongan tidak dapat diselesaikan.';
    }
}

$status_labels = getDraftLetterStatusList();
$support_status_labels = getDraftLetterSupportStatusList();
$approval_status_labels = getDraftLetterApprovalStatusList();
$recipient_status_labels = [
    'belum_mula' => 'Belum Mula',
    'menunggu' => 'Menunggu Kelulusan',
    'menunggu_tandatangan' => 'Menunggu Tandatangan',
    'lulus' => 'Lulus dan Ditandatangani',
    'ditolak' => 'Ditolak',
];
$department_status_labels = [
    'tidak_perlu' => 'Tidak Perlu',
    'menunggu' => 'Menunggu Kelulusan',
    'menunggu_tandatangan' => 'Menunggu Tandatangan',
    'lulus' => 'Lulus dan Ditandatangani',
    'ditolak' => 'Ditolak',
];
$approval_status_icon = in_array($approval_status_key, ['lulus', 'disokong'], true)
    ? 'fa-circle-check'
    : ($approval_status_key === 'ditolak' ? 'fa-circle-xmark' : 'fa-clock');
$letter_pages = decodeDraftLetterPages($draft['letter_pages'] ?? '', $draft['letter_body'] ?? '');
$letter_page_signers = decodeDraftLetterPageSigners($draft['letter_page_signers'] ?? '', count($letter_pages));
$display_file_numbering = '';
if (($draft['status'] ?? '') === 'siap') {
    $stored_file_numbering = trim((string) ($draft['file_numbering'] ?? ''));
    $display_file_numbering = ($stored_file_numbering !== '' && strtoupper($stored_file_numbering) !== 'X' && $stored_file_numbering !== ($draft['ref_no'] ?? ''))
        ? $stored_file_numbering
        : ($draft['computed_file_numbering'] ?? '');
} elseif (strcasecmp($draft['doc_type'] ?? '', 'Surat Rasmi') === 0) {
    $display_file_numbering = 'X';
}
$ruj_kami_display = formatDraftLetterReferenceDisplay(
    $draft['department'] ?? '',
    $draft['ref_no'] ?? '',
    $display_file_numbering
);
$ruj_kami_display = preg_replace('/\s+JLD\.\s*(\d+)\s*\(([^)]+)\)$/i', ' Jld. $1 ($2)', $ruj_kami_display);

function replaceSuratRasmiPrintReferenceLine($html, $reference_display) {
    $reference_display = htmlspecialchars(trim((string) $reference_display), ENT_QUOTES);
    return preg_replace_callback(
        '/(<p\b(?=[^>]*data-surat-rasmi-generated-line=(?:"ref"|\'ref\'))[^>]*>)(.*?)(<\/p>)/is',
        function ($matches) use ($reference_display) {
            return $matches[1] . $reference_display . $matches[3];
        },
        (string) $html
    );
}

function normalizeMemoDistributionPrintText($html) {
    return preg_replace('/\s+/u', '', html_entity_decode(strip_tags((string) $html), ENT_QUOTES, 'UTF-8'));
}

function isMemoDistributionPrintPage($page_body, $distribution_content) {
    $distribution_text = normalizeMemoDistributionPrintText($distribution_content);
    $page_text = normalizeMemoDistributionPrintText($page_body);
    return $distribution_text !== ''
        && $page_text !== ''
        && mb_strlen($page_text, 'UTF-8') >= 20
        && strpos($distribution_text, $page_text) !== false
        && stripos((string) $page_body, 'SENARAI EDARAN') === false;
}
$attachment_map = getDocumentAttachmentsMap($conn, [['id' => (int) ($draft['document_id'] ?? 0)]]);
$attachments = $attachment_map[(int) ($draft['document_id'] ?? 0)] ?? [];
$replacement_attachment = null;
foreach ($attachments as $attachment) {
    if ((int) ($attachment['is_replacement_letter'] ?? 0) === 1) {
        $replacement_attachment = $attachment;
        break;
    }
}
if (!$replacement_attachment) {
    $active_document_file_path = trim((string) ($draft['active_document_file_path'] ?? ''));
    $active_document_file_name = basename(str_replace('\\', '/', $active_document_file_path));
    if ($active_document_file_path !== '' && stripos($active_document_file_name, 'replace_') === 0) {
        foreach ($attachments as $attachment) {
            if (trim((string) ($attachment['file_path'] ?? '')) === $active_document_file_path) {
                $replacement_attachment = $attachment;
                break;
            }
        }
    }
}
$has_replacement_letter_file = !empty($replacement_attachment);
$preview_attachments = $has_replacement_letter_file ? [$replacement_attachment] : $attachments;

function getDraftAttachmentPreviewType($attachment) {
    $file_path = strtolower((string) ($attachment['file_path'] ?? ''));
    $original_name = strtolower((string) ($attachment['original_name'] ?? ''));
    $extension = pathinfo($original_name !== '' ? $original_name : $file_path, PATHINFO_EXTENSION);

    if ($extension === 'pdf') {
        return 'pdf';
    }

    if (in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp'], true)) {
        return 'image';
    }

    return 'file';
}

function getDraftAttachmentDisplayName($attachment) {
    $name = trim((string) ($attachment['original_name'] ?? ''));
    if ($name !== '') {
        return $name;
    }

    return basename((string) ($attachment['file_path'] ?? 'Lampiran sokongan'));
}

function sanitizePrintInlineStyle($style) {
    $safe_styles = [];
    $has_small_font = false;
    foreach (explode(';', (string) $style) as $declaration) {
        $parts = explode(':', $declaration, 2);
        if (count($parts) !== 2) {
            continue;
        }
        $property = strtolower(trim($parts[0]));
        $value = trim($parts[1]);
        if ($property === 'text-align' && preg_match('/^(left|center|right|justify)$/i', $value)) {
            $safe_styles[] = 'text-align: ' . strtolower($value);
        } elseif ($property === 'margin-left' && preg_match('/^(?:0|[0-9]+(?:\.[0-9]+)?(?:cm|mm|pt|px))$/i', $value)) {
            $safe_styles[] = 'margin-left: ' . strtolower($value);
        } elseif (in_array($property, ['height', 'min-height', 'width', 'min-width'], true) && preg_match('/^(?:0|[0-9]+(?:\.[0-9]+)?(?:cm|mm|pt|px))$/i', $value)) {
            $safe_styles[] = $property . ': ' . strtolower($value);
        } elseif ($property === 'display' && strtolower($value) === 'flex') {
            $safe_styles[] = 'display: flex';
        } elseif ($property === 'align-items' && strtolower($value) === 'center') {
            $safe_styles[] = 'align-items: center';
        } elseif ($property === 'justify-content' && in_array(strtolower($value), ['center', 'flex-start'], true)) {
            $safe_styles[] = 'justify-content: ' . strtolower($value);
        } elseif ($property === 'margin' && preg_match('/^(?:0|[0-9]+(?:\.[0-9]+)?(?:cm|mm|pt|px))$/i', $value)) {
            $safe_styles[] = 'margin: ' . strtolower($value);
        } elseif ($property === 'font-size' && preg_match('/^8(?:px|pt)$/i', $value)) {
            $safe_styles[] = 'font-size: 8px';
            $has_small_font = true;
        } elseif (in_array($property, ['line-height', 'font-size', 'font-family'], true)) {
            continue;
        }
    }

    $safe_styles[] = 'font-family: Arial, Helvetica, sans-serif';
    if (!$has_small_font) {
        $safe_styles[] = 'font-size: 16px';
    }
    $safe_styles[] = 'line-height: 1.5';

    return implode('; ', array_unique($safe_styles));
}

function sanitizePrintImageTags($html) {
    return preg_replace_callback('/<img\b[^>]*>/i', function ($matches) {
        $tag = $matches[0];
        if (!preg_match('/\s+src\s*=\s*(["\'])(.*?)\1/i', $tag, $src_match)) {
            return '';
        }

        $src = str_replace('\\', '/', trim(html_entity_decode($src_match[2], ENT_QUOTES)));
        $is_signature = preg_match('#^uploads/signatures/[A-Za-z0-9._/-]+\.(?:png|jpe?g|gif|webp)$#i', $src);
        $is_known_asset = in_array($src, ['mainpp.png'], true);
        if (!$is_signature && !$is_known_asset) {
            return '';
        }

        $full_path = __DIR__ . '/' . $src;
        if (!is_file($full_path)) {
            return '';
        }

        $alt = $is_signature ? 'Tandatangan Digital' : 'Imej';
        $style = $is_signature
            ? 'max-width:150px;max-height:58px;object-fit:contain;'
            : 'max-width:100%;height:auto;';

        return '<img src="' . htmlspecialchars($src, ENT_QUOTES) . '" alt="' . htmlspecialchars($alt, ENT_QUOTES) . '" style="' . htmlspecialchars($style, ENT_QUOTES) . '">';
    }, $html);
}

function applyPrintBodyTypography($html) {
    $html = trim((string) $html);
    if ($html === '') {
        return '';
    }

    return preg_replace_callback('/<(p|div|li|td|th|blockquote|h3|h4|span)(\s[^>]*)?>/i', function ($matches) {
        $tag = $matches[1];
        $attrs = $matches[2] ?? '';

        if (preg_match('/style\s*=\s*(["\'])(.*?)\1/i', $attrs, $style_match)) {
            $quote = $style_match[1];
            $safe_style = sanitizePrintInlineStyle($style_match[2]);
            $attrs = preg_replace(
                '/style\s*=\s*(["\']).*?\1/i',
                'style=' . $quote . htmlspecialchars($safe_style, ENT_QUOTES) . $quote,
                $attrs,
                1
            );
        } else {
            $attrs .= ' style="font-family: Arial, Helvetica, sans-serif; font-size: 16px; line-height: 1.5"';
        }

        return '<' . $tag . $attrs . '>';
    }, $html);
}

function normalizeQuillListHtml($html) {
    $html = (string) $html;
    if (stripos($html, 'data-list') === false && stripos($html, 'ql-ui') === false) {
        return $html;
    }

    $html = preg_replace('/<span\b(?=[^>]*\bclass\s*=\s*(["\'])[^"\']*\bql-ui\b[^"\']*\1)[^>]*>\s*<\/span>/i', '', $html);
    return preg_replace_callback('/<ol\b([^>]*)>(.*?)<\/ol>/is', function ($matches) {
        $content = $matches[2];
        if (stripos($content, 'data-list') === false) {
            return $matches[0];
        }

        preg_match_all('/<li\b([^>]*)>(.*?)<\/li>/is', $content, $items, PREG_SET_ORDER);
        if (empty($items)) {
            return $matches[0];
        }

        $html_parts = [];
        $current_type = '';
        foreach ($items as $item) {
            $attrs = $item[1] ?? '';
            $item_type = preg_match('/\bdata-list\s*=\s*(["\'])bullet\1/i', $attrs) ? 'ul' : 'ol';
            $attrs = preg_replace('/\s*data-list\s*=\s*(["\']).*?\1/i', '', $attrs);
            $attrs = preg_replace('/\s*data-list\s*=\s*[^\s>]+/i', '', $attrs);
            if ($current_type !== $item_type) {
                if ($current_type !== '') {
                    $html_parts[] = '</' . $current_type . '>';
                }
                $current_type = $item_type;
                $html_parts[] = '<' . $current_type . '>';
            }
            $html_parts[] = '<li' . $attrs . '>' . $item[2] . '</li>';
        }
        if ($current_type !== '') {
            $html_parts[] = '</' . $current_type . '>';
        }

        return implode('', $html_parts);
    }, $html);
}

function forcePreparedByPrintSize($html) {
    return preg_replace_callback('/<(span|div)(\s[^>]*)?>(\s*Disediakan\s+Oleh\s*:.*?<\/\1>)/is', function ($matches) {
        $tag = $matches[1];
        $attrs = $matches[2] ?? '';
        $content = $matches[3];
        $prepared_style = 'display: block; margin-top: 0; font-family: Arial, Helvetica, sans-serif; font-size: 8px !important; line-height: 1; font-weight: 400';

        if (preg_match('/style\s*=\s*(["\'])(.*?)\1/i', $attrs, $style_match)) {
            $quote = $style_match[1];
            $style = preg_replace('/font-size\s*:\s*[^;]+;?/i', '', $style_match[2]);
            $style = preg_replace('/line-height\s*:\s*[^;]+;?/i', '', $style);
            $style = preg_replace('/font-family\s*:\s*[^;]+;?/i', '', $style);
            $style = trim($style);
            $style = $prepared_style . ($style !== '' ? '; ' . $style : '');
            $attrs = preg_replace(
                '/style\s*=\s*(["\']).*?\1/i',
                'style=' . $quote . htmlspecialchars($style, ENT_QUOTES) . $quote,
                $attrs,
                1
            );
        } else {
            $attrs .= ' style="' . htmlspecialchars($prepared_style, ENT_QUOTES) . '"';
        }

        return '<' . $tag . $attrs . '>' . $content;
    }, (string) $html);
}

function renderDraftLetterBody($html) {
    $html = trim((string) $html);
    if ($html === '') {
        return '';
    }

    $html = preg_replace('/(<div\b[^>]*class\s*=\s*(["\'])generated-closing-lock\s+signature-block\2)\s+signature-block(?:"|\')/i', '$1', $html);
    $html = preg_replace('/<div\b(?=[^>]*data-generated-closing\s*=\s*(["\'])1\1)(?![^>]*\sclass\s*=)/i', '<div class="generated-closing-lock signature-block"', $html);
    $html = normalizeQuillListHtml($html);

    $allowed_tags = '<p><br><strong><b><em><i><u><ol><ul><li><table><thead><tbody><tr><th><td><colgroup><col><blockquote><h3><h4><div><span><img>';
    $html = strip_tags($html, $allowed_tags);
    $html = preg_replace('/\s+on[a-z]+\s*=\s*(".*?"|\'.*?\'|[^\s>]+)/i', '', $html);
    $html = preg_replace_callback('/\s+style\s*=\s*(["\'])(.*?)\1/i', function ($matches) {
        $safe_style = sanitizePrintInlineStyle($matches[2]);
        return $safe_style !== '' ? ' style="' . htmlspecialchars($safe_style, ENT_QUOTES) . '"' : '';
    }, $html);
    $html = preg_replace('/\s+style\s*=\s*(?!["\'])[^\s>]+/i', '', $html);
    $html = preg_replace('/\s+id\s*=\s*(".*?"|\'.*?\'|[^\s>]+)/i', '', $html);
    $html = preg_replace_callback('/\s+class\s*=\s*(["\'])(.*?)\1/i', function ($matches) {
        $classes = preg_split('/\s+/', trim((string) $matches[2]));
        $allowed_classes = array_values(array_intersect($classes, ['generated-closing-lock', 'signature-block', 'prepared-by-line']));
        return !empty($allowed_classes) ? ' class="' . htmlspecialchars(implode(' ', $allowed_classes), ENT_QUOTES) . '"' : '';
    }, $html);
    $html = preg_replace_callback('/\s+class\s*=\s*(?!["\'])([^\s>]+)/i', function ($matches) {
        $classes = preg_split('/\s+/', trim((string) $matches[1]));
        $allowed_classes = array_values(array_intersect($classes, ['generated-closing-lock', 'signature-block', 'prepared-by-line']));
        return !empty($allowed_classes) ? ' class="' . htmlspecialchars(implode(' ', $allowed_classes), ENT_QUOTES) . '"' : '';
    }, $html);
    $html = preg_replace('/javascript\s*:/i', '', $html);
    $html = sanitizePrintImageTags($html);

    // Jika tiada HTML tags, bungkus teks dalam <p>
    if (strip_tags($html) === $html) {
        $paragraphs = preg_split("/\n\s*\n/", str_replace(["\r\n", "\r"], "\n", $html));
        $converted = '';
        foreach ($paragraphs as $paragraph) {
            $paragraph = trim($paragraph);
            if ($paragraph !== '') {
                // Normalize whitespace dalam paragraph
                $paragraph = preg_replace('/\s+/', ' ', $paragraph);
                $converted .= '<p style="font-family: Arial, Helvetica, sans-serif; font-size: 16px; line-height: 1.5">' . nl2br(htmlspecialchars($paragraph)) . '</p>';
            }
        }
        return forcePreparedByPrintSize(applyPrintBodyTypography($converted));
    }

    // Untuk HTML yang sedia ada, pastikan text wrapping yang betul
    // Bungkus text nodes dalam <p> jika perlu
    $html = preg_replace_callback('/>([^<]+)</', function($matches) {
        $content = $matches[1];
        if (trim($content) !== '' && strpos($content, '<') === false) {
            // Normalize multiple whitespace kepada single space
            $content = preg_replace('/\s+/', ' ', $content);
            return '>' . $content . '<';
        }
        return $matches[0];
    }, $html);

    return forcePreparedByPrintSize(applyPrintBodyTypography($html));
}

function injectPreparerSignatureIntoGeneratedClosing($html, $draft) {
    $signature_path = trim((string) ($draft['signatory_signature_path'] ?? ''));
    if ($signature_path === '' || !is_file(__DIR__ . '/' . $signature_path)) {
        $signature_path = trim((string) ($draft['department_officer_signature_path'] ?? ''));
        if ($signature_path !== '' && is_file(__DIR__ . '/' . $signature_path)) {
            $department_officer_status = trim((string) ($draft['department_officer_status'] ?? ''));
            if ($department_officer_status !== 'lulus') {
                $signature_path = '';
            }
        } else {
            $signature_path = '';
        }
    }

    if ($signature_path === '') {
        return $html;
    }

    $signature_img = '<img src="' . htmlspecialchars($signature_path, ENT_QUOTES) . '" alt="Tandatangan Digital" style="max-width:150px;max-height:58px;object-fit:contain;">';
    $pattern = '/(<p\b[^>]*data-generated-signature\s*=\s*(["\'])1\2[^>]*>).*?(<\/p>)/is';
    if (preg_match($pattern, (string) $html)) {
        return preg_replace($pattern, '$1' . $signature_img . '$3', (string) $html, 1);
    }

    return $html;
}

function formatMalayMemoDate($date) {
    $timestamp = strtotime((string) $date);
    if (!$timestamp) {
        return '-';
    }

    $months = [
        1 => 'Januari', 2 => 'Februari', 3 => 'Mac', 4 => 'April',
        5 => 'Mei', 6 => 'Jun', 7 => 'Julai', 8 => 'Ogos',
        9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Disember',
    ];

    return date('d', $timestamp) . ' ' . $months[(int) date('n', $timestamp)] . ' ' . date('Y', $timestamp);
}

function getDraftPageSigner($draft, $signer_key) {
    $signer_key = (string) $signer_key;

    if ($signer_key === 'department_officer') {
        return [
            'name' => $draft['department_officer_name'] ?? '',
            'position' => getDisplayPositionForDepartment($draft['department'] ?? '', $draft['department_officer_position'] ?? 'Ketua Pegawai') ?: 'Ketua Pegawai',
            'signature' => (($draft['department_officer_status'] ?? '') === 'lulus') ? ($draft['department_officer_signature_path'] ?? '') : '',
        ];
    }

    if ($signer_key === 'preparer') {
        return [
            'name' => $draft['signatory_name'] ?? '',
            'position' => getDisplayPositionForDepartment(($draft['signatory_department'] ?? '') ?: ($draft['department'] ?? ''), $draft['signatory_position'] ?? ''),
            'department' => $draft['signatory_department'] ?? '',
            'signature' => $draft['signatory_signature_path'] ?? '',
            'prepared_by' => trim((string) (($draft['created_by_short_name'] ?? '') ?: ($draft['created_by_fullname'] ?? ''))),
        ];
    }

    return null;
}

function renderDraftPageSignature($draft, $signer_key) {
    $signer = getDraftPageSigner($draft, $signer_key);
    if (!$signer || trim((string) ($signer['name'] ?? '')) === '') {
        return;
    }

    $signature_path = trim((string) ($signer['signature'] ?? ''));
    ?>
    <div class="signature-box">
        <div class="signature-space">
            <?php if ($signature_path !== '' && is_file(__DIR__ . '/' . $signature_path)): ?>
            <img src="<?= htmlspecialchars($signature_path) ?>" alt="Tandatangan">
            <?php endif; ?>
        </div>
        <div><strong>(<?= htmlspecialchars(strtoupper($signer['name'])) ?>)</strong></div>
        <?php if ($signer_key === 'preparer' && trim((string) ($signer['prepared_by'] ?? '')) !== ''): ?>
        <div class="prepared-by-line">Disediakan Oleh: <?= htmlspecialchars($signer['prepared_by']) ?></div>
        <?php endif; ?>
        <?php if ($signer_key !== 'preparer' && !empty($signer['position'])): ?>
        <div><?= htmlspecialchars($signer['position']) ?></div>
        <?php endif; ?>
        <?php if ($signer_key !== 'preparer' && !empty($signer['department'])): ?>
        <div><?= htmlspecialchars($signer['department']) ?></div>
        <?php endif; ?>
    </div>
    <?php
}

function renderMemoApprovalChoiceBoxes($is_final_approver, $status, $decision) {
    $is_final_approver = (bool) $is_final_approver;
    $status = trim((string) $status);
    $decision = trim((string) $decision);

    if ($is_final_approver) {
        $positive_checked = in_array($decision, ['lulus'], true) || $status === 'lulus';
        $negative_checked = in_array($decision, ['ditolak'], true) || $status === 'ditolak';
        $positive_label = 'Diluluskan';
        $negative_label = 'Tidak Diluluskan';
    } else {
        $positive_checked = in_array($decision, ['lulus'], true) || in_array($status, ['menunggu_tandatangan', 'lulus'], true);
        $negative_checked = in_array($decision, ['ditolak'], true) || $status === 'ditolak';
        $positive_label = 'Disokong';
        $negative_label = 'Tidak Disokong';
    }

    ?>
    <div class="approval-choice-boxes">
        <label class="choice-box">
            <input type="checkbox" disabled<?= $positive_checked ? ' checked' : '' ?>>
            <span><?= htmlspecialchars($positive_label) ?></span>
        </label>
        <label class="choice-box">
            <input type="checkbox" disabled<?= $negative_checked ? ' checked' : '' ?>>
            <span><?= htmlspecialchars($negative_label) ?></span>
        </label>
    </div>
    <?php
}

function splitMemoPrintDisplayPositions($value) {
    $items = preg_split('/\r\n|\r|\n/', (string) $value);
    $values = [];
    foreach ($items as $item) {
        $item = trim((string) $item);
        if ($item !== '' && !in_array($item, $values, true)) {
            $values[] = $item;
        }
    }
    return $values;
}

function renderMemoPrintDisplayValue($value) {
    $positions = splitMemoPrintDisplayPositions($value);
    if (empty($positions)) {
        return '-';
    }

    $rows = [];
    foreach ($positions as $position) {
        $display_position = $position;
        if (preg_match('/^Pegawai:\s*(.*?)\s*\(user:\d+\)$/iu', $position, $matches)) {
            $display_position = trim((string) $matches[1]);
        }
        $without_organization = preg_match('/^Pegawai:/iu', $position)
            || strcasecmp($position, 'Seperti dalam Senarai Edaran') === 0;
        $rows[] = htmlspecialchars($display_position)
            . ($without_organization ? '' : ',<br>Majlis Agama Islam Negeri Pulau Pinang');
    }
    return implode('<br>', $rows);
}

function formatMemoApprovalDateTimeDisplay($status, $signature_path, $approved_at, $responded_at) {
    $status = trim((string) $status);
    $signature_path = trim((string) $signature_path);
    $is_signed = in_array($status, ['lulus', 'ditolak'], true)
        && $signature_path !== ''
        && is_file(__DIR__ . '/' . $signature_path);

    $date = '....................';
    $time = '';

    if ($is_signed && trim((string) $responded_at) !== '') {
        $timestamp = strtotime((string) $responded_at);
        if ($timestamp !== false) {
            $date = date('d/m/Y', $timestamp);
            $time = date('H:i', $timestamp);
        }
    } elseif ($status === 'menunggu_tandatangan' && trim((string) $approved_at) !== '') {
        $timestamp = strtotime((string) $approved_at);
        if ($timestamp !== false) {
            $date = date('d/m/Y', $timestamp);
        }
    }

    return ['date' => $date, 'time' => $time];
}

function renderMemoApprovalDecisionSection($label, $name, $position, $signature_path, $status, $approved_at = '', $responded_at = '', $recipient_body = '', $note = '', $recipient_user_id = 0, $decision = '', $is_final_approver = false) {
    $label = trim((string) $label);
    $name = trim((string) $name);
    $position = trim((string) $position);
    if ($name === '' && $position === '') {
        return;
    }

    $status = trim((string) $status);
    $is_signed = in_array($status, ['lulus', 'ditolak'], true) && trim((string) $signature_path) !== '' && is_file(__DIR__ . '/' . $signature_path);
    $approval_datetime = formatMemoApprovalDateTimeDisplay($status, $signature_path, $approved_at, $responded_at);
    $approval_date = $approval_datetime['date'];
    $approval_time = $approval_datetime['time'];
    ?>
    <div class="approval-decision-section" data-approval-user-id="<?= (int) $recipient_user_id ?>">
        <?php if (trim((string) $recipient_body) !== ''): ?>
        <div class="approval-recipient-body"><?= renderDraftLetterBody($recipient_body) ?></div>
        <?php endif; ?>
        <?php renderMemoApprovalChoiceBoxes($is_final_approver, $status, $decision); ?>
        <p class="approval-comment-title">Ulasan <?= htmlspecialchars($label) ?> MAINPP:</p>
        <div class="approval-recorded-note"><?= nl2br(htmlspecialchars($note)) ?></div>
        <div class="approval-sign-row">
            <div class="approval-date">Tarikh: <?= htmlspecialchars($approval_date) ?><?php if ($approval_time !== ''): ?> <?= htmlspecialchars($approval_time) ?><?php endif; ?></div>
            <div class="approval-signature-line">
                <div class="approval-dotted-line<?= $is_signed ? ' has-signature' : '' ?>">
                    <?php if ($is_signed): ?>
                    <img src="<?= htmlspecialchars($signature_path) ?>" alt="Tandatangan">
                    <?php endif; ?>
                </div>
                <?php if ($name !== ''): ?>
                <strong>(<?= htmlspecialchars(strtoupper($name)) ?>)</strong>
                <?php endif; ?>
                <?php if ($position !== ''): ?>
                <span><?= htmlspecialchars($position) ?></span>
                <?php endif; ?>
                <span>Majlis Agama Islam Negeri Pulau Pinang</span>
            </div>
        </div>
    </div>
    <?php
}

function formatDraftFlowTimestamp($value) {
    $value = trim((string) $value);
    if ($value === '' || $value === '0000-00-00 00:00:00') {
        return '';
    }

    $timestamp = strtotime($value);
    return $timestamp ? date('d/m/Y H:i', $timestamp) : '';
}

function buildDraftFlowSteps($draft, $approval_recipients) {
    $steps = [];
    $is_memo_flow = strcasecmp(trim((string) ($draft['doc_type'] ?? '')), 'Memo') === 0;
    $is_surat_rasmi_flow = strcasecmp(trim((string) ($draft['doc_type'] ?? '')), 'Surat Rasmi') === 0;
    $is_memo_kelulusan_flow = strcasecmp(trim((string) ($draft['doc_type'] ?? '')), 'Memo Kelulusan') === 0;
    $max_route_order = 0;
    foreach ((array) $approval_recipients as $approval_recipient) {
        $max_route_order = max($max_route_order, (int) ($approval_recipient['route_order'] ?? 0));
    }
    $department_officer_status = $draft['department_officer_status'] ?? 'tidak_perlu';
    $has_department_officer_step = !empty($draft['department_officer_name']) || $department_officer_status !== 'tidak_perlu';
    $memo_head_status = $draft['memo_preparer_head_status'] ?? 'tidak_perlu';
    $has_memo_preparer_head_step = ($is_memo_flow || $is_surat_rasmi_flow)
        && ((int) ($draft['memo_preparer_head_user_id'] ?? 0) > 0 || $memo_head_status !== 'tidak_perlu');
    if ($has_department_officer_step) {
        $preparer_status = 'disediakan';
        $preparer_signed_at = '';
    } else {
        $preparer_status = ($draft['status'] ?? 'draf') === 'siap'
            ? (($is_memo_flow || $is_memo_kelulusan_flow) ? 'disediakan_ditandatangani' : 'lulus')
            : (($is_memo_flow || $is_memo_kelulusan_flow) ? 'disediakan' : 'belum_mula');
        $preparer_signed_at = formatDraftFlowTimestamp(($draft['preparer_signed_at'] ?? '') ?: (($draft['status'] ?? 'draf') === 'siap' ? ($draft['updated_at'] ?? '') : ''));
    }
    $steps[] = [
        'label' => 'Penyedia',
        'name' => ($draft['created_by_name'] ?? '') ?: ($draft['signatory_name'] ?? '-'),
        'status' => $preparer_status,
        'received_label' => 'Disediakan pada',
        'received_at' => formatDraftFlowTimestamp($draft['created_at'] ?? ''),
        'signed_label' => $has_department_officer_step ? 'Disahkan pada' : 'Ditandatangani pada',
        'signed_at' => $preparer_signed_at,
    ];

    if ($has_memo_preparer_head_step) {
        $memo_head_flow_status = $memo_head_status === 'lulus' ? 'disahkan' : $memo_head_status;
        $steps[] = [
            'label' => 'Ketua Bahagian Penyedia',
            'name' => $draft['memo_preparer_head_name'] ?? '-',
            'status' => $memo_head_flow_status,
            'received_label' => 'Diterima pada',
            'received_at' => formatDraftFlowTimestamp($draft['memo_preparer_head_requested_at'] ?? ''),
            'signed_label' => 'Disahkan pada',
            'signed_at' => formatDraftFlowTimestamp($draft['memo_preparer_head_responded_at'] ?? ''),
        ];
    }

    if ($has_department_officer_step) {
        $department_officer_flow_status = $draft['department_officer_status'] ?? 'belum_mula';
        if (($is_memo_flow || $is_surat_rasmi_flow) && $has_memo_preparer_head_step && $department_officer_flow_status === 'tidak_perlu') {
            $department_officer_flow_status = 'belum_mula';
        } elseif ($is_memo_flow && $department_officer_flow_status === 'lulus') {
            $department_officer_flow_status = $has_memo_preparer_head_step ? 'ditandatangani' : 'disahkan_ditandatangani';
        } elseif ($is_memo_kelulusan_flow && $department_officer_flow_status === 'lulus') {
            $department_officer_flow_status = 'disahkan_ditandatangani';
        } elseif (!$is_memo_flow && !$is_memo_kelulusan_flow && $department_officer_flow_status === 'lulus') {
            $department_officer_flow_status = 'disahkan_ditandatangani';
        }
        $steps[] = [
            'label' => ($is_memo_flow || ($is_surat_rasmi_flow && $has_memo_preparer_head_step)) ? 'Penandatangan' : 'Ketua Pegawai',
            'name' => $draft['department_officer_name'] ?? '-',
            'status' => $department_officer_flow_status,
            'received_label' => 'Diterima pada',
            'received_at' => formatDraftFlowTimestamp($draft['department_officer_requested_at'] ?? ''),
            'signed_at' => formatDraftFlowTimestamp($draft['department_officer_responded_at'] ?? ''),
        ];
    }

    foreach ($approval_recipients as $recipient) {
        $recipient_source_type = $recipient['source_type'] ?? '';
        $recipient_status = $recipient['status'] ?? 'belum_mula';
        if ($recipient_source_type === 'kepada' && $recipient_status === 'lulus') {
            $recipient_status = 'diterima';
        } elseif ($is_memo_flow && $recipient_status === 'lulus') {
            $recipient_status = 'diterima';
        } elseif ($is_memo_kelulusan_flow && $recipient_status === 'lulus') {
            $recipient_status = ((int) ($recipient['route_order'] ?? 0) >= $max_route_order)
                ? 'diluluskan_ditandatangani'
                : 'disokong_ditandatangani';
        }
        $source_labels = [
            'kepada' => 'Penerima Kepada',
            'melalui' => 'Penerima Melalui',
            'tambahan' => 'Edaran Kelulusan Tambahan',
        ];
        $steps[] = [
            'label' => $source_labels[$recipient_source_type] ?? 'Penerima Kelulusan',
            'name' => ($recipient['fullname'] ?? '') ?: ($recipient['position_label'] ?? '-'),
            'status' => $recipient_status,
            'received_label' => 'Diterima pada',
            'received_at' => formatDraftFlowTimestamp($recipient['requested_at'] ?? ''),
            'signed_label' => $recipient_source_type === 'kepada' ? 'Diterima pada' : 'Ditandatangani pada',
            'signed_at' => formatDraftFlowTimestamp($recipient['responded_at'] ?? ''),
        ];
    }

    return $steps;
}

function buildDraftFlowCurrentHolder($draft, $approval_recipients) {
    $approval_status = $draft['approval_status'] ?? 'draft';
    if (($draft['status'] ?? 'draf') === 'draf' || $approval_status === 'draft') {
        return [
            'label' => 'sekarang',
            'name' => ($draft['created_by_name'] ?? '') ?: ($draft['signatory_name'] ?? '-'),
            'received_label' => 'Disediakan pada',
            'received_at' => formatDraftFlowTimestamp($draft['created_at'] ?? ''),
            'signed_at' => formatDraftFlowTimestamp(($draft['preparer_signed_at'] ?? '') ?: (($draft['status'] ?? 'draf') === 'siap' ? ($draft['updated_at'] ?? '') : '')),
        ];
    }

    if ($approval_status === 'menunggu_pegawai_bahagian') {
        if (
            in_array(strtolower(trim((string) ($draft['doc_type'] ?? ''))), ['memo', 'surat rasmi'], true)
            && ($draft['memo_preparer_head_status'] ?? '') === 'menunggu'
            && (int) ($draft['memo_preparer_head_user_id'] ?? 0) > 0
        ) {
            return [
                'label' => 'sekarang',
                'name' => $draft['memo_preparer_head_name'] ?? '-',
                'received_label' => 'Diterima pada',
                'received_at' => formatDraftFlowTimestamp($draft['memo_preparer_head_requested_at'] ?? ''),
                'signed_at' => formatDraftFlowTimestamp($draft['memo_preparer_head_responded_at'] ?? ''),
            ];
        }
        return [
            'label' => 'sekarang',
            'name' => $draft['department_officer_name'] ?? '-',
            'received_label' => 'Diterima pada',
            'received_at' => formatDraftFlowTimestamp($draft['department_officer_requested_at'] ?? ''),
            'signed_at' => formatDraftFlowTimestamp($draft['department_officer_responded_at'] ?? ''),
        ];
    }

    if ($approval_status === 'perlu_pindaan_penyedia') {
        return [
            'label' => 'sekarang',
            'name' => ($draft['created_by_name'] ?? '') ?: ($draft['signatory_name'] ?? '-'),
            'received_label' => 'Dikembalikan pada',
            'received_at' => formatDraftFlowTimestamp($draft['updated_at'] ?? ''),
            'signed_at' => '',
        ];
    }

    if ($approval_status === 'sedang_dipinda_ketua_bahagian') {
        return [
            'label' => 'sekarang',
            'name' => $draft['department_officer_name'] ?? '-',
            'received_label' => 'Pindaan bermula pada',
            'received_at' => formatDraftFlowTimestamp($draft['updated_at'] ?? ''),
            'signed_at' => '',
        ];
    }

    $pending_recipients = array_values(array_filter($approval_recipients, function ($recipient) {
        return in_array($recipient['status'] ?? '', ['menunggu', 'menunggu_tandatangan'], true);
    }));
    if ($approval_status === 'menunggu_pelulus' || $approval_status === 'menunggu_pelulus_akhir') {
        $current = $pending_recipients[0] ?? ($approval_recipients[0] ?? null);
        if ($current) {
            return [
                'label' => 'sekarang',
                'name' => ($current['fullname'] ?? '') ?: ($current['position_label'] ?? '-'),
                'received_label' => 'Diterima pada',
                'received_at' => formatDraftFlowTimestamp($current['requested_at'] ?? ''),
                'signed_at' => formatDraftFlowTimestamp($current['responded_at'] ?? ''),
            ];
        }
    }

    if ($approval_status === 'lulus') {
        $completed = array_values(array_filter($approval_recipients, function ($recipient) {
            return ($recipient['status'] ?? '') === 'lulus';
        }));
        $current = $completed ? end($completed) : ($approval_recipients ? end($approval_recipients) : null);
        if ($current) {
            return [
                'label' => 'sekarang',
                'name' => ($current['fullname'] ?? '') ?: ($current['position_label'] ?? '-'),
                'received_label' => 'Diterima pada',
                'received_at' => formatDraftFlowTimestamp($current['requested_at'] ?? ''),
                'signed_at' => formatDraftFlowTimestamp($current['responded_at'] ?? ''),
            ];
        }
    }

    if ($approval_status === 'ditolak') {
        $rejected = array_values(array_filter($approval_recipients, function ($recipient) {
            return ($recipient['status'] ?? '') === 'ditolak';
        }));
        $current = $rejected ? end($rejected) : null;
        if (!$current && ($draft['department_officer_status'] ?? '') === 'ditolak') {
            return [
                'label' => 'sekarang',
                'name' => $draft['department_officer_name'] ?? '-',
                'received_label' => 'Diterima pada',
                'received_at' => formatDraftFlowTimestamp($draft['department_officer_requested_at'] ?? ''),
                'signed_at' => formatDraftFlowTimestamp($draft['department_officer_responded_at'] ?? ''),
            ];
        }
        if ($current) {
            return [
                'label' => 'sekarang',
                'name' => ($current['fullname'] ?? '') ?: ($current['position_label'] ?? '-'),
                'received_label' => 'Diterima pada',
                'received_at' => formatDraftFlowTimestamp($current['requested_at'] ?? ''),
                'signed_at' => formatDraftFlowTimestamp($current['responded_at'] ?? ''),
            ];
        }
    }

    return [
        'label' => 'sekarang',
        'name' => ($draft['created_by_name'] ?? '') ?: ($draft['signatory_name'] ?? '-'),
        'received_label' => 'Disediakan pada',
        'received_at' => formatDraftFlowTimestamp($draft['created_at'] ?? ''),
        'signed_at' => formatDraftFlowTimestamp(($draft['preparer_signed_at'] ?? '') ?: (($draft['status'] ?? 'draf') === 'siap' ? ($draft['updated_at'] ?? '') : '')),
    ];
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Semak Surat | <?= htmlspecialchars($draft['ref_no']) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <?php renderAppShellAssets(); ?>
    <style>
        :root {
            --primary: #0077b6; --primary-dark: #005f99; --secondary: #00b4d8;
            --superadmin: #6c5ce7; --superadmin-dark: #5b4cdb;
            --bg-light: #f8fbfd; --bg-card: #ffffff; --text-main: #1a3a5c;
            --text-muted: #6c757d; --border: #e0e8f0; --sidebar-width: 240px;
            --success: #1a9955; --danger: #dc3545; --warning: #ffc107;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', 'Inter', Tahoma, Geneva, Verdana, sans-serif; }
        body { background: linear-gradient(135deg, #e0f7fa 0%, #f1f8e9 100%); min-height: 100vh; display: flex; color: var(--text-main); }

        .sidebar { width: var(--sidebar-width); background: linear-gradient(180deg, #fff 0%, #f8fbfd 100%); border-right: 1px solid var(--border); position: fixed; height: 100vh; padding: 20px 0; overflow-y: auto; overflow-x: hidden; z-index: 1000; box-shadow: 2px 0 10px rgba(0,0,0,0.03); transition: width 0.3s ease; display:flex; flex-direction:column; }
        .sidebar.collapsed { width: 70px; }
        .sidebar-header { text-align: center; padding: 0 20px 20px; border-bottom: 1px solid var(--border); margin-bottom: 20px; white-space: nowrap; overflow: hidden; }
        .sidebar.collapsed .sidebar-header h3, .sidebar.collapsed .sidebar-header p, .sidebar.collapsed .menu-text { display: none; }
        .sidebar-header img { width: 50px; margin-bottom: 10px; transition: margin 0.3s ease; }
        .sidebar.collapsed .sidebar-header img { margin: 0 auto 10px; }
        .sidebar-header h3 { font-size: 1rem; font-weight: 700; color: var(--primary); margin-bottom: 4px; }
        .sidebar-header p { font-size: 0.75rem; color: var(--text-muted); }
        .role-badge { display: inline-block; padding: 3px 10px; border-radius: 12px; font-size: 0.7rem; font-weight: 600; margin-left: 8px; }
        .role-badge.user { background: #e6f4ff; color: var(--primary); }
        .role-badge.admin { background: #d4edda; color: var(--success); }
        .role-badge.superadmin { background: linear-gradient(90deg, var(--superadmin), var(--superadmin-dark)); color: #fff; }
        .sidebar-menu { list-style: none; padding: 0 10px; display:flex; flex-direction:column; flex:1; }
        .sidebar-section { padding: 10px 18px 6px; color: var(--text-muted); font-size: 0.72rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; }
        .sidebar-spacer { margin-top: auto; }
        .sidebar-menu li a { display: flex; align-items: center; gap: 12px; padding: 12px 18px; color: var(--text-main); text-decoration: none; border-radius: 8px; margin-bottom: 4px; transition: all 0.2s ease; font-size: 0.9rem; white-space: nowrap; }
        .sidebar-menu li a:hover, .sidebar-menu li a.active { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; }
        .sidebar-menu li a i { width: 20px; text-align: center; font-size: 1.1rem; }
        .sidebar-menu .dropdown { position: relative; }
        .sidebar-menu .dropdown-toggle { display: flex; align-items: center; justify-content: space-between; width: 100%; padding: 12px 18px; color: var(--text-main); background: none; border: none; border-radius: 8px; cursor: pointer; font-size: 0.9rem; text-align: left; transition: all 0.2s ease; }
        .sidebar-menu .dropdown-toggle:hover, .sidebar-menu .dropdown-toggle.active { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; }
        .sidebar-menu .dropdown-toggle i.chevron { transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); font-size: 0.8rem; }
        .sidebar-menu .dropdown.active .dropdown-toggle i.chevron { transform: rotate(180deg); }
        .sidebar-menu .dropdown-menu { display: flex; flex-direction: column; padding-left: 42px; margin-top: 4px; max-height: 0; opacity: 0; overflow: hidden; transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.25s ease; }
        .sidebar-menu .dropdown.active .dropdown-menu { max-height: 260px; opacity: 1; }
        .sidebar-menu .dropdown-menu a { padding: 8px 18px; color: var(--text-main); text-decoration: none; border-radius: 6px; font-size: 0.85rem; display: flex; align-items: center; gap: 8px; opacity: 0; transform: translateY(-5px); transition: opacity 0.2s ease, transform 0.2s ease; }
        .sidebar-menu .dropdown.active .dropdown-menu a { opacity: 1; transform: translateY(0); }
        .sidebar-menu .dropdown-menu a:hover, .sidebar-menu .dropdown-menu a.active { background: #e6f4ff; color: var(--primary); }
        .sidebar.collapsed + .main { margin-left: 70px; }
        .sidebar-toggle { position: absolute; right: -12px; top: 20px; width: 24px; height: 24px; background: var(--primary); color: #fff; border: none; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 0.7rem; box-shadow: 0 2px 6px rgba(0,0,0,0.15); transition: transform 0.3s ease; z-index: 1001; }
        .sidebar.collapsed .sidebar-toggle { transform: rotate(180deg); }
        .main { margin-left: var(--sidebar-width); flex: 1; min-width: 0; width: calc(100% - var(--sidebar-width)); padding: 25px 30px; transition: margin-left 0.3s ease; }
        .top-bar { background: var(--bg-card); padding: 15px 25px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.04); margin-bottom: 25px; display: flex; justify-content: space-between; align-items: center; border: 1px solid var(--border); }
        .top-bar h2 { color: var(--primary); font-size: 1.3rem; font-weight: 600; display: flex; align-items: center; gap: 8px; }
        .user-info { display: flex; align-items: center; gap: 15px; font-size: 0.9rem; color: var(--text-muted); }
        .user-info span { color: var(--primary); font-weight: 600; }
        .user-info a { color: var(--danger); text-decoration: none; font-weight: 500; display: flex; align-items: center; gap: 5px; }
        .user-info a:hover { text-decoration: underline; }
        .alert { background: #ecfdf3; color: #166534; padding: 13px 16px; border-radius: 8px; margin-bottom: 18px; border: 1px solid #bbf7d0; border-left: 4px solid var(--success); }
        .document-command { background: var(--bg-card); border: 1px solid var(--border); border-radius: 8px; margin-bottom: 18px; box-shadow: 0 8px 24px rgba(15, 58, 92, 0.06); overflow: hidden; }
        .document-summary { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 24px; align-items: center; padding: 18px 20px; }
        .document-kicker { color: var(--text-muted); font-size: 0.76rem; font-weight: 700; text-transform: uppercase; margin-bottom: 5px; }
        .document-title { color: var(--text-main); font-size: 1.12rem; line-height: 1.35; overflow-wrap: anywhere; }
        .document-reference { color: var(--text-muted); font-size: 0.86rem; margin-top: 6px; display: flex; gap: 14px; flex-wrap: wrap; }
        .document-reference strong { color: var(--primary-dark); }
        .summary-status { min-width: 180px; text-align: right; }
        .summary-status label { display: block; color: var(--text-muted); font-size: 0.75rem; font-weight: 700; margin-bottom: 6px; }
        .toolbar { border-top: 1px solid var(--border); background: #f8fbfd; padding: 12px 20px; display: flex; justify-content: flex-end; align-items: center; gap: 10px; flex-wrap: wrap; }
        .toolbar-actions { display: flex; gap: 10px; flex-wrap: wrap; }
        .btn { min-height: 40px; padding: 9px 15px; border: 1px solid transparent; border-radius: 7px; text-decoration: none; cursor: pointer; font-size: 0.88rem; display: inline-flex; align-items: center; justify-content: center; gap: 8px; font-weight: 700; transition: background 0.2s ease, border-color 0.2s ease, transform 0.2s ease; }
        .btn:hover { transform: translateY(-1px); }
        .btn-primary { background: var(--primary); color: #fff; }
        .btn-primary:hover { background: var(--primary-dark); }
        .btn-secondary { background: #fff; color: var(--primary-dark); border-color: #cbdbe7; }
        .btn-secondary:hover { background: #eef7fb; border-color: #9fc5d8; }
        .btn-danger { background: #fff; color: #b42318; border-color: #fecaca; }
        .btn-danger:hover { background: #fff1f2; }
        .replace-letter-form { display: inline-flex; margin: 0; }
        .replace-letter-form input[type="file"] { display: none; }
        .page-sheet { position: relative; background: #fff; width: 210mm; min-width: 210mm; max-width: 210mm; height: 297mm; min-height: 297mm; max-height: 297mm; margin: 0 auto; box-shadow: 0 18px 40px rgba(15, 23, 42, 0.12); border: 1px solid #dbe7ef; overflow: hidden; color: #111827; font-family: Arial, Helvetica, sans-serif; }
        .page-sheet + .page-sheet { margin-top: 22px; }
        .page-sheet-inner { height: 100%; padding: 25.4mm 18mm; overflow: hidden; display: flex; flex-direction: column; line-height: 1.5; }
        .approval-sheet .page-sheet-inner { display: block; }
        .page-sheet-inner p,
        .page-sheet-inner div,
        .page-sheet-inner span,
        .page-sheet-inner li,
        .page-sheet-inner td,
        .signature-box,
        .signature-box div,
        .memo-print-closing,
        .memo-print-closing div,
        .approval-recipient-body,
        .approval-recipient-body p,
        .approval-recipient-body div,
        .approval-decision-section,
        .approval-signature-line strong,
        .approval-signature-line span,
        .approval-comment-title,
        .approval-recorded-note,
        .choice-box {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 16px;
            line-height: 1.5;
        }
        .page-sheet :not(i) { font-family: Arial, Helvetica, sans-serif; font-size: 16px; }
        .page-sheet:not(.surat-rasmi-sheet) :not(i),
        .page-sheet:not(.surat-rasmi-sheet) .page-sheet-inner p,
        .page-sheet:not(.surat-rasmi-sheet) .page-sheet-inner div,
        .page-sheet:not(.surat-rasmi-sheet) .page-sheet-inner span,
        .page-sheet:not(.surat-rasmi-sheet) .page-sheet-inner li,
        .page-sheet:not(.surat-rasmi-sheet) .page-sheet-inner td,
        .page-sheet:not(.surat-rasmi-sheet) .signature-box,
        .page-sheet:not(.surat-rasmi-sheet) .signature-box div,
        .page-sheet:not(.surat-rasmi-sheet) .memo-print-closing,
        .page-sheet:not(.surat-rasmi-sheet) .memo-print-closing div,
        .page-sheet:not(.surat-rasmi-sheet) .approval-recipient-body,
        .page-sheet:not(.surat-rasmi-sheet) .approval-recipient-body p,
        .page-sheet:not(.surat-rasmi-sheet) .approval-recipient-body div,
        .page-sheet:not(.surat-rasmi-sheet) .approval-decision-section,
        .page-sheet:not(.surat-rasmi-sheet) .approval-signature-line strong,
        .page-sheet:not(.surat-rasmi-sheet) .approval-signature-line span,
        .page-sheet:not(.surat-rasmi-sheet) .approval-comment-title,
        .page-sheet:not(.surat-rasmi-sheet) .approval-recorded-note,
        .page-sheet:not(.surat-rasmi-sheet) .choice-box {
            font-size: 16px !important;
        }
        .page-sheet:not(.surat-rasmi-sheet) .memo-title {
            font-size: 29px !important;
        }
        .page-sheet:not(.surat-rasmi-sheet) .memo-editor-fixed .memo-title {
            font-size: 29px !important;
        }
        .page-sheet:not(.surat-rasmi-sheet) .memo-ref-table,
        .page-sheet:not(.surat-rasmi-sheet) .memo-ref-table *,
        .page-sheet:not(.surat-rasmi-sheet) .memo-ref-table td {
            font-size: 13px !important;
        }
        .page-sheet:not(.surat-rasmi-sheet) .page-sheet-inner .memo-ref-table,
        .page-sheet:not(.surat-rasmi-sheet) .page-sheet-inner .memo-ref-table td,
        .page-sheet:not(.surat-rasmi-sheet) .page-sheet-inner .memo-ref-table div,
        .page-sheet:not(.surat-rasmi-sheet) .page-sheet-inner .memo-ref-table span {
            font-size: 13px !important;
            line-height: 1.2 !important;
        }
        .print-custom-header { position: absolute; top: 8mm; left: 18mm; right: 18mm; min-height: 7mm; color: #475569; font-size: 16px; line-height: 1.5; text-align: center; white-space: pre-wrap; }
        .print-custom-footer { position: absolute; bottom: 8mm; left: 18mm; right: 18mm; min-height: 7mm; color: #475569; font-size: 16px; line-height: 1.5; text-align: center; white-space: pre-wrap; }
        .print-custom-header p, .print-custom-footer p { margin: 0; }
        .print-page-number { position: absolute; bottom: 8mm; min-width: 10mm; text-align: center; color: #111827; font-size: 16px; line-height: 1; }
        .print-page-number.bottom_center { left: 50%; transform: translateX(-50%); }
        .print-page-number.bottom_right { right: 18mm; }
        .print-page-number.none { display: none; }
        .memo-logo { text-align: center; margin-bottom: 2px; }
        .memo-logo img { width: 130px; height: auto; object-fit: contain; }
        .memo-title { text-align: center; letter-spacing: 0; font-weight: 700; font-size: 29px; margin-bottom: 12px; padding-left: 0; }
        .memo-ref-table { width: 100%; table-layout: fixed; border-collapse: collapse; font-size: 13px; margin-bottom: 16px; }
        .memo-ref-table td { border: 1px solid #111; padding: 1mm 2mm; vertical-align: top; line-height: 1.2; }
        .memo-ref-left { width: 48%; font-weight: 400; line-height: 1.2; }
        .memo-ref-right { width: 52%; font-weight: 400; }
        .memo-ref-line { display: grid; grid-template-columns: 58px 8px minmax(0, 1fr); column-gap: 8px; align-items: start; white-space: nowrap; }
        .memo-ref-label { display: block; }
        .memo-ref-colon { display: block; text-align: center; }
        .memo-ref-value { min-width: 0; white-space: nowrap; }
        .memo-label-grid { width: 100%; border-collapse: collapse; margin-bottom: 12px; font-size: 16px; }
        .memo-label-grid td { padding: 4px 0; vertical-align: top; }
        .memo-label { width: 92px; font-weight: 400; letter-spacing: 0.02em; }
        .memo-colon { width: 18px; }
        .memo-value { font-weight: 400; }
        .memo-subject { font-weight: 700; text-transform: uppercase; }
        .letter-body { 
            color: #111827; 
            margin-bottom: 26px; 
            font-size: 16px; 
            line-height: 1.5;
            word-wrap: break-word;
            overflow-wrap: break-word;
            hyphens: auto;
            text-align: justify;
        }
        .letter-body p { 
            margin: 0;
            word-wrap: break-word;
            overflow-wrap: break-word;
            white-space: normal;
        }
        .letter-body div,
        .letter-body span {
            word-wrap: break-word;
            overflow-wrap: break-word;
        }
        .letter-body ol, .letter-body ul { margin: 0 0 12px 24px; padding-left: 18px; }
        .letter-body table { width: 100%; table-layout: fixed; border-collapse: collapse; margin: 10px 0 14px; }
        .letter-body th, .letter-body td { border: 1px solid #111; padding: 6px 8px; min-width: 80px; vertical-align: top; }
        .letter-body th { background: #f1f5f9; font-weight: 700; }
        .letter-main-body { margin-bottom: 12px; }
        .page-sheet.surat-rasmi-sheet:not(.is-extra-page) .letter-main-body {
            margin-top: 2.92cm;
            text-align: left;
        }
        .page-sheet.surat-rasmi-sheet .letter-body {
            text-align: left;
        }
        .page-sheet.surat-rasmi-sheet [data-surat-rasmi-generated-line] {
            margin-left: 2.54cm !important;
        }
        .page-sheet.surat-rasmi-sheet [data-surat-rasmi-generated-line="ref"] {
            position: relative;
            top: 0.45em;
        }
        .page-sheet.surat-rasmi-sheet [data-surat-rasmi-generated-line="date"] {
            font-size: 15.5px !important;
            line-height: 1.25 !important;
            margin-top: 0.85em !important;
        }
        .memo-print-closing { margin-top: 12px; margin-bottom: 20px; }
        .signature-box { margin-top: 24px; line-height: 1.5; color: #111827; font-size: 16px; }
        .closing-pledge { margin: 18px 0 14px; line-height: 1.5; }
        .closing-pledge strong { display: block; font-weight: 800; letter-spacing: 0.02em; }
        .signature-space { height: 58px; }
        .signature-space img { max-width: 150px; max-height: 58px; object-fit: contain; display: block; }
        .prepared-by-line { display: block; margin-top: 0; font-family: Arial, Helvetica, sans-serif; font-size: 8px !important; line-height: 1; font-weight: 400; }
        .page-sheet .letter-body .prepared-by-line,
        .page-sheet:not(.surat-rasmi-sheet) .page-sheet-inner .prepared-by-line,
        .page-sheet:not(.surat-rasmi-sheet) .signature-box .prepared-by-line,
        .page-sheet:not(.surat-rasmi-sheet) .memo-print-closing .prepared-by-line,
        .page-sheet .memo-print-closing .prepared-by-line,
        .page-sheet .letter-body span[style*="font-size:8px"],
        .page-sheet .letter-body span[style*="font-size: 8px"] {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 8px !important;
            line-height: 1 !important;
            font-weight: 400 !important;
            margin-top: 0 !important;
        }
        .approval-recipient-body { 
            font-size: 16px; 
            line-height: 1.5; 
            margin-bottom: 18px;
            word-wrap: break-word;
            overflow-wrap: break-word;
        }
        .approval-recipient-body p { 
            margin: 0;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 16px;
            line-height: 1.5;
            word-wrap: break-word;
            overflow-wrap: break-word;
        }
        .approval-recipient-body div {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 16px;
            line-height: 1.5;
        }
        .approval-decision-section { padding-top: 12px; font-size: 16px; line-height: 1.5; color: #111827; page-break-inside: avoid; }
        .approval-decision-section + .approval-decision-section { border-top: 1px solid #111; margin-top: 26px; padding-top: 20px; }
        .approval-choice-boxes { display: flex; flex-wrap: wrap; gap: 14px; align-items: center; margin: 0 0 4px; }
        .choice-box { display: inline-flex; align-items: center; gap: 8px; font-size: 16px; font-weight: 700; color: #111827; }
        .choice-box input {
            width: 14px;
            height: 14px;
            margin: 0;
            appearance: none;
            -webkit-appearance: none;
            border: 1.4px solid #111;
            background: #fff;
            position: relative;
            display: inline-grid;
            place-content: center;
        }
        .choice-box input:checked::after {
            content: "\2713";
            color: #000;
            font-size: 13px;
            font-weight: 900;
            line-height: 1;
            position: absolute;
            left: 1px;
            top: -2px;
        }
        .approval-comment-title { font-weight: 700; text-decoration: underline; margin: 6px 0 14px; line-height: 1.5; }
        .approval-recorded-note { position: relative; min-height: 54px; margin-bottom: 18px; padding: 0 2px; line-height: 1.5; white-space: pre-wrap; background: transparent; }
        .approval-recorded-note::before,
        .approval-recorded-note::after { content: ""; position: absolute; left: 0; right: 0; border-bottom: 1px solid #777; pointer-events: none; }
        .approval-recorded-note::before { top: calc(1.5em - 1px); }
        .approval-recorded-note::after { top: calc(3em - 1px); }
        .approval-sign-row { display: grid; grid-template-columns: 52mm 75mm; justify-content: space-between; align-items: start; width: 100%; margin-top: 4px; }
        .approval-date { padding-top: 0; line-height: 1.5; white-space: nowrap; }
        .approval-signature-line { width: 75mm; min-height: 20mm; text-align: left; }
        .approval-signature-line img { max-width: 30mm; max-height: 10mm; object-fit: contain; display: block; margin: 0 auto; }
        .approval-signature-line strong, .approval-signature-line span { display: block; line-height: 1.5; }
        .approval-dotted-line { border-bottom: 1px dotted #555; height: 5mm; margin: 0 0 4px; position: relative; }
        .approval-dotted-line.has-signature { height: 10mm; }
        .approval-dotted-line.has-signature img { position: absolute; left: 50%; bottom: 1px; transform: translateX(-50%); }
        .document-preview { min-width: 0; margin: 20px -30px 0; padding: 20px 30px 32px; background: #edf3f7; border-top: 1px solid #d7e3eb; border-bottom: 1px solid #d7e3eb; overflow-x: auto; }
        .preview-heading { max-width: 980px; margin: 0 auto 14px; display: flex; align-items: center; justify-content: space-between; gap: 16px; }
        .preview-heading h3 { font-size: 1rem; color: var(--text-main); display: flex; align-items: center; gap: 8px; }
        .preview-heading span { color: var(--text-muted); font-size: 0.82rem; }
        .attachment-list { max-width: 980px; margin: 18px auto 0; display: flex; flex-wrap: wrap; gap: 8px; }
        .attachment-item { background: #fff; border: 1px solid var(--border); border-radius: 7px; padding: 9px 12px; }
        .attachment-item a { color: var(--primary); text-decoration: none; font-weight: 600; }
        .attachment-item a:hover { text-decoration: underline; }
        .attachment-preview-area { max-width: 980px; margin: 22px auto 0; display: grid; gap: 16px; }
        .attachment-preview-card { background: #fff; border: 1px solid #d7e3eb; border-radius: 8px; overflow: hidden; box-shadow: 0 10px 28px rgba(15, 58, 92, 0.08); }
        .attachment-preview-header { display: flex; align-items: center; justify-content: space-between; gap: 14px; padding: 12px 14px; border-bottom: 1px solid #e2edf4; background: #f8fbfd; }
        .attachment-preview-title { min-width: 0; color: var(--text-main); font-weight: 800; font-size: 0.9rem; display: flex; align-items: center; gap: 8px; }
        .attachment-preview-title span { overflow-wrap: anywhere; }
        .attachment-preview-header a { color: var(--primary); font-weight: 700; text-decoration: none; white-space: nowrap; font-size: 0.84rem; }
        .attachment-preview-header a:hover { text-decoration: underline; }
        .attachment-preview-frame { width: 100%; height: 680px; border: 0; display: block; background: #f8fafc; }
        .attachment-preview-image { width: 100%; max-height: 680px; object-fit: contain; display: block; background: #f8fafc; }
        .attachment-preview-unavailable { padding: 22px 18px; color: var(--text-muted); font-size: 0.88rem; line-height: 1.5; background: #fff; display: flex; gap: 12px; align-items: flex-start; }
        .attachment-preview-unavailable i { color: var(--primary); margin-top: 2px; }
        .approval-workspace { display: grid; grid-template-columns: minmax(0, 1.35fr) minmax(300px, 0.65fr); gap: 18px; max-width: 1180px; margin: 0 auto 20px; align-items: start; }
        .support-panel, .action-panel { background: #fff; border: 1px solid var(--border); border-radius: 8px; padding: 18px; }
        .panel-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; margin-bottom: 16px; }
        .panel-heading h3 { color: var(--text-main); font-size: 1rem; display: flex; align-items: center; gap: 8px; }
        .panel-heading p { color: var(--text-muted); font-size: 0.82rem; margin-top: 4px; }
        .approval-route { list-style: none; display: grid; gap: 0; }
        .route-step { position: relative; display: grid; grid-template-columns: 34px minmax(0, 1fr) auto; gap: 11px; align-items: start; padding: 0 0 18px; }
        .route-step:last-child { padding-bottom: 0; }
        .route-step:not(:last-child)::after { content: ""; position: absolute; left: 16px; top: 34px; bottom: 0; width: 2px; background: #dbe7ef; }
        .route-index { width: 34px; height: 34px; border-radius: 50%; display: grid; place-items: center; background: #eef4f8; border: 1px solid #cfdde7; color: #52697d; font-weight: 800; font-size: 0.82rem; z-index: 1; }
        .route-step.lulus .route-index { background: #e8f7ef; border-color: #a7ddbf; color: #147a45; }
        .route-step.ditolak .route-index { background: #fff0f0; border-color: #f4b7b7; color: #b42318; }
        .route-step.menunggu .route-index, .route-step.menunggu_tandatangan .route-index { background: #fff7e6; border-color: #f2cf81; color: #986500; }
        .route-name { font-size: 0.9rem; color: var(--text-main); font-weight: 750; line-height: 1.5; }
        .route-role { color: var(--text-muted); font-size: 0.8rem; margin-top: 2px; }
        .route-note { margin-top: 8px; padding: 8px 10px; background: #f7fafc; border-left: 3px solid #b7cad8; color: #475569; font-size: 0.82rem; white-space: pre-wrap; }
        .route-badge { white-space: nowrap; font-size: 0.72rem; font-weight: 800; padding: 5px 8px; border-radius: 999px; background: #eef2f7; color: #52606d; }
        .route-badge.lulus { background: #e8f7ef; color: #147a45; }
        .route-badge.ditolak { background: #fff0f0; color: #b42318; }
        .route-badge.menunggu, .route-badge.menunggu_tandatangan { background: #fff7e6; color: #986500; }
        .action-panel { border-top: 4px solid var(--primary); }
        .action-panel.waiting { border-top-color: #d99a16; }
        .action-panel h3 { color: var(--text-main); font-size: 1rem; display: flex; align-items: center; gap: 8px; margin-bottom: 7px; }
        .action-panel > p, .action-panel form > p { color: var(--text-muted); font-size: 0.84rem; line-height: 1.5; }
        .action-panel textarea { width: 100%; min-height: 105px; resize: vertical; border: 1px solid #bfcfda; border-radius: 7px; padding: 11px 12px; margin: 14px 0 10px; font: inherit; }
        .action-panel textarea:focus { outline: 3px solid rgba(0, 119, 182, 0.13); border-color: var(--primary); }
        .action-panel textarea.support-note-hidden { display: none; }
        .action-panel .toolbar-actions { margin-top: 10px; }
        .action-panel .toolbar-actions .btn { flex: 1; }
        .signature-ready, .signature-missing { display: flex; gap: 9px; align-items: flex-start; border-radius: 7px; padding: 11px 12px; margin-top: 14px; font-size: 0.84rem; line-height: 1.45; }
        .signature-ready { background: #ecfdf3; color: #166534; border: 1px solid #bbf7d0; }
        .signature-missing { background: #fff7ed; color: #9a3412; border: 1px solid #fed7aa; }
        .sign-confirm-modal { position: fixed; inset: 0; z-index: 3000; display: none; align-items: center; justify-content: center; padding: 20px; background: rgba(15, 23, 42, 0.42); }
        .sign-confirm-modal.active { display: flex; }
        .sign-confirm-dialog { width: min(100%, 420px); background: #fff; border-radius: 10px; border: 1px solid var(--border); box-shadow: 0 22px 60px rgba(15, 23, 42, 0.22); padding: 20px; }
        .sign-confirm-dialog h4 { color: var(--primary-dark); font-size: 1rem; display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
        .sign-confirm-dialog p { color: var(--text-muted); line-height: 1.5; font-size: 0.9rem; margin-bottom: 16px; }
        .sign-confirm-actions { display: flex; gap: 10px; justify-content: flex-end; flex-wrap: wrap; }
        .revision-choice-list { display: grid; gap: 10px; margin: 14px 0; }
        .revision-choice-option { display: flex; align-items: center; gap: 10px; padding: 11px 12px; border: 1px solid var(--border); border-radius: 8px; background: #f8fbfd; color: var(--text-main); cursor: pointer; }
        .revision-choice-option input { width: 16px; height: 16px; accent-color: var(--primary); }
        .revision-note-label { display: block; margin: 10px 0 6px; color: var(--primary-dark); font-size: 0.85rem; font-weight: 700; }
        .revision-note-modal { width: 100%; min-height: 90px; resize: vertical; border: 1px solid var(--border); border-radius: 8px; padding: 11px 12px; font: inherit; color: var(--text-main); margin-bottom: 14px; }
        .revision-note-block { display: none; margin-top: 12px; }
        .revision-note-block.active { display: block; }
        .revision-note-display { margin: 12px 0 6px; padding: 11px 12px; border: 1px solid #dbe7ef; border-radius: 8px; background: #f8fbfd; color: var(--text-main); font-size: 0.84rem; line-height: 1.5; }
        .revision-note-display strong { display: block; color: var(--primary-dark); margin-bottom: 5px; }
        .empty-action { display: flex; gap: 10px; align-items: flex-start; color: var(--text-muted); font-size: 0.84rem; line-height: 1.45; padding: 10px 0 2px; }
        .empty-action i { color: var(--success); margin-top: 2px; }
        .support-status { display: inline-flex; align-items: center; gap: 6px; padding: 6px 11px; border-radius: 999px; font-weight: 700; font-size: 0.82rem; }
        .support-status.tidak_perlu { background: #eef2f7; color: #475569; }
        .support-status.menunggu { background: #fff4e5; color: #9a5b00; }
        .support-status.menunggu_pegawai_bahagian, .support-status.menunggu_pelulus, .support-status.menunggu_pelulus_akhir { background: #fff4e5; color: #9a5b00; }
        .support-status.perlu_pindaan_penyedia, .support-status.sedang_dipinda_ketua_bahagian { background: #e8f2ff; color: #075985; }
        .support-status.disokong { background: #e6fffb; color: #0f766e; }
        .support-status.lulus { background: #e6fffb; color: #0f766e; }
        .support-status.ditolak { background: #fde8e8; color: #b42318; }
        .flow-card { background: #fff; border: 1px solid var(--border); border-radius: 8px; padding: 18px; }
        .flow-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; margin-bottom: 14px; }
        .flow-heading h3 { color: var(--text-main); font-size: 1rem; display: flex; align-items: center; gap: 8px; }
        .flow-heading p { color: var(--text-muted); font-size: 0.82rem; margin-top: 4px; }
        .flow-current { display: flex; gap: 9px; align-items: flex-start; border-radius: 7px; padding: 11px 12px; margin-bottom: 14px; background: #f7fafc; border: 1px solid #dbe7ef; }
        .flow-current i { color: var(--draft); margin-top: 2px; }
        .flow-current strong { display: block; color: var(--text-main); font-size: 0.9rem; line-height: 1.5; }
        .flow-current span { display: block; color: var(--text-muted); font-size: 0.78rem; line-height: 1.5; margin-top: 2px; }
        .flow-list { list-style: none; display: grid; gap: 10px; }
        .flow-step { position: relative; display: grid; grid-template-columns: 18px minmax(0, 1fr) auto; gap: 10px; align-items: start; }
        .flow-dot { width: 10px; height: 10px; border-radius: 50%; background: #cbd5e1; margin: 5px auto 0; }
        .flow-dot.lulus, .flow-dot.disokong, .flow-dot.disahkan, .flow-dot.disediakan, .flow-dot.disediakan_ditandatangani, .flow-dot.disahkan_ditandatangani, .flow-dot.disokong_ditandatangani, .flow-dot.diluluskan_ditandatangani, .flow-dot.ditandatangani, .flow-dot.diterima { background: #0f766e; }
        .flow-dot.menunggu, .flow-dot.menunggu_pengesahan { background: #d97706; }
        .flow-dot.menunggu_tandatangan { background: #7c3aed; }
        .flow-dot.ditolak { background: #b42318; }
        .flow-main { min-width: 0; }
        .flow-label { font-size: 0.8rem; color: var(--text-main); font-weight: 750; line-height: 1.5; }
        .flow-name { color: var(--text-muted); font-size: 0.78rem; margin-top: 2px; line-height: 1.5; overflow-wrap: anywhere; }
        .flow-times { margin-top: 4px; display: grid; gap: 2px; color: var(--text-muted); font-size: 0.74rem; line-height: 1.5; }
        .flow-badge { white-space: nowrap; font-size: 0.72rem; font-weight: 800; padding: 5px 8px; border-radius: 999px; background: #eef2f7; color: #52606d; }
        .flow-badge.lulus, .flow-badge.disokong, .flow-badge.disahkan, .flow-badge.disediakan, .flow-badge.disediakan_ditandatangani, .flow-badge.disahkan_ditandatangani, .flow-badge.disokong_ditandatangani, .flow-badge.diluluskan_ditandatangani, .flow-badge.ditandatangani, .flow-badge.diterima { background: #e8f7ef; color: #147a45; }
        .flow-badge.ditolak { background: #fff0f0; color: #b42318; }
        .flow-badge.menunggu, .flow-badge.menunggu_pengesahan, .flow-badge.menunggu_tandatangan { background: #fff7e6; color: #986500; }
        .flow-badge.perlu_pindaan_penyedia, .flow-badge.sedang_dipinda_ketua_bahagian { background: #e8f2ff; color: #075985; }
        .page-footer { text-align: center; padding: 20px; color: var(--text-muted); font-size: 0.8rem; margin-top: 30px; }
        :root {
            --primary: #0077b6;
            --primary-dark: #005f99;
            --secondary: #00b4d8;
            --deep-blue: #023e5f;
            --bg-light: rgba(245, 250, 253, 0.72);
            --bg-card: rgba(255,255,255,0.68);
            --text-main: #163447;
            --text-muted: #2d5367;
            --border: rgba(255,255,255,0.48);
            --sidebar-width: 280px;
            --glass: rgba(255,255,255,0.58);
            --glass-strong: rgba(255,255,255,0.76);
            --shadow-soft: 0 24px 70px rgba(2,62,95,0.16);
        }
        body {
            background:
                linear-gradient(135deg, rgba(245,250,253,0.90), rgba(222,246,252,0.76)),
                url('assets/auth-bg.png') center/cover no-repeat fixed;
            color: var(--text-main);
            overflow-x: hidden;
        }
        body::before {
            content: '';
            position: fixed;
            inset: 0;
            background:
                radial-gradient(circle at 18% 18%, rgba(0,180,216,0.22), transparent 28%),
                radial-gradient(circle at 86% 12%, rgba(0,119,182,0.18), transparent 28%),
                linear-gradient(120deg, rgba(255,255,255,0.28), rgba(255,255,255,0.08));
            pointer-events: none;
            z-index: 0;
        }
        body::after {
            content: '';
            position: fixed;
            width: 520px;
            height: 520px;
            right: -180px;
            bottom: -220px;
            background: rgba(0,180,216,0.18);
            filter: blur(8px);
            transform: rotate(18deg);
            border-radius: 42px;
            pointer-events: none;
            z-index: 0;
        }
        .sidebar {
            background: linear-gradient(180deg, rgba(2,62,95,0.94), rgba(0,119,182,0.84));
            border-right: 1px solid rgba(255,255,255,0.22);
            box-shadow: 18px 0 44px rgba(2,38,60,0.20);
            backdrop-filter: blur(18px) saturate(1.25);
            overflow: hidden;
        }
        .sidebar-header {
            flex: 0 0 auto;
            background: transparent !important;
            border-bottom: 1px solid rgba(255,255,255,0.16);
        }
        .sidebar-header img {
            width: 58px;
            filter: drop-shadow(0 8px 14px rgba(0,0,0,0.22));
        }
        .sidebar-header h3 { color: #fff; font-weight: 800; }
        .sidebar-header p { color: rgba(255,255,255,0.72); }
        .sidebar-menu {
            flex: 1 1 auto;
            min-height: 0;
            overflow-y: auto;
            overflow-x: hidden;
            padding-bottom: 0;
            overscroll-behavior: contain;
            scrollbar-width: thin;
            scrollbar-color: #8f8f8f transparent;
        }
        .sidebar-menu::-webkit-scrollbar { width: 10px; }
        .sidebar-menu::-webkit-scrollbar-track { background: transparent; }
        .sidebar-menu::-webkit-scrollbar-thumb {
            background: #8f8f8f;
            border-radius: 999px;
            border: 2px solid transparent;
            background-clip: content-box;
        }
        .sidebar-menu::-webkit-scrollbar-button {
            display: none;
            width: 0;
            height: 0;
        }
        .sidebar-section { color: rgba(255,255,255,0.58); font-weight: 800; }
        .sidebar-menu li a,
        .sidebar-menu .dropdown-toggle {
            color: rgba(255,255,255,0.88);
        }
        .sidebar-menu li a:hover,
        .sidebar-menu li a.active,
        .sidebar-menu .dropdown-toggle:hover,
        .sidebar-menu .dropdown-toggle.active {
            background: rgba(255,255,255,0.18);
            color: #fff;
            box-shadow: inset 0 0 0 1px rgba(255,255,255,0.18);
        }
        .sidebar-menu .dropdown-menu a { color: rgba(255,255,255,0.78); }
        .sidebar-menu .dropdown-menu a:hover,
        .sidebar-menu .dropdown-menu a.active {
            background: rgba(255,255,255,0.16);
            color: #fff;
        }
        .sidebar-toggle {
            right: 10px;
            top: 28px;
            width: 28px;
            height: 28px;
            background: rgba(255,255,255,0.18);
            border: 1px solid rgba(255,255,255,0.22);
            box-shadow: 0 8px 20px rgba(0,0,0,0.15);
        }
        .main {
            padding: 28px 32px;
            position: relative;
            z-index: 1;
        }
        .top-bar,
        .document-command,
        .flow-card,
        .support-panel,
        .action-panel,
        .attachment-preview-card {
            background: var(--glass);
            border: 1px solid var(--border);
            box-shadow: var(--shadow-soft);
            backdrop-filter: blur(24px) saturate(1.35);
        }
        .top-bar {
            border-radius: 18px;
            padding: 16px 24px;
        }
        .top-bar h2,
        .document-title,
        .flow-heading h3,
        .action-panel h3,
        .preview-heading h3,
        .attachment-preview-title {
            color: var(--primary-dark);
            font-weight: 800;
            
        }

        .top-bar h2 i {
        color: var(--secondary);
        }
        
        .document-command,
        .flow-card,
        .support-panel,
        .action-panel,
        .attachment-preview-card {
            border-radius: 22px;
        }
        .document-summary {
            padding: 20px 22px;
        }
        .document-kicker {
            color: var(--text-muted);
            font-weight: 800;
        }
        .support-status {
            border: 1px solid rgba(255,255,255,0.48);
            box-shadow: 0 10px 22px rgba(2,62,95,0.08);
        }
        .btn {
            border-radius: 12px;
            font-weight: 800;
            transition: opacity 0.2s, transform 0.2s, box-shadow 0.2s;
        }
        .btn:hover {
            opacity: 0.96;
            transform: translateY(-1px);
        }
        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            box-shadow: 0 14px 28px rgba(0,119,182,0.18);
        }
        .btn-secondary {
            background: rgba(255,255,255,0.76);
            color: var(--primary-dark);
            border-color: rgba(0,119,182,0.18);
        }
        .btn-danger {
            background: rgba(255,255,255,0.76);
            color: #b42318;
            border-color: rgba(180,35,24,0.22);
        }
        .approval-workspace {
            max-width: 1220px;
        }
        .flow-current,
        .flow-badge,
        .attachment-preview-header,
        .attachment-preview-unavailable {
            background: rgba(255,255,255,0.62);
            border-color: rgba(255,255,255,0.56);
        }
        .flow-label,
        .flow-current strong {
            color: var(--deep-blue);
        }
        .action-panel textarea {
            background: rgba(255,255,255,0.76);
            border-color: rgba(255,255,255,0.62);
            border-radius: 12px;
            color: var(--text-main);
        }
        .action-panel textarea:focus {
            border-color: rgba(0,180,216,0.82);
            outline: none;
            box-shadow: 0 0 0 4px rgba(0,180,216,0.16);
        }
        .document-preview {
            background: rgba(237,247,250,0.62);
            border-top: 1px solid rgba(255,255,255,0.44);
            border-bottom: 1px solid rgba(255,255,255,0.44);
            backdrop-filter: blur(14px) saturate(1.18);
        }
        .page-sheet {
            background: #fff;
            box-shadow: 0 24px 52px rgba(15,23,42,0.16);
            border: 1px solid #dbe7ef;
        }
        .attachment-preview-frame,
        .attachment-preview-image {
            background: #fff;
        }
        .page-footer { color: var(--text-muted); }
        @media print {
            @page { size: 210mm 297mm; margin: 0 !important; }
            *,
            *::before,
            *::after {
                animation: none !important;
                transition: none !important;
                box-shadow: none !important;
                text-shadow: none !important;
                filter: none !important;
                backdrop-filter: none !important;
                -webkit-backdrop-filter: none !important;
                scroll-behavior: auto !important;
            }
            html {
                width: 210mm !important;
                min-width: 210mm !important;
                margin: 0 !important;
                padding: 0 !important;
                background: #fff !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            body {
                width: 210mm !important;
                min-width: 210mm !important;
                min-height: 297mm !important;
                margin: 0 !important;
                padding: 0 !important;
                background: #fff !important;
                display: block !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            .sidebar,
            .top-bar,
            .document-command,
            .attachment-list,
            .attachment-preview-area,
            .attachment-preview-frame,
            .attachment-preview-image,
            .approval-workspace,
            .preview-heading,
            .page-footer,
            nav[aria-label="Breadcrumb"],
            .alert,
            .sign-confirm-modal,
            script {
                display: none !important;
            }
            .main > :not(.document-preview) {
                display: none !important;
            }
            .main {
                width: 210mm !important;
                max-width: 210mm !important;
                min-width: 0 !important;
                margin: 0 !important;
                padding: 0 !important;
                overflow: visible !important;
                background: #fff !important;
            }
            .document-preview {
                width: 210mm !important;
                max-width: 210mm !important;
                margin: 0 !important;
                padding: 0 !important;
                background: #fff !important;
                border: 0 !important;
                overflow: visible !important;
            }
            .page-sheet {
                width: 210mm !important;
                height: 297mm !important;
                min-height: 297mm !important;
                max-height: 297mm !important;
                max-width: none !important;
                margin: 0 !important;
                box-shadow: none !important;
                border: 0 !important;
                overflow: hidden !important;
                transform: none !important;
                zoom: 1 !important;
                background: #fff !important;
                page-break-after: always;
                break-after: page;
            }
            .page-sheet:last-child {
                page-break-after: auto;
                break-after: auto;
            }
            .page-sheet + .page-sheet {
                margin-top: 0 !important;
                page-break-before: auto;
                break-before: auto;
            }
            .page-sheet-inner {
                width: 100%;
                height: 100%;
                padding: 25.4mm 18mm !important;
                overflow: hidden !important;
            }
            .approval-sheet .page-sheet-inner {
                display: block !important;
            }
            .letter-body,
            .letter-body p,
            .letter-body div,
            .letter-body span,
            .approval-recipient-body,
            .approval-recipient-body p {
                word-wrap: break-word !important;
                overflow-wrap: break-word !important;
                white-space: normal !important;
                max-width: 100% !important;
            }
        }
        @media (max-width: 992px) {
            .sidebar { width: 70px; }
            .sidebar .sidebar-header h3, .sidebar .sidebar-header p, .sidebar .menu-text, .sidebar .role-badge, .sidebar .dropdown-menu, .sidebar .sidebar-section { display: none; }
            .main { margin-left: 70px; width: calc(100% - 70px); min-width: 0; overflow-x: hidden; }
            .sidebar-toggle { display: none; }
            .approval-workspace { grid-template-columns: 1fr; }
            .document-preview { margin-left: -30px; margin-right: -30px; }
        }
        @media (max-width: 680px) {
            .main { padding: 16px 12px; }
            .top-bar { padding: 13px 15px; }
            .top-bar h2 { font-size: 1.05rem; line-height: 1.25; }
            .top-bar .user-info { display: none !important; }
            .document-summary { grid-template-columns: 1fr; gap: 14px; padding: 16px; }
            .summary-status { text-align: left; min-width: 0; }
            .toolbar { justify-content: stretch; padding: 12px 16px; }
            .toolbar .btn { flex: 1 1 100%; }
            .approval-workspace { gap: 12px; }
            .panel-heading { flex-direction: column; }
            .route-step { grid-template-columns: 32px minmax(0, 1fr); }
            .route-badge { grid-column: 2; justify-self: start; }
            .document-preview { margin-left: -12px; margin-right: -12px; padding: 16px 12px 26px; overflow-x: auto; }
            .preview-heading { align-items: flex-start; }
            .attachment-preview-header { align-items: flex-start; flex-direction: column; }
            .attachment-preview-frame { height: 520px; }
            .page-sheet { max-width: none; transform-origin: top left; }
        }
    
        /* Button hover animation */
        .main .btn,
        .main .tab-btn,
        .main .action-btn,
        .main .btn-action,
        .main .filter-btn,
        .main .button,
        .main .generate-closing-btn,
        .main .attachment-remove-btn,
        .main .page-add-btn,
        .main .page-delete-btn,
        .main .delete-current-page-btn,
        .main .form-actions a,
        .main .form-actions button,
        .main .filter-actions a,
        .main .filter-actions button,
        .main .document-command a,
        .main .document-command button,
        .main table a[class*="btn"],
        .main table button[class*="btn"],
        .main input[type="submit"],
        .main input[type="button"] {
            transition: transform 0.2s ease, filter 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease, border-color 0.2s ease !important;
            will-change: transform;
        }

        .main .btn:hover:not(:disabled),
        .main .tab-btn:hover:not(:disabled),
        .main .action-btn:hover:not(:disabled),
        .main .btn-action:hover:not(:disabled),
        .main .filter-btn:hover:not(:disabled),
        .main .button:hover:not(:disabled),
        .main .generate-closing-btn:hover:not(:disabled),
        .main .attachment-remove-btn:hover:not(:disabled),
        .main .page-add-btn:hover:not(:disabled),
        .main .page-delete-btn:hover:not(:disabled),
        .main .delete-current-page-btn:hover:not(:disabled),
        .main .form-actions a:hover,
        .main .form-actions button:hover:not(:disabled),
        .main .filter-actions a:hover,
        .main .filter-actions button:hover:not(:disabled),
        .main .document-command a:hover,
        .main .document-command button:hover:not(:disabled),
        .main table a[class*="btn"]:hover,
        .main table button[class*="btn"]:hover:not(:disabled),
        .main input[type="submit"]:hover:not(:disabled),
        .main input[type="button"]:hover:not(:disabled) {
            transform: translateY(-1px);
            filter: brightness(1.04);
            box-shadow: 0 14px 28px rgba(0, 119, 182, 0.18);
        }

        .main .btn:active:not(:disabled),
        .main .tab-btn:active:not(:disabled),
        .main .action-btn:active:not(:disabled),
        .main .btn-action:active:not(:disabled),
        .main .filter-btn:active:not(:disabled),
        .main .button:active:not(:disabled),
        .main .generate-closing-btn:active:not(:disabled),
        .main .attachment-remove-btn:active:not(:disabled),
        .main .page-add-btn:active:not(:disabled),
        .main .page-delete-btn:active:not(:disabled),
        .main .delete-current-page-btn:active:not(:disabled),
        .main .form-actions a:active,
        .main .form-actions button:active:not(:disabled),
        .main .filter-actions a:active,
        .main .filter-actions button:active:not(:disabled),
        .main .document-command a:active,
        .main .document-command button:active:not(:disabled),
        .main table a[class*="btn"]:active,
        .main table button[class*="btn"]:active:not(:disabled),
        .main input[type="submit"]:active:not(:disabled),
        .main input[type="button"]:active:not(:disabled) {
            transform: translateY(0);
            filter: brightness(0.98);
        }</style>
</head>
<body class="role-<?= htmlspecialchars($role) ?><?= $has_replacement_letter_file ? ' has-replacement-letter' : '' ?>">
    <aside class="sidebar" id="sidebar">
        <button class="sidebar-toggle" id="sidebarToggle" title="Tutup/Buka Menu">
            <i class="fas fa-chevron-left"></i>
        </button>
        <div class="sidebar-header">
            <img src="mainpp.png" alt="Logo MAINPP">
            <h3>MAINPP WORKSPACE</h3>
        </div>
        <ul class="sidebar-menu">
            <?php renderUnifiedSidebarMenu($conn, $role, 'draft_letter_print.php'); ?>
        </ul>
    </aside>

    <main class="main">
        <div class="top-bar">
            <h2><i class="fas fa-file-lines"></i> Semak Surat</h2>
            <?php renderTopBarUserMenu($conn, $role, 'draft_letter_print.php'); ?>
        </div>

        <?php
        renderBreadcrumb([
            ['label' => 'Dashboard', 'url' => 'dashboard.php'],
            ['label' => 'Modul Surat', 'url' => 'draft_letters.php'],
            ['label' => 'Semak Surat', 'url' => 'draft_letter_print.php?id=' . $draft_id, 'current' => true]
        ]);
        ?>

        <?php if ($status_message !== ''): ?>
        <div class="alert"><?= htmlspecialchars($status_message) ?></div>
        <?php endif; ?>

        <section class="document-command" aria-label="Ringkasan dan tindakan dokumen">
            <div class="document-summary">
                <div>
                    <div class="document-kicker"><?= htmlspecialchars($draft['doc_type'] ?? 'Dokumen') ?></div>
                    <h1 class="document-title"><?= htmlspecialchars($draft['subject'] ?: 'Draf tanpa tajuk') ?></h1>
                    <div class="document-reference">
                        <span>Rujukan: <strong><?= htmlspecialchars($ruj_kami_display) ?></strong></span>
                        <span>Fail: <strong><?= htmlspecialchars($draft['folder_name']) ?></strong></span>
                    </div>
                </div>
                <div class="summary-status">
                    <label><?= htmlspecialchars($document_status_label) ?></label>
                    <span class="support-status <?= htmlspecialchars($approval_status_key) ?>">
                        <i class="fas <?= htmlspecialchars($approval_status_icon) ?>"></i>
                        <?= htmlspecialchars($approval_status_labels[$approval_status_key] ?? ($status_labels[$draft['status']] ?? '-')) ?>
                    </span>
                </div>
            </div>
            <div class="toolbar">
                <?php if ($can_print_or_export_pdf): ?>
                <button type="button" class="btn btn-primary" onclick="window.print()"><i class="fas fa-print"></i> Cetak / Simpan PDF</button>
                <a href="export_draft_letter.php?id=<?= $draft_id ?>&format=pdf" class="btn btn-secondary"><i class="fas fa-file-pdf"></i> Export PDF</a>
                <?php endif; ?>
                <?php if ($can_replace_letter_file): ?>
                <form class="replace-letter-form" method="POST" action="process_draft_letter.php?action=replace_letter_file" enctype="multipart/form-data">
                    <input type="hidden" name="id" value="<?= $draft_id ?>">
                    <label class="btn btn-secondary" for="replace_letter_file_<?= $draft_id ?>">
                        <i class="fas fa-file-arrow-up"></i> Replace Surat
                    </label>
                    <input
                        type="file"
                        id="replace_letter_file_<?= $draft_id ?>"
                        name="replacement_file"
                        accept=".pdf,.doc,.docx,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                        onchange="if (this.files.length && confirm('Adakah anda pasti untuk replace fail surat ini? No. rujukan dan maklumat surat akan dikekalkan.')) { this.form.submit(); } else { this.value = ''; }"
                    >
                </form>
                <?php endif; ?>
                <?php if ($can_manage_this_draft): ?>
                <a href="draft_letters.php?id=<?= (int) $draft['folder_id'] ?>" class="btn btn-secondary"><i class="fas fa-folder-open"></i> Buka Fail</a>
                <?php endif; ?>
                <?php if (currentUserCan($conn, 'draft_letter', 'delete') && $can_manage_this_draft): ?>
                <a href="process_draft_letter.php?action=delete&id=<?= $draft_id ?>" class="btn btn-danger" onclick="return confirm('Padam surat ini? Surat akan masuk ke Data Dipadam dan tidak akan diterima atau dibuka oleh penerima lain.')"><i class="fas fa-trash-alt"></i> Padam Surat</a>
                <?php endif; ?>
            </div>
        </section>

        <div class="approval-workspace">
            <section class="flow-card">
                <?php
                $flow_steps = buildDraftFlowSteps($draft, $approval_recipients);
                $flow_current_holder = buildDraftFlowCurrentHolder($draft, $approval_recipients);
                $flow_status_labels = [
                    'belum_mula' => 'Belum Mula',
                    'menunggu' => 'Menunggu',
                    'menunggu_pengesahan' => 'Menunggu Pengesahan',
                    'menunggu_tandatangan' => 'Menunggu Tandatangan',
                    'perlu_pindaan_penyedia' => 'Perlu Pindaan oleh Penyedia',
                    'sedang_dipinda_ketua_bahagian' => 'Sedang Dipinda oleh Ketua Bahagian',
                    'disediakan' => 'Disediakan',
                    'disediakan_ditandatangani' => 'Disediakan dan Ditandatangani',
                    'disahkan' => 'Disahkan',
                    'disahkan_ditandatangani' => 'Disahkan dan Ditandatangani',
                    'disokong_ditandatangani' => 'Disokong dan Ditandatangani',
                    'diluluskan_ditandatangani' => 'Diluluskan dan Ditandatangani',
                    'ditandatangani' => 'Ditandatangani',
                    'diterima' => 'Diterima',
                    'lulus' => 'Selesai Ditandatangani',
                    'ditolak' => 'Ditolak',
                ];
                ?>
                <div class="flow-heading">
                    <div>
                        <h3><i class="fas fa-route"></i> Aliran Kelulusan</h3>
                        <p>Tarikh terima dan tandatangan setiap langkah surat.</p>
                    </div>
                    <span class="support-status <?= htmlspecialchars($approval_status_key) ?>">
                        <?= htmlspecialchars($approval_status_labels[$approval_status_key] ?? '-') ?>
                    </span>
                </div>
                <div class="flow-current">
                    <i class="fas fa-location-dot"></i>
                    <div>
                        (sekarang : <?= htmlspecialchars($flow_current_holder['name'] ?: '-') ?>)
                        <?php if (!empty($flow_current_holder['received_at'])): ?>
                        <span><?= htmlspecialchars($flow_current_holder['received_label'] ?? 'Diterima pada') ?>: <?= htmlspecialchars($flow_current_holder['received_at']) ?></span>
                        <?php endif; ?>
                        <?php if (!empty($flow_current_holder['signed_at'])): ?>
                        <span><?= htmlspecialchars($flow_current_holder['signed_label'] ?? 'Ditandatangani pada') ?>: <?= htmlspecialchars($flow_current_holder['signed_at']) ?></span>
                        <?php endif; ?>
                    </div>
                </div>
                <ol class="flow-list">
                    <?php foreach ($flow_steps as $flow_step): ?>
                    <?php $flow_status = $flow_step['status'] ?: 'belum_mula'; ?>
                    <li class="flow-step">
                        <span class="flow-dot <?= htmlspecialchars($flow_status) ?>"></span>
                        <div class="flow-main">
                            <div class="flow-label"><?= htmlspecialchars($flow_step['label']) ?></div>
                            <div class="flow-name"><?= htmlspecialchars($flow_step['name'] ?: '-') ?></div>
                            <div class="flow-times">
                                <?php if (!empty($flow_step['received_at'])): ?>
                                <span><?= htmlspecialchars($flow_step['received_label'] ?? 'Diterima pada') ?>: <?= htmlspecialchars($flow_step['received_at']) ?></span>
                                <?php endif; ?>
                                <?php if (!empty($flow_step['signed_at'])): ?>
                                <span><?= htmlspecialchars($flow_step['signed_label'] ?? 'Ditandatangani pada') ?>: <?= htmlspecialchars($flow_step['signed_at']) ?></span>
                                <?php endif; ?>
                            </div>
                        </div>
                        <span class="flow-badge <?= htmlspecialchars($flow_status) ?>">
                            <?= htmlspecialchars($flow_status_labels[$flow_status] ?? ucfirst(str_replace('_', ' ', $flow_status))) ?>
                        </span>
                    </li>
                    <?php endforeach; ?>
                </ol>
            </section>

            <section class="action-panel<?= ($is_current_approver || $can_resume_department_officer_revision) ? ' waiting' : '' ?>">
                <h3><i class="fas fa-list-check"></i> Tindakan Anda</h3>
            <?php if ($is_draft_creator && $approval_status_key === 'perlu_pindaan_penyedia'): ?>
            <div class="empty-action">
                <i class="fas fa-pen-to-square"></i>
                <span>Surat ini dipulangkan untuk pindaan. Sila kemaskini surat dan hantar semula kepada Ketua Bahagian.</span>
            </div>
            <?php $active_revision_note = trim((string) ($draft['support_note'] ?? '')); ?>
            <?php if ($active_revision_note !== ''): ?>
            <div class="revision-note-display">
                <strong>Catatan Pindaan:</strong>
                <span><?= nl2br(htmlspecialchars($active_revision_note)) ?></span>
            </div>
            <?php endif; ?>
            <div class="toolbar-actions">
                <a href="<?= htmlspecialchars($draft_edit_page) ?>?id=<?= $draft_id ?>" class="btn btn-primary"><i class="fas fa-pen-to-square"></i> Buat Pindaan</a>
            </div>
            <?php elseif ($can_resume_department_officer_revision): ?>
            <div class="empty-action">
                <i class="fas fa-pen-to-square"></i>
                <span>Surat ini sedang berada dalam pindaan anda. Sambung pindaan untuk mengemaskini kandungan surat sebelum tandatangan.</span>
            </div>
            <div class="toolbar-actions">
                <a href="<?= htmlspecialchars($draft_edit_page) ?>?id=<?= $draft_id ?>&revision=department_officer" class="btn btn-primary"><i class="fas fa-pen-to-square"></i> Sambung Pindaan</a>
            </div>
            <?php elseif ($is_current_approver && in_array($approval_status_key, ['menunggu_pegawai_bahagian', 'menunggu_pelulus'], true)): ?>
            <form method="POST" action="process_draft_letter.php?action=support" enctype="multipart/form-data">
                <input type="hidden" name="id" value="<?= $draft_id ?>">
                <input type="hidden" name="decision" id="support_decision_input" value="">
                <input type="hidden" name="auto_sign" id="support_auto_sign_input" value="0">
                <input type="hidden" name="revision_action" id="revision_action_input" value="">
                <?php if ($current_action_status === 'menunggu'): ?>
                <p><?= htmlspecialchars($current_action_instruction) ?></p>
                <textarea
                    id="support_note"
                    name="support_note"
                    aria-label="Ulasan kelulusan"
                    data-preview-user-id="<?= (int) ($is_memo_preparer_head_review_actor ? ($draft['memo_preparer_head_user_id'] ?? 0) : ($current_recipient['user_id'] ?? 0)) ?>"
                    placeholder="Masukkan ulasan untuk bahagian anda. Ulasan wajib jika surat ditolak."
                    class="<?= ($is_department_officer_actor || $is_memo_preparer_head_review_actor) ? 'support-note-hidden' : '' ?>"
                ></textarea>
                <div class="toolbar-actions">
                    <button type="button" class="btn btn-primary support-decision-btn" data-decision="disokong" data-label="<?= htmlspecialchars($current_action_positive_label) ?>"><i class="fas fa-check"></i> <?= htmlspecialchars($current_action_positive_label) ?></button>
                    <button type="button" class="btn btn-danger support-decision-btn" data-decision="ditolak" data-label="<?= htmlspecialchars($current_action_negative_label) ?>"><i class="fas fa-xmark"></i> <?= htmlspecialchars($current_action_negative_label) ?></button>
                </div>
                <div class="sign-confirm-modal" id="sign_confirm_modal" aria-hidden="true">
                    <div class="sign-confirm-dialog" role="dialog" aria-modal="true" aria-labelledby="sign_confirm_title">
                        <h4 id="sign_confirm_title"><i class="fas fa-signature"></i> Sahkan Tandatangan</h4>
                        <p id="sign_confirm_message">Adakah anda pasti untuk menandatangani tindakan ini?</p>
                        <div class="sign-confirm-actions">
                            <button type="button" class="btn btn-secondary" id="sign_cancel_btn"><i class="fas fa-xmark"></i> Batal</button>
                            <button type="button" class="btn btn-primary" id="sign_confirm_btn" data-signature-ready="<?= $current_user_signature_path !== '' ? '1' : '0' ?>"><i class="fas fa-signature"></i> Sign</button>
                        </div>
                    </div>
                </div>
                <?php if ($is_memo_preparer_head_review_actor): ?>
                <div class="sign-confirm-modal" id="memo_review_confirm_modal" aria-hidden="true">
                    <div class="sign-confirm-dialog" role="dialog" aria-modal="true" aria-labelledby="memo_review_confirm_title">
                        <h4 id="memo_review_confirm_title"><i class="fas fa-circle-check"></i> Sahkan Memo</h4>
                        <p>Adakah anda pasti untuk mengesahkan memo ini?</p>
                        <p>Selepas disahkan, memo akan dihantar kepada bahagian penandatangan untuk proses tandatangan.</p>
                        <div class="sign-confirm-actions">
                            <button type="button" class="btn btn-secondary" id="memo_review_cancel_btn"><i class="fas fa-xmark"></i> Batal</button>
                            <button type="button" class="btn btn-primary" id="memo_review_confirm_btn"><i class="fas fa-check"></i> Ya, Sahkan</button>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                <?php if ($is_department_officer_actor || $is_memo_preparer_head_review_actor): ?>
                <div class="sign-confirm-modal" id="revision_choice_modal" aria-hidden="true">
                    <div class="sign-confirm-dialog" role="dialog" aria-modal="true" aria-labelledby="revision_choice_title">
                        <h4 id="revision_choice_title"><i class="fas fa-pen-to-square"></i> Mohon Pindaan</h4>
                        <p>Pilih tindakan pindaan untuk surat ini.</p>
                        <label class="revision-choice-option">
                            <input type="radio" name="revision_choice_ui" value="return_to_preparer" checked>
                            <span>Hantar semula kepada Penyedia Surat</span>
                        </label>
                        <?php if ($can_self_edit_revision): ?>
                        <label class="revision-choice-option">
                            <input type="radio" name="revision_choice_ui" value="self_edit">
                            <span>Buat pindaan sendiri</span>
                        </label>
                        <?php endif; ?>
                        <div class="revision-note-block" id="revision_note_block">
                            <label class="revision-note-label" for="revision_note_modal">Catatan Pindaan:</label>
                            <textarea
                                class="revision-note-modal"
                                id="revision_note_modal"
                                aria-label="Catatan pindaan"
                                placeholder="Masukkan catatan pindaan untuk penyedia surat."
                            ></textarea>
                        </div>
                        <div class="sign-confirm-actions">
                            <button type="button" class="btn btn-secondary" id="revision_cancel_btn"><i class="fas fa-xmark"></i> Cancel</button>
                            <button type="button" class="btn btn-primary" id="revision_continue_btn"><i class="fas fa-arrow-right"></i> Teruskan</button>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                <?php elseif ($current_action_status === 'menunggu_tandatangan'): ?>
                <?php if ($current_action_decision === 'ditolak'): ?>
                <p><?= htmlspecialchars($current_action_negative_label) ?> dan ulasan telah direkodkan. Klik tandatangan untuk mengesahkan tindakan surat.</p>
                <?php else: ?>
                <p><?= htmlspecialchars($current_action_positive_label) ?> telah direkodkan. Klik tandatangan untuk melengkapkan tindakan dan meneruskan edaran.</p>
                <?php endif; ?>
                <?php if ($current_user_signature_path !== ''): ?>
                <div class="signature-ready">
                    <i class="fas fa-circle-check"></i>
                    Tandatangan anda telah tersedia dalam database sistem.
                </div>
                <div class="toolbar-actions">
                    <button type="submit" name="decision" value="tandatangan" class="btn btn-primary" onclick="return confirm('Adakah anda pasti untuk sign surat ini?')"><i class="fas fa-signature"></i> <?= $current_action_decision === 'ditolak' ? 'Tandatangan Penolakan' : 'Tandatangan Surat' ?></button>
                </div>
                <?php else: ?>
                <div class="signature-missing">
                    <i class="fas fa-triangle-exclamation"></i>
                    Tandatangan anda belum didaftarkan dalam database. Sila kemas kini tandatangan pengguna dahulu.
                </div>
                <?php endif; ?>
                <?php endif; ?>
            </form>
            <?php else: ?>
            <div class="empty-action">
                <i class="fas fa-circle-check"></i>
                <span>Tiada tindakan diperlukan daripada anda buat masa ini. Status terkini boleh dilihat pada aliran kelulusan.</span>
            </div>
            <?php endif; ?>
            </section>
        </div>

        <?php
            $approval_recipient_pages = ($is_surat_rasmi || $is_memo) ? [] : [array_values($approval_recipients)];
            $distribution_print_pages = [];
            $distribution_print_enabled = (int) ($draft['include_distribution_page'] ?? 0) === 1
                && trim(strip_tags((string) ($draft['distribution_page_content'] ?? ''))) !== '';
            if (($is_memo || $is_surat_rasmi) && $distribution_print_enabled) {
                $distribution_already_in_letter_pages = false;
                foreach ($letter_pages as $existing_page_body) {
                    if (isMemoDistributionPrintPage($existing_page_body, $draft['distribution_page_content'] ?? '')) {
                        $distribution_already_in_letter_pages = true;
                        break;
                    }
                }
                if (!$distribution_already_in_letter_pages) {
                    $distribution_print_pages[] = $draft['distribution_page_content'];
                }
            }
        ?>
        <section class="document-preview">
        <div class="preview-heading">
            <h3><i class="fas fa-file-lines"></i> <?= htmlspecialchars($document_preview_label) ?></h3>
            <span id="document_page_count"><?= $has_replacement_letter_file ? 'Fail surat diganti' : (count($letter_pages) + count($distribution_print_pages) + count($approval_recipient_pages) . ' halaman') ?></span>
        </div>
        <?php if (!$has_replacement_letter_file): ?>
        <?php foreach ($letter_pages as $page_index => $page_body): ?>
                <?php
        $page_body = injectPreparerSignatureIntoGeneratedClosing($page_body, $draft);
        if ($is_surat_rasmi) {
            $page_body = replaceSuratRasmiPrintReferenceLine($page_body, $ruj_kami_display);
            $page_body = preg_replace('/^\s*<p[^>]*>\s*(?:<br\s*\/?>)?\s*<\/p>\s*(?=<p[^>]*data-surat-rasmi-generated-line="ref")/i', '', $page_body);
        }
        ?>
        <div class="page-sheet <?= $is_surat_rasmi ? 'surat-rasmi-sheet' : '' ?> <?= $page_index > 0 ? 'is-extra-page' : '' ?>">
            <div class="print-custom-header"><?= renderDraftLetterBody($draft['page_header_text'] ?? '') ?></div>
            <div class="page-sheet-inner">
                <?php if ($page_index === 0 && !$is_surat_rasmi): ?>
                <div class="memo-logo" style="text-align:center;margin-bottom:2px;"><img src="mainpp.png" alt="Logo MAINPP" style="width:130px;height:auto;object-fit:contain;"></div>
                <div class="memo-title" style="text-align:center;letter-spacing:0;font-weight:700;font-size:29px!important;line-height:1.5;margin-bottom:12px;padding-left:0;"><?= htmlspecialchars(strtoupper($draft['doc_type'] ?? 'MEMO')) ?></div>
                <table class="memo-ref-table" style="width:100%;table-layout:fixed;border-collapse:collapse;font-size:13px;margin-bottom:16px;">
                    <tr>
                        <td class="memo-ref-left" rowspan="2">
                            MAJLIS AGAMA ISLAM NEGERI PULAU PINANG,<br>
                            TINGKAT 7, 8 &amp; 9, MENARA JKP,<br>
                            128, JALAN MACALISTER,<br>
                            10400 PULAU PINANG.
                        </td>
                        <td class="memo-ref-right"><div class="memo-ref-line"><span class="memo-ref-label">Ruj Kami</span><span class="memo-ref-colon">:</span><span class="memo-ref-value"><?= htmlspecialchars($ruj_kami_display) ?></span></div></td>
                    </tr>
                    <tr>
                        <td class="memo-ref-right"><div class="memo-ref-line"><span class="memo-ref-label">Tarikh</span><span class="memo-ref-colon">:</span><span class="memo-ref-value"><?= htmlspecialchars(formatMalayMemoDate($draft['letter_date'])) ?></span></div></td>
                    </tr>
                </table>

                <table class="memo-label-grid">
                    <tr>
                        <td class="memo-label">DARIPADA</td>
                        <td class="memo-colon">:</td>
                        <td class="memo-value">
                            <?= htmlspecialchars(getDisplayPositionForDepartment(($draft['signatory_department'] ?? '') ?: ($draft['department'] ?? ''), $draft['signatory_position'] ?? '') ?: ($draft['signatory_department'] ?: $draft['department'])) ?><br>
                            Majlis Agama Islam Negeri Pulau Pinang
                        </td>
                    </tr>
                    <?php if (strcasecmp(trim((string) ($draft['doc_type'] ?? '')), 'Memo') !== 0 && !empty($draft['attention_to'])): ?>
                    <tr>
                        <td class="memo-label">MELALUI</td>
                        <td class="memo-colon">:</td>
                        <td class="memo-value">
                            <?= renderMemoPrintDisplayValue($draft['attention_to']) ?>
                        </td>
                    </tr>
                    <?php endif; ?>
                    <tr>
                        <td class="memo-label">KEPADA</td>
                        <td class="memo-colon">:</td>
                        <td class="memo-value">
                            <?= renderMemoPrintDisplayValue($draft['recipient_organization']) ?>
                        </td>
                    </tr>
                </table>
                <?php endif; ?>

                <?php if (($is_memo || $is_surat_rasmi) && $distribution_print_enabled && isMemoDistributionPrintPage($page_body, $draft['distribution_page_content'] ?? '')): ?>
                <div style="text-align:center;font-weight:bold;font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1.5;margin:0;padding:<?= $is_surat_rasmi ? '6px 0 2px' : '10px 0' ?>;">SENARAI EDARAN</div>
                <?php endif; ?>

                <div class="letter-body letter-main-body">
                    <?= renderDraftLetterBody($page_body) ?>
                </div>
            </div>
            <div class="print-custom-footer"><?= renderDraftLetterBody($draft['page_footer_text'] ?? '') ?></div>
            <div class="print-page-number <?= htmlspecialchars($draft['page_number_position'] ?? 'none') ?>"><?= $page_index + 1 ?></div>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>

        <?php if (!$has_replacement_letter_file): ?>
        <?php foreach ($distribution_print_pages as $distribution_page_index => $distribution_page_body): ?>
        <div class="page-sheet <?= $is_surat_rasmi ? 'surat-rasmi-sheet' : '' ?> is-extra-page">
            <div class="print-custom-header"><?= renderDraftLetterBody($draft['page_header_text'] ?? '') ?></div>
            <div class="page-sheet-inner">
                <div style="text-align:center;font-weight:bold;font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1.5;margin:0;padding:<?= $is_surat_rasmi ? '6px 0 2px' : '10px 0' ?>;">SENARAI EDARAN</div>
                <div class="letter-body letter-main-body">
                    <?= renderDraftLetterBody($distribution_page_body) ?>
                </div>
            </div>
            <div class="print-custom-footer"><?= renderDraftLetterBody($draft['page_footer_text'] ?? '') ?></div>
            <div class="print-page-number <?= htmlspecialchars($draft['page_number_position'] ?? 'none') ?>"><?= count($letter_pages) + $distribution_page_index + 1 ?></div>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>

        <?php if (!$has_replacement_letter_file): ?>
        <?php foreach ($approval_recipient_pages as $approval_page_index => $approval_page_recipients): ?>
        <div class="page-sheet approval-sheet">
            <div class="print-custom-header"><?= renderDraftLetterBody($draft['page_header_text'] ?? '') ?></div>
            <div class="page-sheet-inner">
                <?php
                $approval_route_bodies = decodeDraftApprovalRouteBodies($draft['approval_route_bodies'] ?? '');
                $max_route_order = 0;
                foreach ($approval_recipients as $approval_route) {
                    $max_route_order = max($max_route_order, (int) ($approval_route['route_order'] ?? 0));
                }
                foreach ($approval_page_recipients as $recipient) {
                    $recipient_key = 'user:' . (int) ($recipient['user_id'] ?? 0);
                    $position_key = 'position:' . trim((string) ($recipient['position_label'] ?? ''));
                    $recipient_body = $approval_route_bodies[$recipient_key]
                        ?? $approval_route_bodies[$position_key]
                        ?? '';
                    renderMemoApprovalDecisionSection(
                        $recipient['position_label'] ?? 'Pelulus',
                        $recipient['fullname'] ?? '',
                        $recipient['position_label'] ?? ($recipient['position'] ?? 'Pelulus'),
                        $recipient['signature_path'] ?? '',
                        $recipient['status'] ?? '',
                        $recipient['approved_at'] ?? '',
                        $recipient['responded_at'] ?? '',
                        $recipient_body,
                        $recipient['note'] ?? '',
                        $recipient['user_id'] ?? 0,
                        $recipient['decision'] ?? '',
                        (int) ($recipient['route_order'] ?? 0) >= $max_route_order
                    );
                }
                ?>
            </div>
            <div class="print-custom-footer"><?= renderDraftLetterBody($draft['page_footer_text'] ?? '') ?></div>
            <div class="print-page-number <?= htmlspecialchars($draft['page_number_position'] ?? 'none') ?>"><?= count($letter_pages) + count($distribution_print_pages) + $approval_page_index + 1 ?></div>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>

        <?php if (!empty($preview_attachments)): ?>
        <div class="attachment-preview-area <?= $has_replacement_letter_file ? 'replacement-document-area' : '' ?>" aria-label="<?= $has_replacement_letter_file ? 'Paparan fail surat diganti' : 'Pratonton lampiran sokongan' ?>">
            <?php foreach ($preview_attachments as $attachment): ?>
                <?php
                $attachment_id = (int) ($attachment['id'] ?? 0);
                $attachment_path = trim((string) ($attachment['file_path'] ?? ''));
                $attachment_full_path = $attachment_path !== '' && preg_match('/^[A-Za-z]:[\\\\\\/]/', $attachment_path)
                    ? $attachment_path
                    : __DIR__ . '/' . $attachment_path;
                if ($attachment_id <= 0 || $attachment_path === '' || !is_file($attachment_full_path)) {
                    continue;
                }
                $attachment_name = getDraftAttachmentDisplayName($attachment);
                $preview_type = getDraftAttachmentPreviewType($attachment);
                $attachment_url = 'download.php?attachment_id=' . $attachment_id . '&draft_id=' . $draft_id;
                ?>
                <section class="attachment-preview-card">
                    <div class="attachment-preview-header">
                        <div class="attachment-preview-title">
                            <i class="fas <?= $has_replacement_letter_file ? 'fa-file-arrow-up' : 'fa-paperclip' ?>"></i>
                            <span><?= htmlspecialchars($attachment_name) ?></span>
                        </div>
                        <a href="<?= htmlspecialchars($attachment_url) ?>" target="_blank"><i class="fas fa-up-right-from-square"></i> Buka fail</a>
                    </div>
                    <?php if ($preview_type === 'pdf'): ?>
                    <iframe class="attachment-preview-frame" src="<?= htmlspecialchars($attachment_url) ?>#toolbar=0&navpanes=0" title="<?= htmlspecialchars($attachment_name) ?>"></iframe>
                    <?php elseif ($preview_type === 'image'): ?>
                    <img class="attachment-preview-image" src="<?= htmlspecialchars($attachment_url) ?>" alt="<?= htmlspecialchars($attachment_name) ?>">
                    <?php else: ?>
                    <div class="attachment-preview-unavailable">
                        <i class="fas fa-file-lines"></i>
                        <div><?= $has_replacement_letter_file
                            ? 'Fail surat ini telah menggantikan surat yang dijana dalam sistem. Format Word tidak boleh dipratonton terus oleh pelayar, tetapi boleh dibuka dari sini.'
                            : 'Fail ini telah dilampirkan pada surat. Format Word/Excel tidak boleh dipratonton terus oleh pelayar, tetapi penyedia dan penerima surat boleh membukanya dari sini.' ?></div>
                    </div>
                    <?php endif; ?>
                </section>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
        </section>

        <div class="page-footer">
            Hakcipta Terpelihara &copy; <?= date('Y') ?> Majlis Agama Islam Negeri Pulau Pinang.
        </div>
    </main>

    <script>
                const sidebar = document.getElementById('sidebar');
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', () => sidebar.classList.toggle('collapsed'));
        }
        if (window.innerWidth < 992) sidebar.classList.add('collapsed');

        document.querySelectorAll('.sidebar-menu .dropdown-toggle, .dropdown-toggle').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                const dropdown = this.parentElement;
                const isActive = dropdown.classList.contains('active');
                document.querySelectorAll('.sidebar-menu .dropdown, .dropdown').forEach(item => {
                    if (item !== dropdown) item.classList.remove('active');
                });
                dropdown.classList.toggle('active', !isActive);
            });
        });
        function confirmLogout() {
            return confirm("Adakah anda pasti ingin log keluar?");
        }

        function splitOversizedApprovalBlock(sheet, block) {
            const inner = sheet.querySelector('.page-sheet-inner');
            const sourceBody = block ? block.querySelector('.approval-recipient-body') : null;
            if (!inner || !block || !sourceBody || inner.scrollHeight <= inner.clientHeight + 2) return;

            const continuation = sheet.cloneNode(true);
            const continuationInner = continuation.querySelector('.page-sheet-inner');
            continuationInner.querySelectorAll('.approval-decision-section').forEach(section => section.remove());
            const continuationBlock = block.cloneNode(true);
            const continuationBody = continuationBlock.querySelector('.approval-recipient-body');
            continuationBody.innerHTML = '';
            continuationInner.appendChild(continuationBlock);

            Array.from(block.children).forEach(child => {
                if (child !== sourceBody) child.remove();
            });

            while (inner.scrollHeight > inner.clientHeight + 2 && sourceBody.lastChild) {
                continuationBody.insertBefore(sourceBody.lastChild, continuationBody.firstChild);
            }

            sheet.insertAdjacentElement('afterend', continuation);
            if (continuationInner.scrollHeight > continuationInner.clientHeight + 2 && continuationBody.childNodes.length > 1) {
                splitOversizedApprovalBlock(continuation, continuationBlock);
            }
        }

        function splitOverflowingApprovalSheet(sheet) {
            const inner = sheet.querySelector('.page-sheet-inner');
            if (!inner || inner.scrollHeight <= inner.clientHeight + 2) return;

            const sections = Array.from(inner.querySelectorAll(':scope > .approval-decision-section'));
            if (sections.length > 1) {
                const continuation = sheet.cloneNode(true);
                const continuationInner = continuation.querySelector('.page-sheet-inner');
                continuationInner.querySelectorAll('.approval-decision-section').forEach(section => section.remove());

                while (inner.scrollHeight > inner.clientHeight + 2 && inner.querySelectorAll(':scope > .approval-decision-section').length > 1) {
                    const lastSection = inner.querySelector(':scope > .approval-decision-section:last-child');
                    continuationInner.insertBefore(lastSection, continuationInner.firstChild);
                }

                sheet.insertAdjacentElement('afterend', continuation);
                splitOverflowingApprovalSheet(sheet);
                splitOverflowingApprovalSheet(continuation);
                return;
            }

            const onlyBlock = inner.querySelector(':scope > .approval-decision-section');
            if (onlyBlock) {
                splitOversizedApprovalBlock(sheet, onlyBlock);
            }
        }

        document.querySelectorAll('.approval-sheet').forEach(splitOverflowingApprovalSheet);
        function renumberPrintPages() {
            const sheets = document.querySelectorAll('.page-sheet');
            sheets.forEach((sheet, index) => {
                const number = sheet.querySelector('.print-page-number');
                if (number) number.textContent = String(index + 1);
            });
            const pageCount = document.getElementById('document_page_count');
            if (pageCount) pageCount.textContent = String(sheets.length) + ' halaman';
        }
        renumberPrintPages();

        const supportNoteInput = document.getElementById('support_note');
        if (supportNoteInput) {
            const previewUserId = supportNoteInput.dataset.previewUserId;
            const approvalSection = Array.from(document.querySelectorAll(
                `.approval-decision-section[data-approval-user-id="${previewUserId}"]`
            )).find(section => section.querySelector('.approval-recorded-note'));
            const previewNote = approvalSection?.querySelector('.approval-recorded-note');

            const syncApprovalNotePreview = () => {
                if (!previewNote) return;
                const note = supportNoteInput.value.trim();
                previewNote.textContent = note;
            };

            supportNoteInput.addEventListener('input', syncApprovalNotePreview);
            syncApprovalNotePreview();
        }

        const supportForm = supportNoteInput ? supportNoteInput.closest('form') : null;
        const supportDecisionInput = document.getElementById('support_decision_input');
        const supportAutoSignInput = document.getElementById('support_auto_sign_input');
        const revisionActionInput = document.getElementById('revision_action_input');
        const signConfirmModal = document.getElementById('sign_confirm_modal');
        const signConfirmMessage = document.getElementById('sign_confirm_message');
        const signConfirmBtn = document.getElementById('sign_confirm_btn');
        const signCancelBtn = document.getElementById('sign_cancel_btn');
        const memoReviewConfirmModal = document.getElementById('memo_review_confirm_modal');
        const memoReviewCancelBtn = document.getElementById('memo_review_cancel_btn');
        const memoReviewConfirmBtn = document.getElementById('memo_review_confirm_btn');
        const revisionChoiceModal = document.getElementById('revision_choice_modal');
        const revisionCancelBtn = document.getElementById('revision_cancel_btn');
        const revisionContinueBtn = document.getElementById('revision_continue_btn');
        const revisionNoteBlock = document.getElementById('revision_note_block');
        const revisionNoteModal = document.getElementById('revision_note_modal');
        const isDepartmentOfficerActor = <?= $is_department_officer_actor ? 'true' : 'false' ?>;
        const isMemoPreparerHeadReviewActor = <?= $is_memo_preparer_head_review_actor ? 'true' : 'false' ?>;
        const departmentOfficerAlreadySignedRevision = <?= $department_officer_already_signed_revision ? 'true' : 'false' ?>;
        const isSuratRasmi = <?= $is_surat_rasmi ? 'true' : 'false' ?>;
        const suratRasmiHasFinalRecipient = <?= ($is_surat_rasmi && !empty($approval_recipients)) ? 'true' : 'false' ?>;
        let pendingSupportDecision = '';
        const departmentOfficerSignatureAlreadyInDocument = () => {
            if (!isDepartmentOfficerActor) return false;
            return !!document.querySelector('[data-generated-signature="1"] img, [data-generated-closing="1"] img[src*="uploads/signatures/"]');
        };

        const closeSignConfirmModal = () => {
            pendingSupportDecision = '';
            if (supportDecisionInput) supportDecisionInput.value = '';
            if (supportAutoSignInput) supportAutoSignInput.value = '0';
            if (revisionActionInput) revisionActionInput.value = '';
            signConfirmModal?.classList.remove('active');
            signConfirmModal?.setAttribute('aria-hidden', 'true');
        };

        const closeMemoReviewConfirmModal = () => {
            pendingSupportDecision = '';
            if (supportDecisionInput) supportDecisionInput.value = '';
            if (supportAutoSignInput) supportAutoSignInput.value = '0';
            if (revisionActionInput) revisionActionInput.value = '';
            memoReviewConfirmModal?.classList.remove('active');
            memoReviewConfirmModal?.setAttribute('aria-hidden', 'true');
        };

        const closeRevisionChoiceModal = () => {
            if (supportDecisionInput) supportDecisionInput.value = '';
            if (supportAutoSignInput) supportAutoSignInput.value = '0';
            if (revisionActionInput) revisionActionInput.value = '';
            revisionNoteBlock?.classList.remove('active');
            if (revisionNoteModal) revisionNoteModal.value = '';
            if (revisionContinueBtn) {
                revisionContinueBtn.innerHTML = '<i class="fas fa-arrow-right"></i> Teruskan';
            }
            revisionChoiceModal?.classList.remove('active');
            revisionChoiceModal?.setAttribute('aria-hidden', 'true');
        };

        const resetRevisionChoiceModal = () => {
            revisionNoteBlock?.classList.remove('active');
            if (revisionNoteModal) revisionNoteModal.value = '';
            if (revisionContinueBtn) {
                revisionContinueBtn.innerHTML = '<i class="fas fa-arrow-right"></i> Teruskan';
            }
        };

        document.querySelectorAll('.support-decision-btn').forEach(button => {
            button.addEventListener('click', () => {
                const decision = button.dataset.decision || '';
                const label = button.dataset.label || 'tindakan';
                if (decision === 'ditolak' && !(isDepartmentOfficerActor || isMemoPreparerHeadReviewActor) && supportNoteInput && supportNoteInput.value.trim() === '') {
                    alert('Sila isi ulasan sebelum meneruskan tindakan ini.');
                    supportNoteInput.focus();
                    return;
                }
                if ((isDepartmentOfficerActor || isMemoPreparerHeadReviewActor) && decision === 'ditolak') {
                    if (supportDecisionInput) supportDecisionInput.value = 'ditolak';
                    if (supportAutoSignInput) supportAutoSignInput.value = '0';
                    resetRevisionChoiceModal();
                    revisionChoiceModal?.classList.add('active');
                    revisionChoiceModal?.setAttribute('aria-hidden', 'false');
                    return;
                }
                if (isMemoPreparerHeadReviewActor && decision === 'disokong') {
                    pendingSupportDecision = decision;
                    if (supportDecisionInput) supportDecisionInput.value = decision;
                    if (supportAutoSignInput) supportAutoSignInput.value = '0';
                    memoReviewConfirmModal?.classList.add('active');
                    memoReviewConfirmModal?.setAttribute('aria-hidden', 'false');
                    return;
                }
                if (isDepartmentOfficerActor && decision === 'disokong' && (departmentOfficerAlreadySignedRevision || departmentOfficerSignatureAlreadyInDocument())) {
                    if (supportDecisionInput) supportDecisionInput.value = decision;
                    if (supportAutoSignInput) supportAutoSignInput.value = '1';
                    supportForm?.submit();
                    return;
                }
                if (signConfirmBtn?.dataset.signatureReady !== '1') {
                    alert('Tandatangan anda belum didaftarkan dalam database. Sila kemas kini tandatangan pengguna dahulu.');
                    return;
                }
                pendingSupportDecision = decision;
                if (supportDecisionInput) supportDecisionInput.value = decision;
                if (supportAutoSignInput) supportAutoSignInput.value = '1';
                if (signConfirmMessage) {
                    signConfirmMessage.textContent = `Anda memilih "${label}". Klik Sign untuk menandatangani dan menghantar tindakan ini, atau Batal untuk kembali mengedit ulasan.`;
                }
                signConfirmModal?.classList.add('active');
                signConfirmModal?.setAttribute('aria-hidden', 'false');
            });
        });

        signCancelBtn?.addEventListener('click', closeSignConfirmModal);
        signConfirmModal?.addEventListener('click', event => {
            if (event.target === signConfirmModal) closeSignConfirmModal();
        });
        memoReviewCancelBtn?.addEventListener('click', closeMemoReviewConfirmModal);
        memoReviewConfirmModal?.addEventListener('click', event => {
            if (event.target === memoReviewConfirmModal) closeMemoReviewConfirmModal();
        });
        memoReviewConfirmBtn?.addEventListener('click', () => {
            if (!pendingSupportDecision || !supportForm || !supportDecisionInput || !supportAutoSignInput) return;
            supportDecisionInput.value = pendingSupportDecision;
            supportAutoSignInput.value = '0';
            supportForm.submit();
        });
        revisionCancelBtn?.addEventListener('click', closeRevisionChoiceModal);
        revisionChoiceModal?.addEventListener('click', event => {
            if (event.target === revisionChoiceModal) closeRevisionChoiceModal();
        });
        document.querySelectorAll('input[name="revision_choice_ui"]').forEach(input => {
            input.addEventListener('change', () => {
                revisionNoteBlock?.classList.remove('active');
                if (revisionContinueBtn) {
                    revisionContinueBtn.innerHTML = '<i class="fas fa-arrow-right"></i> Teruskan';
                }
            });
        });
        revisionContinueBtn?.addEventListener('click', () => {
            const selected = document.querySelector('input[name="revision_choice_ui"]:checked')?.value || 'return_to_preparer';
            if (!supportForm || !supportDecisionInput || !supportAutoSignInput || !revisionActionInput) return;
            if (selected === 'return_to_preparer' && !revisionNoteBlock?.classList.contains('active')) {
                revisionNoteBlock?.classList.add('active');
                if (revisionContinueBtn) {
                    revisionContinueBtn.innerHTML = '<i class="fas fa-paper-plane"></i> Hantar Pindaan';
                }
                revisionNoteModal?.focus();
                return;
            }
            if (selected === 'return_to_preparer') {
                const revisionNote = revisionNoteModal?.value.trim() || '';
                if (revisionNote === '') {
                    alert('Sila masukkan catatan pindaan.');
                    revisionNoteModal?.focus();
                    return;
                }
                if (supportNoteInput) {
                    supportNoteInput.value = revisionNote;
                    supportNoteInput.dispatchEvent(new Event('input', { bubbles: true }));
                }
            }
            supportDecisionInput.value = 'ditolak';
            supportAutoSignInput.value = '0';
            revisionActionInput.value = selected;
            supportForm.submit();
        });
        signConfirmBtn?.addEventListener('click', () => {
            if (!pendingSupportDecision || !supportForm || !supportDecisionInput || !supportAutoSignInput) return;
            supportDecisionInput.value = pendingSupportDecision;
            supportAutoSignInput.value = '1';
            supportForm.submit();
        });
    </script>
    <?php renderSessionTimeoutScript(); ?>
</body>
</html>
