<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Accept');

ob_start();

function respond(int $status_code, array $payload): void
{
    while (ob_get_level() > 0) {
        ob_end_clean();
    }

    http_response_code($status_code);
    echo json_encode($payload);
    exit;
}

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
    respond(204, []);
}

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    respond(405, [
        'success' => false,
        'message' => 'Method tidak dibenarkan.',
    ]);
}

require_once __DIR__ . '/../db.php';

$raw = file_get_contents('php://input');
$payload = json_decode($raw ?: '', true);
if (!is_array($payload)) {
    $payload = $_POST;
}

$user_id = (int) ($payload['user_id'] ?? 0);
$draft_id = (int) ($payload['draft_id'] ?? 0);

if ($user_id <= 0 || $draft_id <= 0) {
    respond(422, [
        'success' => false,
        'message' => 'Maklumat user atau surat tidak sah.',
    ]);
}

$user_stmt = mysqli_prepare($conn, 'SELECT id FROM users WHERE id = ? AND status = "approved" LIMIT 1');
if (!$user_stmt) {
    respond(500, [
        'success' => false,
        'message' => 'Ralat sistem semasa membaca pengguna.',
    ]);
}

mysqli_stmt_bind_param($user_stmt, 'i', $user_id);
mysqli_stmt_execute($user_stmt);
$user_result = mysqli_stmt_get_result($user_stmt);
if (!$user_result || !mysqli_fetch_assoc($user_result)) {
    respond(403, [
        'success' => false,
        'message' => 'Akaun tidak dibenarkan.',
    ]);
}

function formatDateLabel(?string $value, bool $include_time = false): string
{
    $value = trim((string) $value);
    if ($value === '' || $value === '0000-00-00' || $value === '0000-00-00 00:00:00') {
        return '';
    }

    $timestamp = strtotime($value);
    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',
    ];

    $day = date('j', $timestamp);
    $month_name = $months[(int) date('n', $timestamp)];
    $year = date('Y', $timestamp);

    if ($include_time) {
        return $day . ' ' . $month_name . ' ' . $year . ', ' . date('g:i A', $timestamp);
    }

    return $day . ' ' . $month_name . ' ' . $year;
}

function fileSizeLabel(string $path): string
{
    if ($path === '') {
        return '';
    }

    $full_path = preg_match('/^[A-Za-z]:[\\\\\\/]/', $path) ? $path : __DIR__ . '/../' . $path;
    if (!is_file($full_path)) {
        return '';
    }

    $bytes = filesize($full_path);
    if ($bytes === false || $bytes <= 0) {
        return '';
    }

    if ($bytes >= 1048576) {
        return rtrim(rtrim(number_format($bytes / 1048576, 1), '0'), '.') . ' MB';
    }

    return max(1, (int) ceil($bytes / 1024)) . ' KB';
}

function statusLabelFromValue(string $status): string
{
    $status_clean = strtolower(trim($status));
    if (in_array($status_clean, ['perlu_pindaan_penyedia', 'pindaan', 'revision'], true)) {
        return 'Pindaan';
    }
    return match ($status_clean) {
        'disokong', 'lulus' => 'Diluluskan',
        'ditolak' => 'Ditolak',
        'menunggu', 'menunggu_tandatangan',
        'menunggu_pegawai_bahagian', 'menunggu_pelulus',
        'menunggu_pelulus_akhir' => 'Menunggu',
        default => 'Surat',
    };
}

function plainTextFromLetterPages(?string $letter_pages, ?string $letter_body): string
{
    return implode("\n\n", plainTextPageList($letter_pages, $letter_body));
}

function plainTextPageList(?string $letter_pages, ?string $letter_body): array
{
    $pages = decodeDraftLetterPages($letter_pages ?? '', $letter_body ?? '');
    $page_texts = [];
    foreach ($pages as $page) {
        $html = (string) $page;
        $html = preg_replace('/<div\b[^>]*class\s*=\s*(["\'])[^"\']*\bgenerated-closing-lock\b[^"\']*\1[^>]*>.*?<\/div>/is', '', $html);
        $html = preg_replace('/<div\b[^>]*data-generated-closing\s*=\s*(["\'])1\1[^>]*>.*?<\/div>/is', '', $html);
        $page_texts[] = plainTextFromHtml($html);
    }

    return !empty($page_texts) ? $page_texts : [''];
}

