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

$draft_module_view = $draft_module_view ?? 'list';
$is_draft_dashboard = $draft_module_view === 'dashboard';
$page_title = $is_draft_dashboard ? 'Dashboard Surat' : 'Senarai Surat';
$sidebar_current_page = $is_draft_dashboard ? 'draft_dashboard.php' : 'draft_letters.php';

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

if (!currentUserCan($conn, 'draft_letter', 'read')) {
    echo "<script>alert('Anda tidak mempunyai kebenaran untuk membuka Modul Surat.'); window.location='dashboard.php';</script>";
    exit();
}

$can_create_draft = currentUserCan($conn, 'draft_letter', 'create');
$can_update_draft = currentUserCan($conn, 'draft_letter', 'update');
$can_delete_draft = currentUserCan($conn, 'draft_letter', 'delete');
$draft_status_labels = getDraftLetterStatusList();
$support_status_labels = getDraftLetterSupportStatusList();
$approval_status_labels = getDraftLetterApprovalStatusList();
$filter_search = trim((string) ($_GET['search'] ?? ''));
$filter_date_from = trim((string) ($_GET['date_from'] ?? ''));
$filter_date_to = trim((string) ($_GET['date_to'] ?? ''));
$filter_status = trim((string) ($_GET['status'] ?? ''));
$filter_from = trim((string) ($_GET['from'] ?? ''));
if ($filter_status !== '' && !array_key_exists($filter_status, $approval_status_labels)) {
    $filter_status = '';
}
if ($filter_date_from !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $filter_date_from)) {
    $filter_date_from = '';
}
if ($filter_date_to !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $filter_date_to)) {
    $filter_date_to = '';
}

$status_message = '';
$status_type = 'success';
if (isset($_GET['success'])) {
    if ($_GET['success'] === 'created') {
        $status_message = 'Draf surat baharu berjaya dimasukkan dalam sistem.';
    } elseif ($_GET['success'] === 'updated') {
        $status_message = 'Draf surat berjaya dikemaskini.';
    } elseif ($_GET['success'] === 'deleted') {
        $status_message = 'Draf surat berjaya dipadam.';
    } elseif ($_GET['success'] === 'support_sent') {
        $status_message = 'Permohonan sokongan telah dihantar ke emel pengguna berdaftar.';
    }
} elseif (isset($_GET['error'])) {
    $status_type = 'error';
    if ($_GET['error'] === 'not_found') {
        $status_message = 'Draf surat tidak dijumpai.';
    } elseif ($_GET['error'] === 'unauthorized') {
        $status_message = 'Anda tidak dibenarkan mengakses surat tersebut.';
    } elseif ($_GET['error'] === 'delete_failed') {
        $status_message = 'Surat tidak dapat dipadam. Sila cuba semula.';
    } else {
        $status_message = 'Operasi tidak dapat diselesaikan. Sila cuba semula.';
    }
}

$sql = "SELECT ld.*, f.folder_name, f.folder_code,
        creator.fullname AS created_by_name,
        d.id AS active_document_id, d.file_numbering,
        (SELECT COUNT(*) FROM document_attachments a WHERE a.document_id = ld.document_id) AS attachment_count
    FROM letter_drafts ld
    INNER JOIN folders f ON f.id = ld.folder_id
    LEFT JOIN users creator ON creator.id = ld.created_by
    LEFT JOIN documents d ON d.id = ld.document_id AND d.deleted_at IS NULL
    WHERE ld.deleted_at IS NULL";
$sql_types = '';
$sql_params = [];

if (!$is_draft_dashboard) {
    if ($filter_search !== '') {
        $search_like = '%' . $filter_search . '%';
        $sql .= " AND (ld.ref_no LIKE ? OR ld.subject LIKE ? OR f.folder_name LIKE ? OR f.folder_code LIKE ?)";
        $sql_types .= 'ssss';
        array_push($sql_params, $search_like, $search_like, $search_like, $search_like);
    }
    if ($filter_date_from !== '') {
        $sql .= " AND ld.letter_date >= ?";
        $sql_types .= 's';
        $sql_params[] = $filter_date_from;
    }
    if ($filter_date_to !== '') {
        $sql .= " AND ld.letter_date <= ?";
        $sql_types .= 's';
        $sql_params[] = $filter_date_to;
    }
    if ($filter_status !== '') {
        $sql .= " AND ld.approval_status = ?";
        $sql_types .= 's';
        $sql_params[] = $filter_status;
    }
    if ($filter_from !== '') {
        $from_like = '%' . $filter_from . '%';
        $sql .= " AND (ld.department LIKE ? OR ld.signatory_department LIKE ? OR ld.signatory_position LIKE ? OR ld.signatory_name LIKE ?)";
        $sql_types .= 'ssss';
        array_push($sql_params, $from_like, $from_like, $from_like, $from_like);
    }
}

if ($role !== 'superadmin') {
    $sql .= " AND (ld.department = ? OR ld.created_by = ? OR ld.support_user_id = ? OR ld.department_officer_user_id = ? OR ld.memo_preparer_head_user_id = ?
        OR EXISTS (
            SELECT 1 FROM letter_approval_recipients lar
            WHERE lar.draft_id = ld.id AND lar.user_id = ?
        ))
        AND ((ld.status <> 'draf' AND ld.approval_status <> 'draft') OR ld.created_by = ?)";
    $current_user_id = (int) ($_SESSION['user_id'] ?? 0);
    $sql_types .= 'siiiiii';
    array_push($sql_params, $user_department, $current_user_id, $current_user_id, $current_user_id, $current_user_id, $current_user_id, $current_user_id);
}

$sql .= " ORDER BY COALESCE(ld.updated_at, ld.created_at) DESC, ld.id DESC";
$stmt = mysqli_prepare($conn, $sql);
if ($sql_types !== '') {
    $bind_params = [$sql_types];
    foreach ($sql_params as $index => $param) {
        $bind_params[] = &$sql_params[$index];
    }
    call_user_func_array([$stmt, 'bind_param'], $bind_params);
}
mysqli_stmt_execute($stmt);
$drafts = mysqli_fetch_all(mysqli_stmt_get_result($stmt), MYSQLI_ASSOC);

