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

// DAPATKAN ROLE UNTUK SIDEBAR CONSISTENCY
$role = $_SESSION['role'] ?? 'user';
$user_department = currentUserDepartment($conn);

if (!currentUserCan($conn, 'folder', 'read') || !currentUserCan($conn, 'document', 'read')) {
    echo "<script>alert('Anda tidak mempunyai kebenaran untuk membuka fail ini.'); window.location='list_folder.php';</script>";
    exit();
}

if (!isset($_GET['id']) && !isset($_GET['folder_id'])) { header("Location: dashboard.php"); exit(); }

$folder_id_raw = $_GET['id'] ?? ($_GET['folder_id'] ?? '');
$folder_id = intval($folder_id_raw);

if ($folder_id <= 0) {
    if (isset($_SESSION['user_id'])) {
        logActivity($conn, $_SESSION['user_id'], 'view_folder_failed',
            "View fail failed: invalid fail id value [$folder_id_raw]");
    }
    header("Location: list_folder.php?error=invalid_folder_id&folder_id=0&source=view_folder");
    exit();
}

// Maklumat folder
$folder_sql = mysqli_prepare($conn, "SELECT * FROM folders WHERE id = ? AND deleted_at IS NULL");
mysqli_stmt_bind_param($folder_sql, "i", $folder_id);
mysqli_stmt_execute($folder_sql);
$folder = mysqli_fetch_assoc(mysqli_stmt_get_result($folder_sql));

if (!$folder) {
    if (isset($_SESSION['user_id'])) {
        logActivity($conn, $_SESSION['user_id'], 'view_folder_failed',
            "View fail failed: folder_id $folder_id not found");
    }
    header("Location: list_folder.php?error=folder_not_found&folder_id=$folder_id&source=view_folder");
    exit();
}

if ($role !== 'superadmin' && !isSameDepartmentDb($conn, $folder['department'] ?? '', $user_department)) {
    echo "<script>alert('Anda tidak mempunyai kebenaran untuk membuka fail bahagian lain.'); window.location='list_folder.php';</script>";
    exit();
}