function plainTextFromHtml(?string $html): string
{
    $html = (string) $html;
    $html = preg_replace('/<\s*br\s*\/?\s*>/i', "\n", $html);
    $html = preg_replace('/<\s*\/\s*(p|div|li|tr|h1|h2|h3|h4|h5|h6)\s*>/i', "\n", (string) $html);
    $text = html_entity_decode(strip_tags((string) $html), ENT_QUOTES | ENT_HTML5, 'UTF-8');
    $text = preg_replace('/[ \t]+/', ' ', (string) $text);
    $text = preg_replace("/\n{3,}/", "\n\n", (string) $text);
    return trim((string) $text);
}

function fetchApprovalPages(mysqli $conn, int $draft_id, ?string $route_bodies, ?string $approval_page_body, ?array $draft = null): array
{
    if ($draft) {
        $doc_type = strtolower(trim((string) ($draft['doc_type'] ?? '')));
        if ($doc_type === 'memo' || $doc_type === 'surat rasmi') {
            return [];
        }
    }

    $route_body_map = decodeDraftApprovalRouteBodies($route_bodies ?? '');
    $stmt = mysqli_prepare($conn, "
        SELECT
            lar.user_id,
            lar.position_label,
            lar.source_type,
            lar.status,
            lar.note,
            lar.signature_path,
            lar.responded_at,
            lar.approved_at,
            lar.route_order,
            u.fullname,
            u.position
        FROM letter_approval_recipients lar
        LEFT JOIN users u ON u.id = lar.user_id
        WHERE lar.draft_id = ?
        ORDER BY lar.route_order ASC, lar.id ASC
    ");

    if (!$stmt) {
        return [];
    }

    mysqli_stmt_bind_param($stmt, 'i', $draft_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $pages = [];
    $source_labels = [
        'kepada' => 'Kelulusan Kepada',
        'melalui' => 'Kelulusan Melalui',
        'tambahan' => 'Kelulusan',
    ];

    while ($row = $result ? mysqli_fetch_assoc($result) : null) {
        $user_key = 'user:' . (int) ($row['user_id'] ?? 0);
        $position_key = 'position:' . trim((string) ($row['position_label'] ?? ''));
        $body = $route_body_map[$user_key] ?? $route_body_map[$position_key] ?? '';

        $pages[] = [
            'label' => $source_labels[$row['source_type'] ?? ''] ?? 'Kelulusan',
            'name' => (string) (($row['fullname'] ?? '') ?: ($row['position_label'] ?? '')),
            'position' => (string) (($row['position_label'] ?? '') ?: ($row['position'] ?? '')),
            'status' => statusLabelFromValue((string) ($row['status'] ?? '')),
            'rawStatus' => (string) ($row['status'] ?? ''),
            'bodyText' => plainTextFromHtml($body),
            'note' => plainTextFromHtml($row['note'] ?? ''),
            'signatureUrl' => (string) ($row['signature_path'] ?? ''),
            'dateLabel' => formatDateLabel(($row['responded_at'] ?? '') ?: ($row['approved_at'] ?? ''), true),
        ];
    }

    if (empty($pages) && $draft && (!empty($draft['department_officer_note']) || !empty($draft['department_officer_status']))) {
        $pages[] = [
            'label' => 'Ulasan Pegawai Bahagian',
            'name' => (string) (($draft['department_officer_name'] ?? '') ?: ($draft['signatory_name'] ?? '')),
            'position' => (string) (($draft['department_officer_position'] ?? '') ?: ($draft['signatory_position'] ?? '')),
            'status' => statusLabelFromValue((string) ($draft['department_officer_status'] ?? '')),
            'rawStatus' => (string) ($draft['department_officer_status'] ?? ''),
            'bodyText' => '',
            'note' => plainTextFromHtml($draft['department_officer_note'] ?? ''),
            'signatureUrl' => (string) ($draft['department_officer_signature_path'] ?? ''),
            'dateLabel' => formatDateLabel($draft['department_officer_responded_at'] ?? null, true),
        ];
    }

    $fallback_body = plainTextFromHtml($approval_page_body ?? '');
    if (empty($pages) && $fallback_body !== '') {
        $pages[] = [
            'label' => 'Halaman Kelulusan',
            'name' => '',
            'position' => '',
            'status' => 'Surat',
            'rawStatus' => '',
            'bodyText' => $fallback_body,
            'note' => '',
            'dateLabel' => '',
        ];
    }

    $total_pages = count($pages);
    for ($i = 0; $i < $total_pages; $i++) {
        $pages[$i]['isFinalApprover'] = ($i === $total_pages - 1);
    }

    return $pages;
}

function fetchDistributionPages(array $draft): array
{
    $doc_type = strtolower(trim((string) ($draft['doc_type'] ?? '')));
    $include_dist = (int) ($draft['include_distribution_page'] ?? 0);
    $content = trim((string) ($draft['distribution_page_content'] ?? ''));

    if (($doc_type === 'memo' || $doc_type === 'surat rasmi') && ($include_dist === 1 || $content !== '')) {
        $plain_text = plainTextFromHtml($content);
        if ($plain_text !== '') {
            return [$plain_text];
        }
    }

    return [];
}

function getSignatorySignatureUrl(array $detail): string
{
    $created_by = (int) ($detail['created_by'] ?? 0);
    $department_officer_user_id = (int) ($detail['department_officer_user_id'] ?? 0);
    $department_officer_status = trim((string) ($detail['department_officer_status'] ?? ''));
    $signatory_signature_path = trim((string) ($detail['signatory_signature_path'] ?? ''));

    if ($department_officer_user_id > 0 && $department_officer_user_id !== $created_by) {
        if ($department_officer_status === 'lulus') {
            return $signatory_signature_path ?: trim((string) ($detail['department_officer_signature_path'] ?? ''));
        }
        return '';
    }

    if ($signatory_signature_path !== '') {
        return $signatory_signature_path;
    }

    $status = strtolower(trim((string) ($detail['status'] ?? '')));
    if ($status === 'siap' || $status === 'lulus' || !empty($detail['preparer_signed_at'])) {
        return trim((string) ($detail['creator_signature_path'] ?? ''));
    }

    return '';
}

function fetchWorkflowData(mysqli $conn, array $draft): array
{
    $draft_id = (int) ($draft['id'] ?? 0);
    $approval_recipients = getLetterApprovalRecipients($conn, $draft_id);

    $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 ($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 = formatDateLabel(($draft['preparer_signed_at'] ?? '') ?: (($draft['status'] ?? 'draf') === 'siap' ? ($draft['updated_at'] ?? '') : ''), true);
    }

    $flow_status_labels = [
        'disediakan' => 'Disediakan',
        'disediakan_ditandatangani' => 'Disediakan dan Ditandatangani',
        'disahkan' => 'Disahkan',
        'disahkan_ditandatangani' => 'Disahkan dan Ditandatangani',
        'disokong' => 'Disokong',
        'disokong_ditandatangani' => 'Disokong dan Ditandatangani',
        'diluluskan_ditandatangani' => 'Diluluskan dan Ditandatangani',
        'ditandatangani' => 'Ditandatangani',
        'diterima' => 'Diterima',
        'menunggu' => 'Menunggu Kelulusan',
        'menunggu_pengesahan' => 'Menunggu Pengesahan',
        'menunggu_tandatangan' => 'Menunggu Tandatangan',
        'ditolak' => 'Ditolak',
        'perlu_pindaan_penyedia' => 'Perlu Pindaan oleh Penyedia',
        'sedang_dipinda_ketua_bahagian' => 'Sedang Dipinda oleh Ketua Bahagian',
    ];

    $steps[] = [
        'label' => 'Penyedia',
        'name' => (string) (($draft['created_by_name'] ?? '') ?: ($draft['signatory_name'] ?? '-')),
        'status' => $flow_status_labels[$preparer_status] ?? ucfirst(str_replace('_', ' ', $preparer_status)),
        'rawStatus' => $preparer_status,
        'receivedLabel' => 'Disediakan pada',
        'receivedAt' => formatDateLabel($draft['created_at'] ?? null, true),
        'signedLabel' => $has_department_officer_step ? 'Disahkan pada' : 'Ditandatangani pada',
        'signedAt' => $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' => (string) ($draft['memo_preparer_head_name'] ?? '-'),
            'status' => $flow_status_labels[$memo_head_flow_status] ?? ucfirst(str_replace('_', ' ', $memo_head_flow_status)),
            'rawStatus' => $memo_head_flow_status,
            'receivedLabel' => 'Diterima pada',
            'receivedAt' => formatDateLabel($draft['memo_preparer_head_requested_at'] ?? null, true),
            'signedLabel' => 'Disahkan pada',
            'signedAt' => formatDateLabel($draft['memo_preparer_head_responded_at'] ?? null, true),
        ];
    }

    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' => (string) ($draft['department_officer_name'] ?? '-'),
            'status' => $flow_status_labels[$department_officer_flow_status] ?? ucfirst(str_replace('_', ' ', $department_officer_flow_status)),
            'rawStatus' => $department_officer_flow_status,
            'receivedLabel' => 'Diterima pada',
            'receivedAt' => formatDateLabel($draft['department_officer_requested_at'] ?? null, true),
            'signedLabel' => 'Ditandatangani pada',
            'signedAt' => formatDateLabel($draft['department_officer_responded_at'] ?? null, true),
        ];
    }

    $is_doc_ready = in_array(strtolower(trim((string) ($draft['approval_status'] ?? ''))), ['lulus', 'siap'], true) || ($draft['status'] ?? '') === 'siap';

    foreach ($approval_recipients as $recipient) {
        $recipient_source_type = $recipient['source_type'] ?? '';
        $recipient_status = $recipient['status'] ?? 'belum_mula';
        if (($recipient_source_type === 'kepada' || $is_surat_rasmi_flow || $is_memo_flow) && ($recipient_status === 'lulus' || $is_doc_ready)) {
            $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' => (string) (($recipient['fullname'] ?? '') ?: ($recipient['position_label'] ?? '-')),
            'status' => $flow_status_labels[$recipient_status] ?? ucfirst(str_replace('_', ' ', $recipient_status)),
            'rawStatus' => $recipient_status,
            'receivedLabel' => 'Diterima pada',
            'receivedAt' => formatDateLabel($recipient['requested_at'] ?: ($is_doc_ready ? ($draft['updated_at'] ?? $draft['created_at']) : null), true),
            'signedLabel' => ($recipient_source_type === 'kepada' || $is_surat_rasmi_flow || $is_memo_flow) ? 'Diterima pada' : 'Ditandatangani pada',
            'signedAt' => formatDateLabel($recipient['responded_at'] ?: ($is_doc_ready ? ($draft['updated_at'] ?? $draft['created_at']) : null), true),
        ];
    }

    // Add staff from distribution_staff_list (Senarai Edaran)
    $dist_staff_json = trim((string) ($draft['distribution_staff_list'] ?? ''));
    if ($dist_staff_json !== '' && $dist_staff_json !== '[]') {
        $dist_decoded = json_decode($dist_staff_json, true);
        if (is_array($dist_decoded)) {
            $dist_ids = [];
            foreach ($dist_decoded as $s_item) {
                $s_int = (int) (is_array($s_item) ? ($s_item['id'] ?? 0) : $s_item);
                if ($s_int > 0) {
                    $dist_ids[] = $s_int;
                }
            }
            if (!empty($dist_ids)) {
                $placeholders = implode(',', array_fill(0, count($dist_ids), '?'));
                $dist_u_stmt = mysqli_prepare($conn, "SELECT id, fullname, position FROM users WHERE id IN ({$placeholders})");
                if ($dist_u_stmt) {
                    $types = str_repeat('i', count($dist_ids));
                    mysqli_stmt_bind_param($dist_u_stmt, $types, ...$dist_ids);
                    mysqli_stmt_execute($dist_u_stmt);
                    $dist_u_res = mysqli_stmt_get_result($dist_u_stmt);
                    while ($u_row = $dist_u_res ? mysqli_fetch_assoc($dist_u_res) : null) {
                        $dist_status = $is_doc_ready ? 'diterima' : 'belum_mula';
                        $steps[] = [
                            'label' => 'Senarai Edaran',
                            'name' => (string) (($u_row['fullname'] ?? '') ?: ($u_row['position'] ?? '-')),
                            'status' => $flow_status_labels[$dist_status] ?? 'Diterima',
                            'rawStatus' => $dist_status,
                            'receivedLabel' => 'Diterima pada',
                            'receivedAt' => $is_doc_ready ? formatDateLabel($draft['updated_at'] ?? $draft['created_at'], true) : '',
                            'signedLabel' => 'Diterima pada',
                            'signedAt' => $is_doc_ready ? formatDateLabel($draft['updated_at'] ?? $draft['created_at'], true) : '',
                        ];
                    }
                }
            }
        }
    }

    $approval_status = $draft['approval_status'] ?? 'draft';
    $current_holder = null;

    if (($draft['status'] ?? 'draf') === 'draf' || $approval_status === 'draft') {
        $current_holder = [
            'name' => (string) (($draft['created_by_name'] ?? '') ?: ($draft['signatory_name'] ?? '-')),
            'receivedLabel' => 'Disediakan pada',
            'receivedAt' => formatDateLabel($draft['created_at'] ?? null, true),
            'signedLabel' => 'Ditandatangani pada',
            'signedAt' => formatDateLabel(($draft['preparer_signed_at'] ?? '') ?: (($draft['status'] ?? 'draf') === 'siap' ? ($draft['updated_at'] ?? '') : ''), true),
        ];
    } elseif ($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
        ) {
            $current_holder = [
                'name' => (string) ($draft['memo_preparer_head_name'] ?? '-'),
                'receivedLabel' => 'Diterima pada',
                'receivedAt' => formatDateLabel($draft['memo_preparer_head_requested_at'] ?? null, true),
                'signedLabel' => 'Disahkan pada',
                'signedAt' => formatDateLabel($draft['memo_preparer_head_responded_at'] ?? null, true),
            ];
        } else {
            $current_holder = [
                'name' => (string) ($draft['department_officer_name'] ?? '-'),
                'receivedLabel' => 'Diterima pada',
                'receivedAt' => formatDateLabel($draft['department_officer_requested_at'] ?? null, true),
                'signedLabel' => 'Ditandatangani pada',
                'signedAt' => formatDateLabel($draft['department_officer_responded_at'] ?? null, true),
            ];
        }
    } elseif ($approval_status === 'perlu_pindaan_penyedia') {
        $current_holder = [
            'name' => (string) (($draft['created_by_name'] ?? '') ?: ($draft['signatory_name'] ?? '-')),
            'receivedLabel' => 'Dikembalikan pada',
            'receivedAt' => formatDateLabel($draft['updated_at'] ?? null, true),
            'signedLabel' => '',
            'signedAt' => '',
        ];
    } elseif ($approval_status === 'sedang_dipinda_ketua_bahagian') {
        $current_holder = [
            'name' => (string) ($draft['department_officer_name'] ?? '-'),
            'receivedLabel' => 'Pindaan bermula pada',
            'receivedAt' => formatDateLabel($draft['updated_at'] ?? null, true),
            'signedLabel' => '',
            'signedAt' => '',
        ];
    } else {
        $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) {
                $current_holder = [
                    'name' => (string) (($current['fullname'] ?? '') ?: ($current['position_label'] ?? '-')),
                    'receivedLabel' => 'Diterima pada',
                    'receivedAt' => formatDateLabel($current['requested_at'] ?? null, true),
                    'signedLabel' => 'Ditandatangani pada',
                    'signedAt' => formatDateLabel($current['responded_at'] ?? null, true),
                ];
            }
        } elseif ($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) {
                $current_holder = [
                    'name' => (string) (($current['fullname'] ?? '') ?: ($current['position_label'] ?? '-')),
                    'receivedLabel' => 'Diterima pada',
                    'receivedAt' => formatDateLabel($current['requested_at'] ?? null, true),
                    'signedLabel' => 'Ditandatangani pada',
                    'signedAt' => formatDateLabel($current['responded_at'] ?? null, true),
                ];
            }
        }
    }

    return [
        'currentHolder' => $current_holder,
        'workflowSteps' => $steps,
    ];
}