$office_folder_sql = "SELECT COUNT(*) AS total FROM folders WHERE deleted_at IS NULL AND COALESCE(folder_type, 'office') <> 'sendirian'";
if ($role !== 'superadmin') {
    $office_folder_sql .= " AND department = ?";
    $folder_count_stmt = mysqli_prepare($conn, $office_folder_sql);
    mysqli_stmt_bind_param($folder_count_stmt, "s", $user_department);
    mysqli_stmt_execute($folder_count_stmt);
    $office_folder_count = (int) (mysqli_fetch_assoc(mysqli_stmt_get_result($folder_count_stmt))['total'] ?? 0);
} else {
    $office_folder_count_result = mysqli_query($conn, $office_folder_sql);
    $office_folder_count = (int) (mysqli_fetch_assoc($office_folder_count_result)['total'] ?? 0);
}

$total_drafts = count($drafts);
$total_ready = 0;
$total_attachments = 0;
$total_waiting_support = 0;
$total_not_sent = 0;
$total_waiting_action = 0;
$total_approved = 0;
$total_rejected = 0;
foreach ($drafts as $draft_row) {
    $row_status = $draft_row['status'] ?? 'draf';
    $row_approval_status = $draft_row['approval_status'] ?? 'draft';
    if (($draft_row['status'] ?? 'draf') === 'siap') {
        $total_ready++;
    }
    if (in_array($draft_row['approval_status'] ?? '', ['menunggu_pegawai_bahagian', 'menunggu_pelulus', 'menunggu_pelulus_akhir'], true)
        || (($draft_row['support_status'] ?? 'tidak_perlu') === 'menunggu')) {
        $total_waiting_support++;
    }
    if (($draft_row['approval_status'] ?? '') === 'lulus') {
        $total_approved++;
    }
    if (($draft_row['approval_status'] ?? '') === 'ditolak') {
        $total_rejected++;
    }
    if ($row_approval_status === 'lulus') {
        // Already counted above; category used for chart below.
    } elseif ($row_approval_status === 'ditolak') {
        // Already counted above; category used for chart below.
    } elseif ($row_status === 'draf' || $row_approval_status === 'draft') {
        $total_not_sent++;
    } else {
        $total_waiting_action++;
    }
    $total_attachments += (int) ($draft_row['attachment_count'] ?? 0);
}
$dashboard_status_chart = [
    'Lulus' => $total_approved,
    'Belum Dihantar' => $total_not_sent,
    'Menunggu Tindakan' => $total_waiting_action,
    'Ditolak' => $total_rejected,
];
$draft_pagination = $is_draft_dashboard ? null : paginateArrayItems($drafts, 'page', 15);
$display_drafts = $is_draft_dashboard ? array_slice($drafts, 0, 5) : $draft_pagination['items'];

foreach ($display_drafts as $_dtr => $_draft) {
    $subject_words = preg_split('/\s+/', trim((string) ($_draft['subject'] ?? '')), -1, PREG_SPLIT_NO_EMPTY);
    $display_drafts[$_dtr]['subject_short'] = count($subject_words) > 5 ? implode(' ', array_slice($subject_words, 0, 5)) . '...' : implode(' ', $subject_words);
}