// Senarai fail dalam fail. Surat yang dijana sistem hanya dipaparkan selepas lulus.
$doc_sql = mysqli_prepare($conn, "SELECT d.*
    FROM documents d
    LEFT JOIN letter_drafts ld ON ld.document_id = d.id AND ld.deleted_at IS NULL
    WHERE d.folder_id = ?
      AND d.deleted_at IS NULL
      AND (
          ld.id IS NULL
          OR ld.approval_status = 'lulus'
      )
    ORDER BY d.doc_date DESC");
$current_user_id = (int) ($_SESSION['user_id'] ?? 0);
mysqli_stmt_bind_param($doc_sql, "i", $folder_id);
mysqli_stmt_execute($doc_sql);
$documents = mysqli_fetch_all(mysqli_stmt_get_result($doc_sql), MYSQLI_ASSOC);
$document_attachments_map = getDocumentAttachmentsMap($conn, $documents);
$draft_letter_map = getLetterDraftMapByDocumentIds($conn, array_column($documents, 'id'));
$documents_pagination = paginateArrayItems($documents, 'page', 15);
$display_documents = $documents_pagination['items'];
$is_folder_closed = !empty($folder['closed_at']);
$folder_same_department = isSameDepartmentDb($conn, $folder['department'] ?? '', $user_department);
$can_create_document = $folder_same_department && !$is_folder_closed && hasUserPermission($conn, $_SESSION['user_id'], 'document', 'create', $user_department);
$can_create_letter = $folder_same_department && !$is_folder_closed && (currentUserCan($conn, 'draft_letter', 'create') || $can_create_document);
$can_download_document = currentUserCan($conn, 'document', 'download');
$can_read_draft_letter = currentUserCan($conn, 'draft_letter', 'read');

// Dropdown untuk "Daripada" & "Kepada" (ambil dari users)
$users_sql = mysqli_query($conn, "SELECT fullname, department FROM users ORDER BY fullname");
$users_list = mysqli_fetch_all($users_sql, MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($folder['folder_name']); ?> | Sistem Pengurusan Fail</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;
            --edit-color: #ffc107;
            --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: '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 - SAMA PERSIS DENGAN DASHBOARD.PHP */

        .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; 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: none; }
        
        /* Fail Info Box */
        .folder-info { background: var(--glass); padding: 20px 24px; border-radius: 22px; box-shadow: var(--shadow-soft); margin-bottom: 22px; border: 1px solid var(--border); border-left: 5px solid var(--secondary); backdrop-filter: blur(24px) saturate(1.25); -webkit-backdrop-filter: blur(24px) saturate(1.25); }
        .folder-info h3 { color: var(--primary-dark); margin-bottom: 10px; font-size: 1.12rem; font-weight: 850; }
        .folder-info h3 i { color: var(--secondary); }
        .folder-info p { color: var(--text-muted); font-size: 0.9rem; margin: 6px 0; font-weight: 650; }
        .folder-info strong { color: var(--text-main); }
        .folder-info code { background: #e6f4ff; padding: 3px 10px; border-radius: 999px; font-size: 0.85rem; color: var(--primary-dark); font-weight: 750; }
        
        /* Card & Table */
        .card { background: var(--glass); border-radius: 22px; box-shadow: var(--shadow-soft); padding: 22px; margin-bottom: 25px; border: 1px solid var(--border); backdrop-filter: blur(24px) saturate(1.25); -webkit-backdrop-filter: blur(24px) saturate(1.25); }
        .card-header { display: flex; justify-content: space-between; align-items: center; gap: 14px; margin-bottom: 18px; padding-bottom: 14px; border-bottom: 1px solid rgba(0,119,182,0.14); }
        .card-title { color: var(--primary-dark); font-size: 1.15rem; font-weight: 850; }
        .card-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; justify-content: flex-end; }
        .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: 7px; 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: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; }
        
        .table-responsive { overflow-x: auto; border-radius: 18px; border: 1px solid rgba(255,255,255,0.58); background: rgba(255,255,255,0.60); }
        table { width: 100%; border-collapse: collapse; font-size: 0.9rem; min-width: 980px; }
        table 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); }
        table td { padding: 14px 16px; border-bottom: 1px solid rgba(0,119,182,0.10); vertical-align: middle; text-align: left; background: rgba(255,255,255,0.66); }
        table td.empty-state { text-align: center; }
        table tr:hover td { background: rgba(231, 248, 252, 0.72); }
        .badge { padding: 5px 12px; border-radius: 999px; font-size: 0.8rem; font-weight: 700; display: inline-block; }
        .badge-blue { background: #e6f4ff; color: var(--primary-dark); }
        .badge-orange { background: #fff3cd; color: #856404; }
        .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; gap: 4px; white-space: nowrap; min-width: 32px; transition: all 0.2s ease; }
        .btn-view { background: var(--primary); }
        .btn-edit { background: var(--edit-color); color: #000; }
        .btn-delete { background: var(--danger); }
        .btn-disabled { background:#c8d3d9; cursor:not-allowed; opacity:0.78; }
        .status-closed { color: var(--danger); font-weight: 800; }
        .status-active { color: var(--success); font-weight: 800; }
        .empty-note { font-size:0.85rem; font-weight: 600; }
        .back-link a { color: var(--primary-dark); text-decoration: none; font-weight: 750; }
        
        .empty-state { text-align: center; padding: 40px 20px; color: var(--text-muted); }
        .empty-state i { font-size: 2.5rem; margin-bottom: 12px; opacity: 0.6; }
        .back-link { display: inline-block; margin-top: 20px; color: var(--primary); text-decoration: none; font-size: 0.9rem; }
        .back-link:hover, .back-link a:hover, .back-link a:focus { text-decoration: none; }
        .page-footer { text-align: center; padding: 20px; color: var(--text-muted); font-size: 0.8rem; margin-top: 30px; }
        
        /* Element visibility by role */
        .admin-only, .superadmin-only { display: none; }
        body.role-admin .admin-only,
        body.role-superadmin .admin-only,
        body.role-superadmin .superadmin-only { display: block; }

        @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; }
            .sidebar-toggle { display: none; }
        }
        .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) ?>">

    <!-- SIDEBAR - SAMA PERSIS DENGAN DASHBOARD.PHP -->
    <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>SISTEM PENGURUSAN FAIL</h3>
            <p>Jabatan Teknologi Maklumat</p>
        </div>
        <ul class="sidebar-menu">
            <?php renderUnifiedSidebarMenu($conn, $role, 'view_folder.php'); ?>
        </ul>
    </aside>

    <!-- MAIN CONTENT -->
    <main class="main">
        <div class="top-bar">
            <h2><i class="fas fa-folder-open"></i> <?php echo htmlspecialchars($folder['folder_name']); ?></h2>
            <?php renderTopBarUserMenu($conn, $role, 'view_folder.php'); ?>
        </div>

        <?php
        renderBreadcrumb([
            ['label' => 'Dashboard', 'url' => 'dashboard.php'],
            ['label' => 'Senarai Fail', 'url' => 'list_folder.php'],
            ['label' => $folder['folder_name'], 'url' => 'view_folder.php?id=' . $folder_id, 'current' => true]
        ]);
        ?>

        <!-- Maklumat Fail -->
        <div class="folder-info">
            <h3><i class="fas fa-info-circle"></i> Maklumat Fail</h3>
            <p><strong>Kod ID:</strong> <code><?php echo htmlspecialchars($folder['folder_code']); ?></code></p>
            <p><strong>Jenis Fail:</strong> <?php echo htmlspecialchars(getFolderTypeLabel($folder['folder_type'] ?? 'office')); ?></p>
            <p><strong>Status:</strong> <?php echo $is_folder_closed ? '<span class="status-closed">Ditutup</span>' : '<span class="status-active">Aktif</span>'; ?></p>
            <p><strong>Dicipta pada:</strong> <?php echo date('d/m/Y H:i', strtotime($folder['created_at'])); ?></p>
            <?php if ($is_folder_closed): ?>
            <p><strong>Ditutup pada:</strong> <?php echo date('d/m/Y H:i', strtotime($folder['closed_at'])); ?></p>
            <?php endif; ?>
        </div>

        <!-- Senarai Fail -->
        <div class="card">
            <div class="card-header">
                <div class="card-title"> Senarai Surat Lulus</div>
                <div class="card-actions">
                    <?php if ($can_create_document): ?>
                    <a href="add_documents.php?folder_id=<?php echo $folder_id; ?>&mode=upload" class="btn btn-secondary">
                        <i class="fas fa-upload"></i> Upload Surat
                    </a>
                    <?php endif; ?>
                    <?php if ($can_create_letter): ?>
                    <?php $add_letter_url = "draft_letter_form.php?folder_id={$folder_id}"; ?>
                    <a href="<?php echo htmlspecialchars($add_letter_url); ?>" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Tambah Surat Baharu
                    </a>
                    <?php elseif ($is_folder_closed): ?>
                    <span class="btn btn-primary btn-disabled"><i class="fas fa-lock"></i> Fail Ditutup</span>
                    <?php endif; ?>
                </div>
            </div>

            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>Bil.</th>
                            <th>No. Rujukan</th>
                            <th>Perkara</th>
                            <th>Tarikh</th>
                            <th>Daripada</th>
                            <th>Kepada</th>
                            <th>Jenis</th>
                            <th>Tindakan</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($display_documents)): ?>
                            <tr><td colspan="8" class="empty-state"><i class="fas fa-folder-open"></i><br>Tiada fail dalam fail ini.<br><small class="empty-note">Sila daftar fail baru untuk mula mengurus dokumen.</small></td></tr>
                        <?php else: ?>
                            <?php foreach ($display_documents as $document_index => $doc): 
                                // Check permission untuk button Edit & Delete
                                $can_delete = $folder_same_department && hasUserPermission($conn, $_SESSION['user_id'], 'document', 'delete', $user_department);
                                $doc_attachments = $document_attachments_map[$doc['id']] ?? [];
                                $linked_draft = $draft_letter_map[(int) ($doc['id'] ?? 0)] ?? null;
                                $linked_draft_is_approved = ($linked_draft['approval_status'] ?? '') === 'lulus';
                                $can_edit = $folder_same_department
                                    && hasUserPermission($conn, $_SESSION['user_id'], 'document', 'update', $user_department)
                                    && !$linked_draft_is_approved;
                                $subject_words = preg_split('/\s+/', trim((string) ($doc['subject'] ?? '')), -1, PREG_SPLIT_NO_EMPTY);
                                $subject_display = count($subject_words) > 5
                                    ? implode(' ', array_slice($subject_words, 0, 5)) . '...'
                                    : implode(' ', $subject_words);
                                $available_attachments = array_values(array_filter($doc_attachments, function ($attachment) {
                                    return !empty($attachment['file_path']) && file_exists($attachment['file_path']);
                                }));
                            ?>
                            <tr>
                                <td><?= (int) $documents_pagination['offset'] + $document_index + 1 ?></td>
                                <td><span class="badge badge-blue"><?php echo htmlspecialchars(formatDraftLetterReferenceDisplay('', $doc['ref_no'] ?? '', $doc['file_numbering'] ?? '')); ?></span></td>
                                <td><?php echo htmlspecialchars($subject_display); ?></td>
                                <td><?php echo date('d/m/Y', strtotime($doc['doc_date'])); ?></td>
                                <td><?php echo htmlspecialchars($doc['from_person']); ?></td>
                                <td><?php echo htmlspecialchars(strcasecmp(trim((string) (($linked_draft['doc_type'] ?? '') ?: ($doc['doc_type'] ?? ''))), 'Surat Rasmi') === 0 ? 'Seperti tertulis dalam surat.' : ($doc['to_person'] ?? '')); ?></td>
                                <td><span class="badge badge-orange"><?php echo htmlspecialchars($doc['doc_type']); ?></span></td>
                                <td>
                                    <div class="action-group">
                                    <!-- Paparan surat atau lampiran -->
                                    <?php if ($linked_draft && $can_read_draft_letter): ?>
                                    <a href="draft_letter_print.php?id=<?= (int) ($linked_draft['id'] ?? 0) ?>"
                                       class="btn-sm btn-view"
                                       title="Papar surat dan lampiran"
                                       aria-label="Papar surat dan lampiran">
                                       <i class="fas fa-file-lines"></i>
                                    </a>
                                    <?php elseif (!empty($available_attachments) && $can_download_document): ?>
                                    <?php $primary_attachment = $available_attachments[0]; ?>
                                    <a href="download.php?attachment_id=<?= (int) ($primary_attachment['id'] ?? 0) ?>"
                                       class="btn-sm btn-view"
                                       target="_blank"
                                       title="<?= htmlspecialchars($primary_attachment['original_name'] ?: basename($primary_attachment['file_path'])) ?>"
                                       aria-label="Papar lampiran">
                                       <i class="fas fa-file-lines"></i>
                                    </a>
                                    <?php elseif (!$can_download_document): ?>
                                        <span class="btn-sm btn-disabled" title="Tiada kebenaran download fail">
                                            <i class="fas fa-lock"></i>
                                        </span>
                                    <?php else: ?>
                                        <span class="btn-sm btn-disabled" title="Tiada fail dilampirkan">
                                            <i class="fas fa-file-lines"></i>
                                        </span>
                                    <?php endif; ?>
                                    
                                    <?php if ($can_edit || $can_delete): ?>
                                    <div class="action-separator"></div>
                                    <?php endif; ?>

                                    <!-- Button Edit (Hanya jika ada permission) -->
                                    <?php if ($can_edit): ?>
                                    <a href="edit_document.php?id=<?php echo $doc['id']; ?>&folder_id=<?php echo $folder_id; ?>" 
                                       class="btn-sm btn-edit"
                                       title="Ubah maklumat fail">
                                       <i class="fas fa-edit"></i>
                                    </a>
                                    <?php endif; ?>

                                    <?php if ($can_delete && $can_edit): ?>
                                    <div class="action-separator"></div>
                                    <?php endif; ?>

                                    <!-- Button Padam (Hanya jika ada permission) -->
                                    <?php if ($can_delete): ?>
                                    <a href="process_document.php?action=delete&id=<?php echo $doc['id']; ?>&folder_id=<?php echo $folder_id; ?>" 
                                       class="btn-sm btn-delete"
                                       onclick="return confirm('Adakah anda pasti mahu memadam fail ini?\\n\\nTindakan ini akan direkod dalam log sistem.')">
                                       <i class="fas fa-trash-alt"></i>
                                    </a>
                                    <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
                <?php renderPaginationControls($documents_pagination, 'surat'); ?>
            </div>
        </div>

        <div class="back-link">
            <a href="list_folder.php"><i class="fas fa-arrow-left"></i> Kembali ke Senarai Fail</a>
        </div>

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

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

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