$detail_sql = "
    SELECT
        ld.id,
        ld.document_id,
        ld.ref_no,
        ld.subject,
        ld.doc_type,
        ld.status,
        ld.recipient_organization,
        ld.attention_to,
        ld.letter_body,
        ld.letter_pages,
        ld.include_distribution_page,
        ld.distribution_page_content,
        ld.approval_page_body,
        ld.approval_route_bodies,
        ld.signatory_name,
        ld.signatory_position,
        ld.signatory_department,
        ld.signatory_signature_path,
        creator.signature_path AS creator_signature_path,
        department_officer.signature_path AS department_officer_signature_path,
        creator.short_name AS created_by_short_name,
        creator.fullname AS created_by_name,
        department_officer.fullname AS department_officer_name,
        memo_preparer_head.fullname AS memo_preparer_head_name,
        ld.memo_preparer_head_user_id,
        ld.memo_preparer_head_status,
        ld.memo_preparer_head_requested_at,
        ld.memo_preparer_head_responded_at,
        ld.preparer_signed_at,
        ld.letter_date,
        ld.department,
        ld.created_at,
        ld.updated_at,
        ld.created_by,
        ld.updated_by,
        ld.support_user_id,
        ld.support_status,
        ld.support_requested_at,
        ld.support_responded_at,
        ld.department_officer_user_id,
        ld.department_officer_status,
        ld.department_officer_requested_at,
        ld.department_officer_responded_at,
        ld.department_officer_approved_at,
        ld.approval_status,
        creator.fullname AS applicant_name,
        creator.department AS applicant_department,
        (
            SELECT lar.status
            FROM letter_approval_recipients lar
            WHERE lar.draft_id = ld.id
              AND lar.user_id = ?
            ORDER BY lar.route_order ASC, lar.id ASC
            LIMIT 1
        ) AS recipient_status,
        (
            SELECT COALESCE(lar.responded_at, lar.approved_at, lar.requested_at, lar.updated_at, lar.created_at)
            FROM letter_approval_recipients lar
            WHERE lar.draft_id = ld.id
              AND lar.user_id = ?
            ORDER BY lar.route_order ASC, lar.id ASC
            LIMIT 1
        ) AS recipient_date
    FROM letter_drafts ld
    LEFT JOIN users creator ON creator.id = ld.created_by
    LEFT JOIN users department_officer ON department_officer.id = ld.department_officer_user_id
    LEFT JOIN users memo_preparer_head ON memo_preparer_head.id = ld.memo_preparer_head_user_id
    WHERE ld.id = ?
      AND ld.deleted_at IS NULL
      AND (
          ld.created_by = ?
          OR ld.updated_by = ?
          OR ld.support_user_id = ?
          OR ld.department_officer_user_id = ?
          OR ld.department_officer_user_id IS NULL
          OR ld.department_officer_user_id = 0
          OR EXISTS (
              SELECT 1
              FROM letter_approval_recipients access_lar
              WHERE access_lar.draft_id = ld.id
                AND access_lar.user_id = ?
          )
          OR (
              ld.distribution_staff_list IS NOT NULL
              AND ld.distribution_staff_list != ''
              AND ld.distribution_staff_list != '[]'
              AND (
                  ld.distribution_staff_list LIKE CONCAT('%\"', ?, '\"%')
                  OR ld.distribution_staff_list LIKE CONCAT('%[', ?, ',%')
                  OR ld.distribution_staff_list LIKE CONCAT('%,', ?, ',%')
                  OR ld.distribution_staff_list LIKE CONCAT('%,', ?, ']%')
                  OR ld.distribution_staff_list LIKE CONCAT('%[', ?, ']%')
              )
          )
      )
    LIMIT 1";