function getSuratRasmiRecipientDisplay($draft) {
    if (strcasecmp(trim((string) ($draft['doc_type'] ?? '')), 'Surat Rasmi') !== 0) {
        return '';
    }

    $letter_pages = json_decode((string) ($draft['letter_pages'] ?? ''), true);
    $letter_html = is_array($letter_pages) && !empty($letter_pages[0])
        ? (string) $letter_pages[0]
        : (string) ($draft['letter_body'] ?? '');
    if (trim(strip_tags($letter_html)) === '') {
        return '';
    }

    $previous_libxml_errors = libxml_use_internal_errors(true);
    $document = new DOMDocument('1.0', 'UTF-8');
    $document->loadHTML('<?xml encoding="UTF-8"><div id="surat-rasmi-recipient">' . $letter_html . '</div>');
    libxml_clear_errors();
    libxml_use_internal_errors($previous_libxml_errors);

    $paragraphs = $document->getElementsByTagName('p');
    $has_generated_date = false;
    foreach ($paragraphs as $paragraph) {
        if ($paragraph->getAttribute('data-surat-rasmi-generated-line') === 'date') {
            $has_generated_date = true;
            break;
        }
    }

    $recipient_lines = [];
    $started = false;
    $after_generated_date = !$has_generated_date;
    $fallback_header_lines = 0;
    foreach ($paragraphs as $paragraph) {
        $generated_line = $paragraph->getAttribute('data-surat-rasmi-generated-line');
        if ($generated_line === 'date') {
            $after_generated_date = true;
            continue;
        }
        if ($generated_line !== '' || !$after_generated_date) {
            continue;
        }

        $line = html_entity_decode($paragraph->textContent ?? '', ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $line = trim((string) preg_replace('/[\s\p{Z}]+/u', ' ', $line));
        if (!$has_generated_date && $fallback_header_lines < 2) {
            if ($line !== '') {
                $fallback_header_lines++;
            }
            continue;
        }
        if ($line === '') {
            if ($started) {
                break;
            }
            continue;
        }
        if ($started && preg_match('/^(tuan\/?puan|puan|tuan),?$/iu', $line)) {
            break;
        }

        $recipient_lines[] = $line;
        $started = true;
        if (count($recipient_lines) >= 6) {
            break;
        }
    }

    return implode("\n", $recipient_lines);
}

function formatDraftTraceDate($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 getDraftCurrentHolder($draft) {
    $approval_status = $draft['approval_status'] ?? 'draft';
    $routing_recipients = $draft['_routing_recipients'] ?? [];

    if ($approval_status === 'menunggu_pegawai_bahagian') {
        return [
            'label' => 'sekarang',
            'name' => $draft['department_officer_name'] ?? '-',
            'since' => formatDraftTraceDate($draft['department_officer_requested_at'] ?? ''),
        ];
    }

    if ($approval_status === 'perlu_pindaan_penyedia') {
        return [
            'label' => 'Perlu Pindaan',
            'name' => ($draft['created_by_name'] ?? '') ?: ($draft['signatory_name'] ?? '-'),
            'since' => formatDraftTraceDate($draft['updated_at'] ?? ''),
        ];
    }

    if ($approval_status === 'sedang_dipinda_ketua_bahagian') {
        return [
            'label' => 'Sedang Dipinda',
            'name' => $draft['department_officer_name'] ?? '-',
            'since' => formatDraftTraceDate($draft['updated_at'] ?? ''),
        ];
    }

    if ($approval_status === 'menunggu_pelulus') {
        $pending_names = [];
        $requested_at = '';
        foreach ($routing_recipients as $recipient) {
            if (!in_array($recipient['status'] ?? '', ['menunggu', 'menunggu_tandatangan'], true)) {
                continue;
            }
            $pending_names[] = trim((string) (($recipient['fullname'] ?? '') ?: ($recipient['position_label'] ?? '')));
            if ($requested_at === '' && !empty($recipient['requested_at'])) {
                $requested_at = $recipient['requested_at'];
            }
        }
        return [
            'label' => 'sekarang',
            'name' => $pending_names ? implode(', ', $pending_names) : '-',
            'since' => formatDraftTraceDate($requested_at),
        ];
    }

    if ($approval_status === 'menunggu_pelulus_akhir') {
        return [
            'label' => 'sekarang',
            'name' => '-',
            'since' => '',
        ];
    }

    if ($approval_status === 'lulus') {
        $approved_names = array_values(array_filter(array_map(function ($recipient) {
            return ($recipient['status'] ?? '') === 'lulus'
                ? trim((string) (($recipient['fullname'] ?? '') ?: ($recipient['position_label'] ?? '')))
                : '';
        }, $routing_recipients)));
        return [
            'label' => 'Lulus',
            'name' => $approved_names ? implode(', ', $approved_names) : '-',
            'since' => '',
        ];
    }

    if ($approval_status === 'ditolak') {
        return [
            'label' => 'Kembali kepada Penyedia',
            'name' => ($draft['created_by_name'] ?? '') ?: ($draft['signatory_name'] ?? '-'),
            'since' => getDraftRejectedAt($draft),
        ];
    }

    return [
        'label' => 'Belum dihantar',
        'name' => ($draft['created_by_name'] ?? '') ?: ($draft['signatory_name'] ?? '-'),
        'since' => formatDraftTraceDate($draft['created_at'] ?? ''),
    ];
}

function getDraftRejectedByName($draft) {
    if (($draft['department_officer_status'] ?? '') === 'ditolak') {
        return $draft['department_officer_name'] ?? '-';
    }
    foreach (($draft['_routing_recipients'] ?? []) as $recipient) {
        if (($recipient['status'] ?? '') === 'ditolak') {
            return ($recipient['fullname'] ?? '') ?: ($recipient['position_label'] ?? '-');
        }
    }
    return '-';
}

function getDraftRejectedAt($draft) {
    if (($draft['department_officer_status'] ?? '') === 'ditolak') {
        return formatDraftTraceDate($draft['department_officer_responded_at'] ?? '');
    }
    foreach (($draft['_routing_recipients'] ?? []) as $recipient) {
        if (($recipient['status'] ?? '') === 'ditolak') {
            return formatDraftTraceDate($recipient['responded_at'] ?? '');
        }
    }
    return '';
}

function getDraftTraceSteps($draft) {
    $department_officer_status = $draft['department_officer_status'] ?? 'tidak_perlu';
    $has_department_officer_step = !empty($draft['department_officer_name']) || $department_officer_status !== 'tidak_perlu';
    $preparer_status = $has_department_officer_step
        ? ($department_officer_status === 'lulus' ? 'disahkan' : 'menunggu_pengesahan')
        : 'lulus';
    $preparer_date = $has_department_officer_step && $department_officer_status === 'lulus'
        ? formatDraftTraceDate($draft['department_officer_responded_at'] ?? '')
        : formatDraftTraceDate($draft['created_at'] ?? '');

    $steps = [
        [
            'label' => 'Penyedia',
            'name' => ($draft['created_by_name'] ?? '') ?: ($draft['signatory_name'] ?? '-'),
            'status' => $preparer_status,
            'date' => $preparer_date,
        ],
    ];

    if ($has_department_officer_step) {
        $steps[] = [
            'label' => 'Ketua Pegawai',
            'name' => $draft['department_officer_name'] ?? '-',
            'status' => $draft['department_officer_status'] ?? 'belum_mula',
            'date' => formatDraftTraceDate(($draft['department_officer_responded_at'] ?? '') ?: ($draft['department_officer_requested_at'] ?? '')),
        ];
    }

    foreach (($draft['_routing_recipients'] ?? []) as $recipient) {
        $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'] ?? 'belum_mula',
            'date' => formatDraftTraceDate(($recipient['responded_at'] ?? '') ?: ($recipient['requested_at'] ?? '')),
        ];
    }

    return $steps;
}

function getDraftTraceStatusLabel($status) {
    $labels = [
        'tidak_perlu' => 'Tidak Perlu',
        'belum_mula' => 'Belum Mula',
        'menunggu' => 'Menunggu',
        'menunggu_pengesahan' => 'Menunggu Pengesahan',
        'menunggu_tandatangan' => 'Menunggu Tandatangan',
        'disahkan' => 'Disahkan',
        'lulus' => 'Selesai Ditandatangani',
        'disokong' => 'Disokong',
        'ditolak' => 'Ditolak',
    ];

    return $labels[$status] ?? ucfirst(str_replace('_', ' ', (string) $status));
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($page_title) ?> | MAINPP WORKSPACE</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;
            --deep-blue: #023e5f;
            --superadmin: #6c5ce7; --superadmin-dark: #5b4cdb;
            --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;
            --success: #1a9955; --danger: #dc3545; --warning: #ffc107;
            --draft: #0d9488; --draft-soft: #e6fffb;
            --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);
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: var(--app-font, 'Segoe UI', 'Inter', Tahoma, Geneva, Verdana, sans-serif); }
        button, input, select, textarea, table { font-family: var(--app-font, 'Segoe UI', 'Inter', Tahoma, Geneva, Verdana, sans-serif); }
        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;
            min-height: 100vh;
            display: flex;
            color: var(--text-main);
            overflow-x: hidden;
        }

        body::before,
        body::after {
            content: "";
            position: fixed;
            pointer-events: none;
            z-index: 0;
        }

        body::before {
            width: 42vw;
            height: 42vw;
            right: -16vw;
            top: -18vw;
            border-radius: 50%;
            background: radial-gradient(circle, rgba(0, 180, 216, 0.24), transparent 62%);
            filter: blur(4px);
        }

        body::after {
            width: 48vw;
            height: 48vw;
            left: 120px;
            bottom: -30vw;
            border-radius: 46px;
            background:
                linear-gradient(155deg, rgba(255, 255, 255, 0.20), rgba(255, 255, 255, 0.03)),
                repeating-linear-gradient(0deg, transparent 0 34px, rgba(0, 119, 182, 0.08) 35px 36px);
            border: 1px solid rgba(255, 255, 255, 0.32);
            transform: rotate(-9deg);
        }

        .sidebar { width: var(--sidebar-width); background: linear-gradient(180deg, rgba(2, 62, 95, 0.94), rgba(0, 119, 182, 0.84)), radial-gradient(circle at 22% 8%, rgba(0, 180, 216, 0.28), transparent 32%); border-right: 1px solid rgba(255, 255, 255, 0.22); position: fixed; height: 100vh; padding: 20px 0; overflow-y: auto; overflow-x: hidden; z-index: 1000; box-shadow: 18px 0 44px rgba(2, 38, 60, 0.20); transition: width 0.3s ease; display:flex; flex-direction:column; backdrop-filter: blur(18px) saturate(1.25); -webkit-backdrop-filter: blur(18px) saturate(1.25); }
        .sidebar.collapsed { width: 70px; }
        .sidebar-header { text-align: center; padding: 0 20px 20px; border-bottom: 1px solid rgba(255, 255, 255, 0.16); margin-bottom: 20px; white-space: nowrap; overflow: hidden; background: transparent !important; }
        .sidebar.collapsed .sidebar-header h3, .sidebar.collapsed .sidebar-header p, .sidebar.collapsed .menu-text { display: none; }
        .sidebar-header img { width: 54px; margin-bottom: 10px; transition: margin 0.3s ease; filter: drop-shadow(0 10px 18px rgba(0,0,0,0.25)); }
        .sidebar.collapsed .sidebar-header img { margin: 0 auto 10px; }
        .sidebar-header h3 { font-size: 1rem; font-weight: 800; color: #fff; margin-bottom: 4px; letter-spacing: 0.01em; }
        .sidebar-header p { font-size: 0.75rem; color: rgba(255,255,255,0.72); }
        .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: rgba(255,255,255,0.58); font-size: 0.72rem; font-weight: 800; 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: rgba(255,255,255,0.88); text-decoration: none; border-radius: 10px; margin-bottom: 5px; transition: all 0.2s ease; font-size: 0.9rem; white-space: nowrap; }
        .sidebar-menu li a:hover, .sidebar-menu li a.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 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: rgba(255,255,255,0.88); background: none; border: none; border-radius: 10px; 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: rgba(255,255,255,0.18); color: #fff; box-shadow: inset 0 0 0 1px rgba(255,255,255,0.18); }
        .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: rgba(255,255,255,0.78); text-decoration: none; border-radius: 8px; 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: rgba(255,255,255,0.16); color: #fff; }
        .sidebar.collapsed + .main { margin-left: 70px; }
        .sidebar-toggle { position: absolute; right: 10px; top: 20px; width: 28px; height: 28px; background: rgba(255,255,255,0.20); color: #fff; border: 1px solid rgba(255,255,255,0.28); border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 0.7rem; box-shadow: 0 10px 22px rgba(0,0,0,0.14); transition: transform 0.3s ease; z-index: 1001; }
        .sidebar.collapsed .sidebar-toggle { transform: rotate(180deg); }
        .main { position: relative; z-index: 1; margin-left: var(--sidebar-width); flex: 1; min-width: 0; max-width: calc(100vw - var(--sidebar-width)); padding: 28px 32px; transition: margin-left 0.3s ease; }
        .top-bar { background: var(--glass); padding: 18px 24px; border-radius: 18px; box-shadow: var(--shadow-soft); margin-bottom: 18px; display: flex; justify-content: space-between; align-items: center; border: 1px solid var(--border); backdrop-filter: blur(22px) saturate(1.25); -webkit-backdrop-filter: blur(22px) saturate(1.25); }
        .top-bar h2 { color: var(--primary-dark); font-size: 1.35rem; font-weight: 850; display: flex; align-items: center; gap: 10px; }
        .top-bar h2 i { color: var(--secondary); }
        .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 { padding: 12px 16px; border-radius: 10px; margin-bottom: 18px; border-left: 4px solid transparent; font-size: 0.92rem; }
        .alert.success { background: #d4edda; color: #155724; border-left-color: var(--success); }
        .alert.error { background: #f8d7da; color: #721c24; border-left-color: var(--danger); }
        .hero-card, .table-card { background: var(--glass); border-radius: 22px; border: 1px solid var(--border); box-shadow: var(--shadow-soft); backdrop-filter: blur(24px) saturate(1.25); -webkit-backdrop-filter: blur(24px) saturate(1.25); }
        .hero-card { padding: 24px; margin-bottom: 22px; }
        .hero-header { display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; margin-bottom: 18px; }
        .hero-header h3 { color: var(--primary-dark); font-size: 1.08rem; font-weight: 850; margin-bottom: 6px; }
        .hero-header p { color: var(--text-muted); line-height: 1.6; max-width: 780px; font-weight: 650; }
        .hero-actions { display: flex; gap: 10px; flex-wrap: wrap; }
        .stats-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 16px; margin-top: 18px; }
        .stat-box { position: relative; overflow: hidden; background: linear-gradient(135deg, rgba(0,119,182,0.94), rgba(0,180,216,0.86)); color: #fff; padding: 20px; border-radius: 18px; text-align: left; box-shadow: 0 18px 34px rgba(0,119,182,0.24); border: 1px solid rgba(255,255,255,0.24); min-height: 132px; }
        .stat-box::after { content: ""; position: absolute; width: 136px; height: 136px; right: -48px; bottom: -74px; border-radius: 50%; background: rgba(255,255,255,0.16); }
        .stat-box i { position: relative; z-index: 1; width: 44px; height: 44px; border-radius: 14px; background: rgba(255,255,255,0.18); display: inline-flex; align-items: center; justify-content: center; font-size: 1.1rem; }
        .stat-box h4 { position: relative; z-index: 1; font-size: 2.1rem; margin: 12px 0 4px; line-height: 1; font-weight: 850; }
        .stat-box p { position: relative; z-index: 1; font-size: 0.88rem; opacity: 0.92; font-weight: 700; line-height: 1.35; }
        .stat-box.waiting { background: linear-gradient(135deg, #d97706, #f59e0b); }
        .stat-box.not-sent { background: linear-gradient(135deg, #64748b, #38bdf8); }
        .stat-box.approved { background: linear-gradient(135deg, #0f766e, #14b8a6); }
        .stat-box.rejected { background: linear-gradient(135deg, #b42318, #ef4444); }
        .chart-card { background: var(--glass); border-radius: 22px; border: 1px solid var(--border); box-shadow: var(--shadow-soft); backdrop-filter: blur(24px) saturate(1.25); -webkit-backdrop-filter: blur(24px) saturate(1.25); padding: 20px 22px; margin-bottom: 22px; }
        .chart-head { margin-bottom: 12px; }
        .chart-head h3 { color: var(--primary-dark); font-size: 1.05rem; font-weight: 850; margin-bottom: 4px; }
        .chart-head p { color: var(--text-muted); font-size: 0.86rem; font-weight: 650; }
        .status-chart-wrap { position: relative; height: 260px; width: 100%; }
        .btn { padding: 10px 18px; border: none; border-radius: 999px; text-decoration: none; font-size: 0.9rem; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; font-weight: 850; transition: transform 0.2s ease, filter 0.2s ease, box-shadow 0.2s ease; }
        .btn:hover { transform: translateY(-1px); filter: brightness(1.04); }
        .btn-primary { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; }
        .btn-secondary { background: rgba(255,255,255,0.68); color: var(--primary-dark); border: 1px solid rgba(0,119,182,0.16); }
        .table-card { overflow: hidden; }
        .table-head { padding: 18px 22px 14px; border-bottom: 1px solid rgba(0,119,182,0.14); display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; }
        .table-head h3 { color: var(--primary-dark); font-size: 1.05rem; font-weight: 850; }
        .table-head p { color: var(--text-muted); font-size: 0.86rem; font-weight: 650; }
        .filter-panel { padding: 16px 22px; border-bottom: 1px solid rgba(0,119,182,0.14); background: rgba(255,255,255,0.34); }
        .filter-grid { display: grid; grid-template-columns: 1.4fr repeat(4, minmax(145px, 1fr)) auto; gap: 10px; align-items: end; }
        .filter-group label { display: block; color: var(--text-main); font-size: 0.78rem; font-weight: 800; margin-bottom: 5px; }
        .filter-group input, .filter-group select { width: 100%; height: 38px; border: 1px solid rgba(0,119,182,0.18); border-radius: 12px; padding: 8px 10px; font-size: 0.86rem; background: rgba(255,255,255,0.78); color: var(--text-main); }
        .filter-group input:focus, .filter-group select:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 4px rgba(0,119,182,0.13); background: #fff; }
        .filter-actions { display: flex; gap: 8px; align-items: center; }
        .filter-actions .btn { width: 40px; min-height: 38px; padding: 0; justify-content: center; white-space: nowrap; }
        .filter-actions .btn i { margin: 0; }
        .table-wrap {
            display: block;
            width: 100%;
            max-width: 100%;
            overflow-x: auto;
            overflow-y: hidden;
            -webkit-overflow-scrolling: touch;
        }
        .table-wrap::-webkit-scrollbar { height: 9px; }
        .table-wrap::-webkit-scrollbar-track { background: rgba(0,119,182,0.08); border-radius: 999px; }
        .table-wrap::-webkit-scrollbar-thumb { background: rgba(0,119,182,0.32); border-radius: 999px; }
        table { width: 100%; border-collapse: collapse; }
        table.dashboard-table { min-width: 760px; }
        table.result-table { min-width: 1420px; }
        th { background: rgba(0,119,182,0.09); color: var(--primary-dark); font-weight: 850; text-align: center; padding: 14px 16px; border-bottom: 1px solid rgba(0,119,182,0.13); font-size: 0.88rem; }
        td { padding: 14px 16px; border-bottom: 1px solid rgba(0,119,182,0.10); vertical-align: middle; text-align: center; font-size: 0.9rem; font-weight: 400; background: rgba(255,255,255,0.54); }
        table.dashboard-table td { text-align: center; }
        table.result-table td { text-align: center; }
        table td.empty-state { text-align: center; }
        tbody td strong { font-weight: 400; }
        tr:hover td { background: rgba(231, 248, 252, 0.72); }
        .ref-pill { display: inline-block; background: #e6f4ff; color: var(--primary-dark); padding: 5px 10px; border-radius: 999px; font-size: 0.82rem; font-weight: 700; }
        .meta-line { color: var(--text-muted); font-size: 0.82rem; margin-top: 4px; }
        .status-pill { display: inline-flex; align-items: center; gap: 6px; padding: 5px 10px; border-radius: 999px; font-size: 0.8rem; font-weight: 700; }
        .status-pill.draf { background: #fff4e5; color: #9a5b00; }
        .status-pill.siap { background: var(--draft-soft); color: var(--draft); }
        .support-pill { display: inline-flex; align-items: center; gap: 6px; padding: 5px 10px; border-radius: 999px; font-size: 0.78rem; font-weight: 700; margin-top: 8px; }
        .support-pill.tidak_perlu { background: #eef2f7; color: #475569; }
        .support-pill.menunggu { background: #fff4e5; color: #9a5b00; }
        .support-pill.menunggu_pegawai_bahagian, .support-pill.menunggu_pelulus, .support-pill.menunggu_pelulus_akhir { background: #fff4e5; color: #9a5b00; }
        .support-pill.disokong { background: #e6fffb; color: #0f766e; }
        .support-pill.lulus { background: #e6fffb; color: #0f766e; }
        .support-pill.ditolak { background: #fde8e8; color: #b42318; }
        .support-pill.draft { background: #eef2f7; color: #475569; }
        .support-pill.perlu_pindaan_penyedia, .support-pill.sedang_dipinda_ketua_bahagian { background: #e8f2ff; color: #075985; }
        .result-pill { display: inline-flex; align-items: center; gap: 7px; padding: 7px 11px; border-radius: 999px; font-size: 0.8rem; font-weight: 400; white-space: nowrap; }
        .result-pill.lulus { background: #e6fffb; color: #0f766e; }
        .result-pill.ditolak { background: #fde8e8; color: #b42318; }
        .result-pill.draft { background: #eef2f7; color: #475569; }
        .result-pill.menunggu_pegawai_bahagian, .result-pill.menunggu_pelulus, .result-pill.menunggu_pelulus_akhir { background: #fff4e5; color: #9a5b00; }
        .result-pill.perlu_pindaan_penyedia, .result-pill.sedang_dipinda_ketua_bahagian { background: #e8f2ff; color: #075985; }
        .inactive-doc { color: var(--danger); font-weight: 800; }
        .trace-box { margin-top: 10px; padding: 10px; background: rgba(255,255,255,0.56); border: 1px solid rgba(0,119,182,0.14); border-radius: 12px; min-width: 260px; }
        .trace-current { display: flex; align-items: flex-start; gap: 8px; color: var(--primary-dark); font-weight: 700; font-size: 0.84rem; margin-bottom: 8px; }
        .trace-current i { color: var(--draft); margin-top: 2px; }
        .trace-current span { display: block; color: var(--text-muted); font-weight: 500; font-size: 0.78rem; margin-top: 2px; }
        .trace-steps { display: flex; flex-direction: column; gap: 6px; }
        .trace-step { display: grid; grid-template-columns: 18px minmax(120px, 1fr) auto; gap: 8px; align-items: start; }
        .trace-dot { width: 10px; height: 10px; border-radius: 50%; background: #cbd5e1; margin: 5px auto 0; }
        .trace-dot.lulus, .trace-dot.disokong, .trace-dot.disahkan { background: #0f766e; }
        .trace-dot.menunggu, .trace-dot.menunggu_pengesahan { background: #d97706; }
        .trace-dot.ditolak { background: #b42318; }
        .trace-label { color: var(--text-main); font-weight: 700; font-size: 0.78rem; line-height: 1.25; }
        .trace-name { color: var(--text-muted); font-size: 0.76rem; margin-top: 1px; line-height: 1.25; }
        .trace-date { color: var(--text-muted); font-size: 0.72rem; margin-top: 1px; }
        .trace-badge { display: inline-flex; align-items: center; justify-content: center; padding: 3px 7px; border-radius: 999px; font-size: 0.7rem; font-weight: 800; white-space: nowrap; background: #eef2f7; color: #475569; }
        .trace-badge.lulus, .trace-badge.disokong, .trace-badge.disahkan { background: #e6fffb; color: #0f766e; }
        .trace-badge.menunggu, .trace-badge.menunggu_pengesahan { background: #fff4e5; color: #9a5b00; }
        .trace-badge.ditolak { background: #fde8e8; color: #b42318; }
        
        .action-group { display: flex; align-items: center; justify-content: center; gap: 8px; flex-wrap: nowrap; white-space: nowrap; }
        .action-separator {
            width: 1px;
            height: 18px;
            background: #94a3b8;
            margin: 0;
            display: inline-block;
            flex-shrink: 0;
            align-self: center;
        }
        .btn-sm { 
            padding: 6px 12px; 
            font-size: 0.8rem; 
            border-radius: 6px; 
            text-decoration: none; 
            color: #fff; 
            display: inline-flex; 
            align-items: center; 
            justify-content: center;
            gap: 4px; 
            white-space: nowrap;
            min-width: 32px;
            transition: all 0.2s ease;
        }
        .btn-sm:hover { 
            transform: translateY(-1px); 
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        .btn-view { background: var(--primary); }
        .btn-edit { background: var(--warning); color: #1a1a1a; }
        .btn-folder { background: #0f766e; }
        .btn-delete { background: var(--danger); }
        
        .empty-state { text-align: center; padding: 48px 20px; color: var(--text-muted); }
        .empty-state i { font-size: 2.8rem; margin-bottom: 12px; opacity: 0.5; }
        .page-footer { text-align: center; padding: 20px; color: var(--text-muted); font-size: 0.8rem; margin-top: 30px; }

        @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; max-width: calc(100vw - 70px); }
            .sidebar-toggle { display: none; }
            .filter-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
            .filter-actions { grid-column: 1 / -1; justify-content: flex-end; }
        }
        @media (max-width: 640px) {
            .filter-grid { grid-template-columns: 1fr; }
            .filter-actions { justify-content: stretch; }
            .filter-actions .btn { flex: 0 0 40px; justify-content: center; }
        }
        .sidebar {
            overflow: hidden;
        }
        .sidebar-header {
            flex: 0 0 auto;
        }
        .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;
        }
    
        /* 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) ?> draft-module-page">
    <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, $sidebar_current_page); ?>
        </ul>
    </aside>

    <main class="main">
        <div class="top-bar">
            <h2><i class="fas fa-file-signature"></i> <?= htmlspecialchars($page_title) ?></h2>
            <?php renderTopBarUserMenu($conn, $role, 'draft_letters.php'); ?>
        </div>

        <?php
        renderBreadcrumb([
            ['label' => 'Dashboard', 'url' => 'dashboard.php'],
            ['label' => $page_title, 'url' => $is_draft_dashboard ? 'draft_dashboard.php' : 'draft_letters.php', 'current' => true]
        ]);
        ?>

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

        <?php if ($is_draft_dashboard): ?>
        <div class="hero-card">
            <div class="hero-header">
                <div>
                    <h3>Status Surat</h3>
                </div>
                <div class="hero-actions">
                    <?php if ($can_create_draft): ?>
                    <a href="draft_letter_form.php" class="btn btn-primary"><i class="fas fa-plus"></i> Sediakan Surat Baharu</a>
                    <?php endif; ?>
                    <a href="list_folder.php" class="btn btn-secondary"><i class="fas fa-folder-open"></i> Lihat Fail</a>
                </div>
            </div>
            <div class="stats-row">
                <div class="stat-box">
                    <i class="fas fa-file-signature"></i>
                    <h4><?= number_format($total_drafts) ?></h4>
                    <p>Jumlah Surat</p>
                </div>
                <div class="stat-box not-sent">
                    <i class="fas fa-file-circle-plus"></i>
                    <h4><?= number_format($total_not_sent) ?></h4>
                    <p>Belum Dihantar</p>
                </div>
                <div class="stat-box waiting">
                    <i class="fas fa-clock"></i>
                    <h4><?= number_format($total_waiting_action) ?></h4>
                    <p>Menunggu Tindakan</p>
                </div>
                <div class="stat-box approved">
                    <i class="fas fa-circle-check"></i>
                    <h4><?= number_format($total_approved) ?></h4>
                    <p>Lulus</p>
                </div>
                <div class="stat-box rejected">
                    <i class="fas fa-circle-xmark"></i>
                    <h4><?= number_format($total_rejected) ?></h4>
                    <p>Ditolak</p>
                </div>
            </div>
        </div>
        <div class="chart-card">
            <div class="chart-head">
                <h3>Status Surat</h3>
                <p>Ringkasan status keseluruhan surat dalam sistem.</p>
            </div>
            <div class="status-chart-wrap">
                <canvas id="statusSuratChart"></canvas>
            </div>
        </div>
        <?php endif; ?>

        <div class="table-card">
            <div class="table-head">
                <div>
                    <h3><?= $is_draft_dashboard ? ' Surat Terkini' : 'Senarai Surat' ?></h3>
                    <p>
                        <?php if ($is_draft_dashboard): ?>
                            Ringkasan 5 surat paling terkini daripada senarai utama.
                        <?php else: ?>
                            Senarai utama semua surat mengikut status semasa.
                        <?php endif; ?>
                    </p>
                </div>
            </div>
            <?php if (!$is_draft_dashboard): ?>
            <form class="filter-panel" method="GET" action="draft_letters.php">
                <div class="filter-grid">
                    <div class="filter-group">
                        <label>Kata Kunci Surat</label>
                        <input type="text" name="search" value="<?= htmlspecialchars($filter_search) ?>" placeholder="Cari no. rujukan, perkara atau nama fail">
                    </div>
                    <div class="filter-group">
                        <label>Tarikh Dari</label>
                        <input type="date" name="date_from" value="<?= htmlspecialchars($filter_date_from) ?>">
                    </div>
                    <div class="filter-group">
                        <label>Tarikh Hingga</label>
                        <input type="date" name="date_to" value="<?= htmlspecialchars($filter_date_to) ?>">
                    </div>
                    <div class="filter-group">
                        <label>Status</label>
                        <select name="status">
                            <option value="" <?= $filter_status === '' ? 'selected' : '' ?>>Semua</option>
                            <?php foreach ($approval_status_labels as $status_value => $status_text): ?>
                            <option value="<?= htmlspecialchars($status_value) ?>" <?= $filter_status === $status_value ? 'selected' : '' ?>>
                                <?= htmlspecialchars($status_text) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label>Daripada</label>
                        <input type="text" name="from" value="<?= htmlspecialchars($filter_from) ?>" placeholder="Bahagian / jawatan / nama">
                    </div>
                    <div class="filter-actions">
                        <button type="submit" class="btn btn-primary" title="Cari" aria-label="Cari"><i class="fas fa-search"></i></button>
                        <a href="draft_letters.php" class="btn btn-secondary" title="Reset" aria-label="Reset"><i class="fas fa-rotate-left"></i></a>
                    </div>
                </div>
            </form>
            <?php endif; ?>
            <div class="table-wrap">
                <table class="<?= $is_draft_dashboard ? 'dashboard-table' : 'result-table' ?>">
                    <thead>
                        <tr>
                            <th>Bil.</th>
                            <th>No. Rujukan</th>
                            <?php if (!$is_draft_dashboard): ?>
                            <th>Fail</th>
                            <?php endif; ?>
                            <th>Perkara</th>
                            <?php if (!$is_draft_dashboard): ?>
                            <th>Penerima</th>
                            <th>Daripada</th>
                            <th>Jenis Surat</th>
                            <?php endif; ?>
                            <th>Status</th>
                            <?php if (!$is_draft_dashboard): ?>
                            <th>Dokumen</th>
                            <th>Tarikh Ditolak</th>
                            <?php endif; ?>
                            <th>Tindakan</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($display_drafts)): ?>
                        <tr>
                            <td colspan="<?= $is_draft_dashboard ? 5 : 11 ?>" class="empty-state">
                                <i class="fas fa-file-signature"></i><br>
                                <?= $is_draft_dashboard ? 'Tiada surat direkodkan lagi.' : 'Tiada surat direkodkan.' ?>
                            </td>
                        </tr>
                        <?php else: ?>
                            <?php foreach ($display_drafts as $i => $draft): ?>
                            <?php
                            $recipient_display = trim((string) ($draft['recipient_organization'] ?? ''));
                            if (strcasecmp(trim((string) ($draft['doc_type'] ?? '')), 'Surat Rasmi') === 0) {
                                $recipient_display = 'Seperti tertulis dalam surat.';
                            }
                            if ($recipient_display === '') {
                                $recipient_display = trim((string) ($draft['recipient_name'] ?? '-'));
                            }
                            $status_key = $draft['status'] ?? 'draf';
                            $status_label = $draft_status_labels[$status_key] ?? ucfirst($status_key);
                            $support_key = $draft['approval_status'] ?? (($draft['support_status'] ?? 'tidak_perlu') === 'disokong' ? 'lulus' : ($draft['support_status'] ?? 'tidak_perlu'));
                            $support_label = $approval_status_labels[$support_key] ?? ($support_status_labels[$support_key] ?? ucfirst(str_replace('_', ' ', $support_key)));
                            $is_draft_creator = (int) ($draft['created_by'] ?? 0) === (int) ($_SESSION['user_id'] ?? 0);
                            $draft_same_department = isSameDepartmentDb($conn, $draft['department'] ?? '', $user_department);
                            $can_manage_this_draft = $is_draft_creator || ($role === 'superadmin' && $draft_same_department);
                            $can_edit_this_draft = $can_update_draft && $can_manage_this_draft && ($support_key !== 'lulus');
                            $routing_recipients = getLetterApprovalRecipients($conn, (int) $draft['id']);
                            $draft['_routing_recipients'] = $routing_recipients;
                            ?>
                            <tr>
                                <td><?= ($is_draft_dashboard ? 0 : (int) ($draft_pagination['offset'] ?? 0)) + $i + 1 ?></td>
                                <td>
                                    <span class="ref-pill"><?= htmlspecialchars(formatDraftLetterReferenceDisplay('', $draft['ref_no'] ?? '', $draft['file_numbering'] ?? '')) ?></span>
                                    <?php if ($is_draft_dashboard): ?>
                                    <div class="meta-line"><?= htmlspecialchars($draft['folder_code']) ?></div>
                                    <?php endif; ?>
                                </td>
                                <?php if (!$is_draft_dashboard): ?>
                                <td>
                                    <strong><?= htmlspecialchars($draft['folder_name'] ?: '-') ?></strong>
                                </td>
                                <?php endif; ?>
                                <td>
                                    <strong><?= htmlspecialchars($draft['subject_short']) ?></strong>
                                    <?php if ($is_draft_dashboard): ?>
                                    <div class="meta-line"><?= htmlspecialchars($draft['folder_name']) ?></div>
                                    <div class="meta-line"><?= date('d/m/Y', strtotime($draft['letter_date'])) ?> - <?= htmlspecialchars($draft['department']) ?></div>
                                    <?php endif; ?>
                                </td>
                                <?php if (!$is_draft_dashboard): ?>
                                <td>
                                    <?= nl2br(htmlspecialchars($recipient_display)) ?>
                                </td>
                                <td>
                                    <strong><?= htmlspecialchars(getDisplayPositionForDepartment(($draft['signatory_department'] ?? '') ?: ($draft['department'] ?? ''), $draft['signatory_position'] ?? '') ?: '-') ?></strong>
                                </td>
                                <td>
                                    <?= htmlspecialchars(trim((string) ($draft['doc_type'] ?? '')) ?: '-') ?>
                                </td>
                                <?php endif; ?>
                                <td>
                                    <?php if ($is_draft_dashboard): ?>
                                    <span class="support-pill <?= htmlspecialchars($support_key) ?>">
                                        <i class="fas fa-location-dot"></i>
                                        <?= htmlspecialchars($support_label) ?>
                                    </span>
                                    <?php else: ?>
                                    <span class="result-pill <?= htmlspecialchars($support_key) ?>">
                                        <i class="fas <?=
                                            $support_key === 'lulus'
                                                ? 'fa-circle-check'
                                                : ($support_key === 'ditolak' ? 'fa-circle-xmark' : 'fa-clock')
                                        ?>"></i>
                                        <?= htmlspecialchars($support_label) ?>
                                    </span>
                                    <?php endif; ?>
                                </td>
                                <?php if (!$is_draft_dashboard): ?>
                                <td>
                                    <?php if (!empty($draft['active_document_id'])): ?>
                                    <div><strong>Aktif</strong></div>
                                    <?php else: ?>
                                    <div class="inactive-doc">Tidak aktif</div>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?= $support_key === 'ditolak' ? htmlspecialchars(getDraftRejectedAt($draft) ?: '-') : '-' ?>
                                </td>
                                <?php endif; ?>
                                <td>
                                    <div class="action-group">
                                        <a href="draft_letter_print.php?id=<?= (int) $draft['id'] ?>" class="btn-sm btn-view" title="Papar surat" aria-label="Papar surat"><i class="fas fa-file-lines"></i></a>
                                        <?php if (!$is_draft_dashboard): ?>
                                            <?php if ($can_edit_this_draft): ?>
                                             <span class="action-separator"></span>
                                             <a href="draft_letter_form.php?id=<?= (int) $draft['id'] ?>" class="btn-sm btn-edit" title="Ubah surat" aria-label="Ubah surat"><i class="fas fa-edit"></i></a>
                                            <?php endif; ?>
                                            <?php if ($can_manage_this_draft): ?>
                                             <span class="action-separator"></span>
                                             <a href="view_folder.php?id=<?= (int) $draft['folder_id'] ?>" class="btn-sm btn-folder" title="Buka fail" aria-label="Buka fail"><i class="fas fa-folder-open"></i></a>
                                            <?php endif; ?>
                                            <?php if ($can_delete_draft && $can_manage_this_draft): ?>
                                             <span class="action-separator"></span>
                                             <a href="process_draft_letter.php?action=delete&id=<?= (int) $draft['id'] ?>" class="btn-sm btn-delete" onclick="return confirm('Padam surat ini? Surat akan masuk ke Data Dipadam dan tidak akan diterima atau dibuka oleh penerima lain.')" title="Padam surat" aria-label="Padam surat"><i class="fas fa-trash-alt"></i></a>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
                <?php if (!$is_draft_dashboard): ?>
                <?php renderPaginationControls($draft_pagination, 'surat'); ?>
                <?php endif; ?>
            </div>
        </div>

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

    <?php if ($is_draft_dashboard): ?>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"></script>
    <?php endif; ?>
    <script>
        <?php if ($is_draft_dashboard): ?>
        const statusSuratChartCanvas = document.getElementById('statusSuratChart');
        if (statusSuratChartCanvas && window.Chart) {
            const statusSuratLabels = <?= json_encode(array_keys($dashboard_status_chart), JSON_UNESCAPED_UNICODE) ?>;
            const statusSuratValues = <?= json_encode(array_values($dashboard_status_chart), JSON_NUMERIC_CHECK) ?>;
            const statusSuratValueLabels = {
                id: 'statusSuratValueLabels',
                afterDatasetsDraw(chart) {
                    const { ctx } = chart;
                    const meta = chart.getDatasetMeta(0);
                    ctx.save();
                    ctx.font = '700 12px ' + getComputedStyle(document.body).fontFamily;
                    ctx.fillStyle = '#163447';
                    ctx.textBaseline = 'middle';
                    meta.data.forEach((bar, index) => {
                        const value = chart.data.datasets[0].data[index] || 0;
                        const x = Math.min(bar.x + 8, chart.chartArea.right - 18);
                        ctx.fillText(value, x, bar.y);
                    });
                    ctx.restore();
                }
            };
            new Chart(statusSuratChartCanvas, {
                type: 'bar',
                data: {
                    labels: statusSuratLabels,
                    datasets: [{
                        data: statusSuratValues,
                        backgroundColor: ['#14b8a6', '#93c5fd', '#f59e0b', '#ef4444'],
                        borderRadius: 8,
                        borderSkipped: false,
                        barThickness: 28
                    }]
                },
                options: {
                    indexAxis: 'y',
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            callbacks: {
                                label(context) {
                                    return ' ' + context.parsed.x + ' surat';
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            beginAtZero: true,
                            ticks: { precision: 0, color: '#2d5367', font: { weight: 700 } },
                            grid: { color: 'rgba(0,119,182,0.10)' }
                        },
                        y: {
                            ticks: { color: '#023e5f', font: { weight: 800 } },
                            grid: { display: false }
                        }
                    }
                },
                plugins: [statusSuratValueLabels]
            });
        }
        <?php endif; ?>

        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?");
        }
    </script>
    <?php renderSessionTimeoutScript(); ?>
</body>
</html>