$detail_stmt = mysqli_prepare($conn, $detail_sql);
if (!$detail_stmt) {
    respond(500, [
        'success' => false,
        'message' => 'Ralat sistem semasa membaca detail surat.',
    ]);
}

mysqli_stmt_bind_param(
    $detail_stmt,
    'iiiiiiiiiiiii',
    $user_id,
    $user_id,
    $draft_id,
    $user_id,
    $user_id,
    $user_id,
    $user_id,
    $user_id,
    $user_id,
    $user_id,
    $user_id,
    $user_id,
    $user_id
);
mysqli_stmt_execute($detail_stmt);
$detail_result = mysqli_stmt_get_result($detail_stmt);
$detail = $detail_result ? mysqli_fetch_assoc($detail_result) : null;

if (!$detail) {
    respond(404, [
        'success' => false,
        'message' => 'Surat tidak dijumpai atau tiada akses.',
    ]);
}

$current_status = '';
$activity_date = $detail['updated_at'] ?? '';

if ((int) ($detail['support_user_id'] ?? 0) === $user_id) {
    $current_status = (string) ($detail['support_status'] ?? '');
    $activity_date = $detail['support_responded_at'] ?: ($detail['support_requested_at'] ?: $activity_date);
}

if ((int) ($detail['department_officer_user_id'] ?? 0) === $user_id) {
    $current_status = (string) ($detail['department_officer_status'] ?? '');
    $activity_date = $detail['department_officer_responded_at']
        ?: ($detail['department_officer_approved_at'] ?: ($detail['department_officer_requested_at'] ?: $activity_date));
}

if (!empty($detail['recipient_status'])) {
    $current_status = (string) $detail['recipient_status'];
    $activity_date = $detail['recipient_date'] ?: $activity_date;
}

if ($current_status === '') {
    $current_status = (string) ($detail['approval_status'] ?? '');
}

$user_action_status = strtolower(trim((string) $current_status));
$overall_approval_status = strtolower(trim((string) ($detail['approval_status'] ?? '')));

$can_approve = false;

if (!in_array($overall_approval_status, ['lulus', 'ditolak', 'draft', 'draf'], true)) {
    if ($overall_approval_status === 'menunggu_pegawai_bahagian') {
        if (
            in_array(strtolower(trim((string) ($detail['doc_type'] ?? ''))), ['memo', 'surat rasmi'], true)
            && ($detail['memo_preparer_head_status'] ?? '') === 'menunggu'
        ) {
            if ((int) ($detail['memo_preparer_head_user_id'] ?? 0) === $user_id) {
                $can_approve = true;
            }
        } elseif ((int) ($detail['department_officer_user_id'] ?? 0) === $user_id) {
            $officer_stat = strtolower(trim((string) ($detail['department_officer_status'] ?? '')));
            if (in_array($officer_stat, ['menunggu', 'belum_mula', ''], true)) {
                $can_approve = true;
            }
        }
    } else {
        $approval_recipients = getLetterApprovalRecipients($conn, $draft_id);
        $current_pending_recipient = null;
        foreach ($approval_recipients as $recipient) {
            $rec_stat = strtolower(trim((string) ($recipient['status'] ?? '')));
            if (in_array($rec_stat, ['menunggu', 'menunggu_tandatangan', 'belum_mula'], true)) {
                $current_pending_recipient = $recipient;
                break;
            }
        }

        if ($current_pending_recipient && (int) ($current_pending_recipient['user_id'] ?? 0) === $user_id) {
            $can_approve = true;
        }
    }
}

$attachments = [];
$attachment_stmt = mysqli_prepare($conn, "
    SELECT id, file_path, original_name, created_at
    FROM document_attachments
    WHERE document_id = ?
    ORDER BY id ASC
");

if ($attachment_stmt) {
    $document_id = (int) ($detail['document_id'] ?? 0);
    mysqli_stmt_bind_param($attachment_stmt, 'i', $document_id);
    mysqli_stmt_execute($attachment_stmt);
    $attachment_result = mysqli_stmt_get_result($attachment_stmt);

    while ($row = $attachment_result ? mysqli_fetch_assoc($attachment_result) : null) {
        $file_path = (string) ($row['file_path'] ?? '');
        $original_name = (string) ($row['original_name'] ?? '');
        $file_name = $original_name !== '' ? $original_name : basename($file_path);
        $extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        $attachments[] = [
            'id' => (int) ($row['id'] ?? 0),
            'fileName' => $file_name,
            'fileType' => $extension,
            'sizeLabel' => fileSizeLabel($file_path),
            'dateLabel' => formatDateLabel($row['created_at'] ?? null),
            'viewUrl' => '/api/mobile_file.php?action=attachment&user_id=' . $user_id . '&draft_id=' . $draft_id . '&attachment_id=' . (int) ($row['id'] ?? 0),
            'downloadUrl' => '/api/mobile_file.php?action=attachment&download=1&user_id=' . $user_id . '&draft_id=' . $draft_id . '&attachment_id=' . (int) ($row['id'] ?? 0),
        ];
    }
}

$workflow_data = fetchWorkflowData($conn, $detail);

respond(200, [
    'success' => true,
    'detail' => [
        'draftId' => (int) ($detail['id'] ?? 0),
        'createdById' => (int) ($detail['created_by'] ?? 0),
        'referenceNo' => (string) ($detail['ref_no'] ?? ''),
        'title' => (string) ($detail['subject'] ?? ''),
        'documentType' => (string) ($detail['doc_type'] ?? ''),
        'status' => statusLabelFromValue($current_status),
        'approvalStatusRaw' => (string) ($detail['approval_status'] ?? ''),
        'revisionNote' => plainTextFromHtml(($detail['support_note'] ?? '') ?: ($detail['department_officer_note'] ?? '')),
        'canApprove' => (bool) $can_approve,
        'userStatus' => statusLabelFromValue($user_action_status),
        'rawUserStatus' => $user_action_status,
        'letterDate' => formatDateLabel($detail['letter_date'] ?? null),
        'applicant' => (string) ($detail['applicant_name'] ?? ''),
        'department' => (string) (($detail['department'] ?? '') ?: ($detail['applicant_department'] ?? '')),
        'receivedAt' => formatDateLabel($activity_date, true),
        'letterPdfUrl' => '/api/mobile_file.php?action=letter_pdf&user_id=' . $user_id . '&draft_id=' . $draft_id,
        'letterDownloadUrl' => '/api/mobile_file.php?action=letter_pdf&download=1&user_id=' . $user_id . '&draft_id=' . $draft_id,
        'recipientOrganization' => (string) ($detail['recipient_organization'] ?? ''),
        'attentionTo' => (string) ($detail['attention_to'] ?? ''),
        'signatoryName' => (string) ($detail['signatory_name'] ?? ''),
        'signatoryPosition' => (string) ($detail['signatory_position'] ?? ''),
        'signatoryDepartment' => (string) ($detail['signatory_department'] ?? ''),
        'signatorySignatureUrl' => getSignatorySignatureUrl($detail),
        'bodyText' => plainTextFromLetterPages($detail['letter_pages'] ?? '', $detail['letter_body'] ?? ''),
        'bodyPages' => plainTextPageList($detail['letter_pages'] ?? '', $detail['letter_body'] ?? ''),
        'approvalPages' => fetchApprovalPages($conn, $draft_id, $detail['approval_route_bodies'] ?? '', $detail['approval_page_body'] ?? '', $detail),
        'distributionPages' => fetchDistributionPages($detail),
        'attachments' => $attachments,
        'currentHolder' => $workflow_data['currentHolder'],
        'workflowSteps' => $workflow_data['workflowSteps'],
    ],
]);
