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

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

if (!isset($_GET['id'], $_GET['folder_id'])) {
    header("Location: dashboard.php?error=invalid_request");
    exit();
}

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

if (!hasUserPermission($conn, $_SESSION['user_id'], 'document', 'update', $user_department)) {
    echo "<script>alert('Anda tidak mempunyai kebenaran untuk mengemaskini fail ini!'); window.history.back();</script>";
    exit();
}

$doc_sql = mysqli_prepare($conn, "SELECT * FROM documents WHERE id = ? AND folder_id = ? AND deleted_at IS NULL");
mysqli_stmt_bind_param($doc_sql, "ii", $doc_id, $folder_id);
mysqli_stmt_execute($doc_sql);
$doc = mysqli_fetch_assoc(mysqli_stmt_get_result($doc_sql));

if (!$doc) {
    echo "<script>alert('Dokumen tidak dijumpai!'); window.location='view_folder.php?id=$folder_id';</script>";
    exit();
}

$folder_sql = mysqli_prepare($conn, "SELECT folder_name, department, folder_type 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 ($role !== 'superadmin' && !isSameDepartmentDb($conn, $folder['department'] ?? '', $user_department)) {
    echo "<script>alert('Anda tidak mempunyai kebenaran untuk mengemaskini dokumen dalam bahagian lain.'); window.location='list_folder.php';</script>";
    exit();
}
$folder_type = normalizeFolderType($folder['folder_type'] ?? 'office');
$is_private_folder = $folder_type === 'sendirian';

$departments_list = getDepartmentList();
$document_types = getDocumentTypeList();
$can_download_document = currentUserCan($conn, 'document', 'download');
$linked_draft_map = getLetterDraftMapByDocumentIds($conn, [$doc_id]);
$linked_draft = $linked_draft_map[$doc_id] ?? null;
if (($linked_draft['approval_status'] ?? '') === 'lulus') {
    echo "<script>alert('Surat yang telah lulus tidak boleh diubah.'); window.location='view_folder.php?id=$folder_id';</script>";
    exit();
}
$status_message = '';
$status_type = '';

if (isset($_GET['success']) && $_GET['success'] === 'attachment_deleted') {
    $status_message = 'Attachment berjaya dipadam.';
    $status_type = 'success';
} elseif (isset($_GET['error'])) {
    if ($_GET['error'] === 'attachment_not_found') {
        $status_message = 'Attachment tidak dijumpai.';
        $status_type = 'error';
    } elseif ($_GET['error'] === 'attachment_delete_failed') {
        $status_message = 'Gagal memadam attachment.';
        $status_type = 'error';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_document'])) {
    $ref_no = trim($_POST['ref_no'] ?? '');
    $subject = trim($_POST['subject'] ?? '');
    $doc_date = trim($_POST['doc_date'] ?? '');
    $from_person = trim($_POST['from_person'] ?? '');
    $to_person = trim($_POST['to_person'] ?? '');
    $doc_type = trim($_POST['doc_type'] ?? '');
    $file_path = $doc['file_path'] ?? null;
    $file_numbering = $ref_no;
    $uploaded_files = normalizeUploadedFiles('file_upload');

    if (empty($ref_no) || empty($subject) || empty($doc_date) || empty($from_person) || empty($to_person)) {
        $error_msg = "Sila lengkapkan semua medan wajib!";
    } elseif ($from_person === $to_person) {
        $error_msg = "Pilihan Daripada dan Kepada tidak boleh sama!";
    } else {
        $check = mysqli_prepare($conn, "SELECT id FROM documents WHERE folder_id = ? AND ref_no = ? AND id != ? AND deleted_at IS NULL");
        mysqli_stmt_bind_param($check, "isi", $folder_id, $ref_no, $doc_id);
        mysqli_stmt_execute($check);
        mysqli_stmt_store_result($check);

        if (mysqli_stmt_num_rows($check) > 0) {
            $error_msg = "No. Rujukan ini sudah wujud dalam fail yang sama!";
        } elseif (!isset($error_msg)) {
            mysqli_begin_transaction($conn);

            try {
                $update = mysqli_prepare($conn, "UPDATE documents SET ref_no = ?, file_numbering = ?, subject = ?, doc_date = ?, from_person = ?, to_person = ?, doc_type = ?, file_path = ? WHERE id = ? AND deleted_at IS NULL");
                mysqli_stmt_bind_param($update, "ssssssssi", $ref_no, $file_numbering, $subject, $doc_date, $from_person, $to_person, $doc_type, $file_path, $doc_id);

                if (!mysqli_stmt_execute($update)) {
                    throw new Exception("Ralat sistem: " . mysqli_error($conn));
                }

                $attachment_result = saveDocumentAttachments($conn, $doc_id, $folder_id, $uploaded_files);
                if (empty($file_path) && !empty($attachment_result['first_path'])) {
                    $file_path = $attachment_result['first_path'];
                    $update_primary_file = mysqli_prepare($conn, "UPDATE documents SET file_path = ? WHERE id = ?");
                    mysqli_stmt_bind_param($update_primary_file, "si", $file_path, $doc_id);
                    mysqli_stmt_execute($update_primary_file);
                }

                if ($linked_draft) {
                    $draft_update = mysqli_prepare($conn, "UPDATE letter_drafts
                        SET ref_no = ?, letter_date = ?, subject = ?, doc_type = ?, recipient_organization = ?, signatory_department = ?, updated_by = ?, updated_at = CURRENT_TIMESTAMP
                        WHERE document_id = ? AND deleted_at IS NULL");
                    if ($draft_update) {
                        $current_user_id = (int) ($_SESSION['user_id'] ?? 0);
                        $folder_department = $folder['department'];
                        mysqli_stmt_bind_param($draft_update, "ssssssii", $ref_no, $doc_date, $subject, $doc_type, $to_person, $folder_department, $current_user_id, $doc_id);
                        mysqli_stmt_execute($draft_update);
                    }
                }

                saveCustomData($conn, 'document', $doc_id);
                mysqli_commit($conn);

                $attachment_info = !empty($attachment_result['count']) ? " | Attachment baru: {$attachment_result['count']}" : "";
                logActivity($conn, $_SESSION['user_id'], 'update_document', "Update document: $ref_no - $subject (ID: $doc_id)$attachment_info");
                echo "<script>alert('Maklumat fail berjaya dikemaskini!'); window.location='view_folder.php?id=$folder_id';</script>";
                exit();
            } catch (Exception $e) {
                mysqli_rollback($conn);
                $error_msg = $e->getMessage();
            }
        }
    }

    $doc['subject'] = $subject;
    $doc['doc_date'] = $doc_date;
    $doc['from_person'] = $from_person;
    $doc['to_person'] = $to_person;
    $doc['doc_type'] = $doc_type;
    $doc['file_path'] = $file_path;
}

$doc_attachment_map = getDocumentAttachmentsMap($conn, [$doc]);
$doc_attachments = $doc_attachment_map[$doc_id] ?? [];
$custom_data = loadCustomData($conn, 'document', $doc_id);
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ubah Fail | <?php echo htmlspecialchars($folder['folder_name']); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <?php renderAppShellAssets(); ?>
    <style>
        :root {
            --primary: #0077b6; --primary-dark: #005f99; --secondary: #00b4d8;
            --superadmin: #6c5ce7; --superadmin-dark: #5b4cdb;
            --bg-light: #f8fbfd; --bg-card: #ffffff; --text-main: #1a3a5c;
            --text-muted: #6c757d; --border: #e0e8f0; --sidebar-width: 240px;
            --success: #1a9955; --danger: #dc3545; --warning: #ffc107;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', 'Inter', Tahoma, Geneva, Verdana, sans-serif; }
        body { background: linear-gradient(135deg, #e0f7fa 0%, #f1f8e9 100%); min-height: 100vh; display: flex; color: var(--text-main); }

        .sidebar { width: var(--sidebar-width); background: linear-gradient(180deg, #fff 0%, #f8fbfd 100%); border-right: 1px solid var(--border); position: fixed; height: 100vh; padding: 20px 0; overflow-y: auto; overflow-x: hidden; z-index: 1000; box-shadow: 2px 0 10px rgba(0,0,0,0.03); transition: width 0.3s ease; display:flex; flex-direction:column; }
        .sidebar.collapsed { width: 70px; }
        .sidebar-header { text-align: center; padding: 0 20px 20px; border-bottom: 1px solid var(--border); margin-bottom: 20px; white-space: nowrap; overflow: hidden; }
        .sidebar.collapsed .sidebar-header h3, .sidebar.collapsed .sidebar-header p, .sidebar.collapsed .menu-text { display: none; }
        .sidebar-header img { width: 50px; margin-bottom: 10px; transition: margin 0.3s ease; }
        .sidebar.collapsed .sidebar-header img { margin: 0 auto 10px; }
        .sidebar-header h3 { font-size: 1rem; font-weight: 700; color: var(--primary); margin-bottom: 4px; }
        .sidebar-header p { font-size: 0.75rem; color: var(--text-muted); }
        .role-badge { display: inline-block; padding: 3px 10px; border-radius: 12px; font-size: 0.7rem; font-weight: 600; margin-left: 8px; }
        .role-badge.user { background: #e6f4ff; color: var(--primary); }
        .role-badge.admin { background: #d4edda; color: var(--success); }
        .role-badge.superadmin { background: linear-gradient(90deg, var(--superadmin), var(--superadmin-dark)); color: #fff; }
        .sidebar-menu { list-style: none; padding: 0 10px; display:flex; flex-direction:column; flex:1; }
        .sidebar-section { padding: 10px 18px 6px; color: var(--text-muted); font-size: 0.72rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; }
        .sidebar-spacer { margin-top: auto; }
        .sidebar-menu li a { display: flex; align-items: center; gap: 12px; padding: 12px 18px; color: var(--text-main); text-decoration: none; border-radius: 8px; margin-bottom: 4px; transition: all 0.2s ease; font-size: 0.9rem; white-space: nowrap; }
        .sidebar-menu li a:hover, .sidebar-menu li a.active { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; }
        .sidebar-menu li a i { width: 20px; text-align: center; font-size: 1.1rem; }
        .sidebar-menu .dropdown { position: relative; }
        .sidebar-menu .dropdown-toggle { display: flex; align-items: center; justify-content: space-between; width: 100%; padding: 12px 18px; color: var(--text-main); background: none; border: none; border-radius: 8px; cursor: pointer; font-size: 0.9rem; text-align: left; transition: all 0.2s ease; }
        .sidebar-menu .dropdown-toggle:hover, .sidebar-menu .dropdown-toggle.active { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; }
        .sidebar-menu .dropdown-toggle i.chevron { transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); font-size: 0.8rem; }
        .sidebar-menu .dropdown.active .dropdown-toggle i.chevron { transform: rotate(180deg); }
        .sidebar-menu .dropdown-menu { display: flex; flex-direction: column; padding-left: 42px; margin-top: 4px; max-height: 0; opacity: 0; overflow: hidden; transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.25s ease; }
        .sidebar-menu .dropdown.active .dropdown-menu { max-height: 260px; opacity: 1; }
        .sidebar-menu .dropdown-menu a { padding: 8px 18px; color: var(--text-main); text-decoration: none; border-radius: 6px; font-size: 0.85rem; display: flex; align-items: center; gap: 8px; opacity: 0; transform: translateY(-5px); transition: opacity 0.2s ease, transform 0.2s ease; }
        .sidebar-menu .dropdown.active .dropdown-menu a { opacity: 1; transform: translateY(0); }
        .sidebar-menu .dropdown-menu a:hover, .sidebar-menu .dropdown-menu a.active { background: #e6f4ff; color: var(--primary); }
        .sidebar.collapsed + .main { margin-left: 70px; }
        .sidebar-toggle { position: absolute; right: -12px; top: 20px; width: 24px; height: 24px; background: var(--primary); color: #fff; border: none; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 0.7rem; box-shadow: 0 2px 6px rgba(0,0,0,0.15); transition: transform 0.3s ease; z-index: 1001; }
        .sidebar.collapsed .sidebar-toggle { transform: rotate(180deg); }
        .main { margin-left: var(--sidebar-width); flex: 1; padding: 25px 30px; transition: margin-left 0.3s ease; }
        .top-bar { background: var(--bg-card); padding: 15px 25px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.04); margin-bottom: 25px; display: flex; justify-content: space-between; align-items: center; border: 1px solid var(--border); }
        .top-bar h2 { color: var(--primary); font-size: 1.3rem; font-weight: 600; display: flex; align-items: center; gap: 8px; }
        .user-info { display: flex; align-items: center; gap: 15px; font-size: 0.9rem; color: var(--text-muted); }
        .user-info span { color: var(--primary); font-weight: 600; }
        .user-info a { color: var(--danger); text-decoration: none; font-weight: 500; display: flex; align-items: center; gap: 5px; }
        .user-info a:hover { text-decoration: underline; }
        .form-card { background: var(--bg-card); border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.04); padding: 30px; border: 1px solid var(--border); max-width: 700px; margin: 0 auto; }
        .form-header { text-align: center; margin-bottom: 25px; }
        .form-header h1 { font-size: 1.3rem; color: var(--primary); margin-bottom: 5px; }
        .form-header p { color: var(--text-muted); font-size: 0.85rem; }
        .form-group { margin-bottom: 18px; }
        .form-group label { display: block; margin-bottom: 6px; color: var(--text-main); font-weight: 600; font-size: 0.9rem; }
        .form-group input, .form-group select, .form-group textarea { width: 100%; padding: 11px 14px; border: 1px solid var(--border); border-radius: 8px; font-size: 0.95rem; background: #fff; box-sizing: border-box; }
        .form-group input:focus, .form-group select:focus, .form-group textarea:focus { border-color: var(--primary); outline: none; box-shadow: 0 0 0 3px rgba(0,119,182,0.15); }
        .form-group input[readonly] { background: #f8f9fa; color: var(--text-muted); cursor: not-allowed; }
        .hint { font-size: 0.75rem; color: var(--text-muted); margin-top: 4px; }
        .current-file { background: var(--bg-light); border: 1px solid var(--border); border-radius: 8px; padding: 10px 12px; margin-top: 8px; }
        .current-file a { color: var(--primary); text-decoration: none; }
        .current-file a:hover { text-decoration: underline; }
        .attachment-list { display: flex; flex-direction: column; gap: 8px; margin-top: 8px; }
        .form-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; }
        .error-msg { background: #f8d7da; color: #721c24; padding: 12px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid var(--danger); }
        .success-msg { background: #d4edda; color: #155724; padding: 12px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid var(--success); }
        .btn { padding: 12px 22px; border: none; border-radius: 8px; cursor: pointer; font-size: 0.95rem; font-weight: 500; display: inline-flex; align-items: center; gap: 6px; }
        .btn:hover { opacity: 0.95; }
        .btn-primary { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; }
        .btn-secondary { background: #6c757d; color: #fff; }
        .btn-danger { background: var(--danger); color: #fff !important ; }
        .attachment-item { display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
        .attachment-meta { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
        .btn-sm { padding: 8px 14px; font-size: 0.85rem; border-radius: 6px; text-decoration: none; }
        .btn-group { display: flex; gap: 10px; margin-top: 25px; }
        .back-link { display: inline-block; margin-top: 20px; color: var(--primary); text-decoration: none; font-size: 0.9rem; }
        .back-link:hover { text-decoration: underline; }
        .page-footer { text-align: center; padding: 20px; color: var(--text-muted); font-size: 0.8rem; margin-top: 30px; }

        :root {
            --deep-blue: #023e5f;
            --bg-light: rgba(245, 250, 253, 0.72);
            --bg-card: rgba(255,255,255,0.68);
            --text-main: #163447;
            --text-muted: #2d5367;
            --border: rgba(255,255,255,0.48);
            --sidebar-width: 280px;
            --glass: rgba(255,255,255,0.58);
            --glass-strong: rgba(255,255,255,0.76);
            --shadow-soft: 0 24px 70px rgba(2,62,95,0.16);
        }
        body {
            background:
                linear-gradient(135deg, rgba(245,250,253,0.90), rgba(222,246,252,0.76)),
                url('assets/auth-bg.png') center/cover no-repeat fixed;
            color: var(--text-main);
            overflow-x: hidden;
        }
        body::before {
            content: '';
            position: fixed;
            inset: 0;
            background:
                radial-gradient(circle at 18% 18%, rgba(0,180,216,0.22), transparent 28%),
                radial-gradient(circle at 86% 12%, rgba(0,119,182,0.18), transparent 28%),
                linear-gradient(120deg, rgba(255,255,255,0.28), rgba(255,255,255,0.08));
            pointer-events: none;
            z-index: 0;
        }
        body::after {
            content: '';
            position: fixed;
            width: 520px;
            height: 520px;
            right: -180px;
            bottom: -220px;
            background: rgba(0,180,216,0.18);
            filter: blur(8px);
            transform: rotate(18deg);
            border-radius: 42px;
            pointer-events: none;
            z-index: 0;
        }
        .sidebar {
            background: linear-gradient(180deg, rgba(2,62,95,0.94), rgba(0,119,182,0.84));
            border-right: 1px solid rgba(255,255,255,0.22);
            box-shadow: 18px 0 44px rgba(2,38,60,0.20);
            backdrop-filter: blur(18px) saturate(1.25);
            overflow: hidden;
        }
        .sidebar-header {
            flex: 0 0 auto;
            background: transparent !important;
            border-bottom: 1px solid rgba(255,255,255,0.16);
        }
        .sidebar-header img {
            width: 58px;
            filter: drop-shadow(0 8px 14px rgba(0,0,0,0.22));
        }
        .sidebar-header h3 { color: #fff; font-weight: 800; }
        .sidebar-header p { color: rgba(255,255,255,0.72); }
        .sidebar-menu {
            flex: 1 1 auto;
            min-height: 0;
            overflow-y: auto;
            overflow-x: hidden;
            padding-bottom: 0;
            overscroll-behavior: contain;
            scrollbar-width: thin;
            scrollbar-color: #8f8f8f transparent;
        }
        .sidebar-menu::-webkit-scrollbar { width: 10px; }
        .sidebar-menu::-webkit-scrollbar-track { background: transparent; }
        .sidebar-menu::-webkit-scrollbar-thumb {
            background: #8f8f8f;
            border-radius: 999px;
            border: 2px solid transparent;
            background-clip: content-box;
        }
        .sidebar-menu::-webkit-scrollbar-button { display: none; width: 0; height: 0; }
        .sidebar-section { color: rgba(255,255,255,0.58); font-weight: 800; }
        .sidebar-menu li a,
        .sidebar-menu .dropdown-toggle { color: rgba(255,255,255,0.88); }
        .sidebar-menu li a:hover,
        .sidebar-menu li a.active,
        .sidebar-menu .dropdown-toggle:hover,
        .sidebar-menu .dropdown-toggle.active {
            background: rgba(255,255,255,0.18);
            color: #fff;
            box-shadow: inset 0 0 0 1px rgba(255,255,255,0.18);
        }
        .sidebar-menu .dropdown-menu a { color: rgba(255,255,255,0.78); }
        .sidebar-menu .dropdown-menu a:hover,
        .sidebar-menu .dropdown-menu a.active {
            background: rgba(255,255,255,0.16);
            color: #fff;
        }
        .sidebar-toggle {
            right: 10px;
            top: 28px;
            width: 28px;
            height: 28px;
            background: rgba(255,255,255,0.18);
            border: 1px solid rgba(255,255,255,0.22);
            box-shadow: 0 8px 20px rgba(0,0,0,0.15);
        }
        .main {
            padding: 28px 32px;
            position: relative;
            z-index: 1;
        }
        .top-bar,
        .form-card {
            background: var(--glass);
            border: 1px solid var(--border);
            box-shadow: var(--shadow-soft);
            backdrop-filter: blur(24px) saturate(1.35);
        }
        .top-bar {
            border-radius: 18px;
            padding: 16px 24px;
        }
        .top-bar h2,
        .form-header h1 {
            color: var(--deep-blue);
            font-weight: 800;
        }
        .form-card {
            border-radius: 22px;
            max-width: 760px;
        }
        .form-header img {
            width: 70px;
            margin-bottom: 10px;
            filter: drop-shadow(0 10px 18px rgba(0,119,182,0.18));
        }
        .form-group label {
            color: var(--deep-blue);
            font-weight: 700;
        }
        .form-group input,
        .form-group select,
        .form-group textarea {
            background: rgba(255,255,255,0.76);
            border-color: rgba(255,255,255,0.62);
            border-radius: 12px;
            color: var(--text-main);
        }
        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            border-color: rgba(0,180,216,0.82);
            box-shadow: 0 0 0 4px rgba(0,180,216,0.16);
        }
        .form-group input[readonly],
        .current-file {
            background: rgba(255,255,255,0.54);
            border-color: rgba(255,255,255,0.58);
        }
        .error-msg,
        .success-msg {
            border-radius: 12px;
            border-left-width: 4px;
        }
        .btn {
            border-radius: 12px;
            font-weight: 800;
            text-decoration: none;
            justify-content: center;
            transition: opacity 0.2s, transform 0.2s, box-shadow 0.2s;
        }
        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            box-shadow: 0 14px 28px rgba(0,119,182,0.18);
        }
        .btn-secondary {
            background: var(--glass-strong);
            color: var(--primary-dark);
            border: 1px solid var(--border);
        }
        .btn-danger {
            box-shadow: 0 12px 24px rgba(220,53,69,0.16);
        }
        .btn-group {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
            margin-top: 25px;
        }
        .btn:hover {
            opacity: 0.96;
            transform: translateY(-1px);
        }
        .page-footer { color: var(--text-muted); }

        @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; }
        }
        @media (max-width: 640px) {
            .main { padding: 22px 18px; }
            .top-bar { align-items: flex-start; flex-direction: column; gap: 12px; }
            .form-card { padding: 24px 20px; }
            .btn-group { grid-template-columns: 1fr; }
        }
    
        /* 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) ?>">
    <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, 'edit_document.php'); ?>
        </ul>
    </aside>

    <main class="main">
        <div class="top-bar">
            <h2><i class="fas fa-edit"></i> Ubah Maklumat Fail</h2>
            <?php renderTopBarUserMenu($conn, $role, 'edit_document.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],
            ['label' => 'Ubah Fail', 'url' => 'edit_document.php?id=' . $doc_id . '&folder_id=' . $folder_id, 'current' => true]
        ]);
        ?>

        <div class="form-card">
            <div class="form-header">
                <img src="mainpp.png" alt="Logo MAINPP">
                <h1>KEMASKINI FAIL</h1>
                <p>Fail: <strong><?= htmlspecialchars($folder['folder_name']) ?></strong></p>
                <p><?= $is_private_folder ? 'Fail personal membenarkan nombor rujukan diubah secara bebas.' : 'Fail office mengekalkan nombor rujukan ikut format rasmi sedia ada.' ?></p>
                <?php if ($linked_draft): ?>
                <p><a href="draft_letter_print.php?id=<?= (int) ($linked_draft['id'] ?? 0) ?>" style="color:var(--primary);font-weight:600;text-decoration:none;"><i class="fas fa-file-signature"></i> Semak surat berkaitan</a></p>
                <?php endif; ?>
            </div>

            <?php if (isset($error_msg)): ?>
            <div class="error-msg"><?= htmlspecialchars($error_msg) ?></div>
            <?php endif; ?>
            <?php if ($status_message): ?>
            <div class="<?= $status_type === 'success' ? 'success-msg' : 'error-msg' ?>"><?= htmlspecialchars($status_message) ?></div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="update_document" value="1">

                <div class="form-group">
                    <label>No. Rujukan <span style="color:var(--danger);">*</span></label>
                    <?php if ($is_private_folder): ?>
                        <input type="text" name="ref_no" value="<?= htmlspecialchars($doc['ref_no']) ?>" required>
                        <div class="hint">Fail personal membenarkan nombor rujukan dikemaskini secara bebas.</div>
                    <?php else: ?>
                        <input type="hidden" name="ref_no" value="<?= htmlspecialchars($doc['ref_no']) ?>">
                        <input type="text" value="<?= htmlspecialchars($doc['ref_no']) ?>" readonly>
                    <?php endif; ?>
                </div>

                <div class="form-group">
                    <label>Perkara <span style="color:var(--danger);">*</span></label>
                    <input type="text" name="subject" value="<?= htmlspecialchars($doc['subject']) ?>" required>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label>Tarikh <span style="color:var(--danger);">*</span></label>
                        <input type="date" name="doc_date" value="<?= htmlspecialchars($doc['doc_date']) ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Jenis Surat <span style="color:var(--danger);">*</span></label>
                        <select name="doc_type" required>
                            <option value="">-- Pilih Jenis --</option>
                            <?php foreach ($document_types as $document_type): ?>
                                <option value="<?= htmlspecialchars($document_type) ?>" <?= $doc['doc_type'] === $document_type ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($document_type) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label>Daripada <span style="color:var(--danger);">*</span></label>
                        <select name="from_person" id="from_person" required>
                            <option value="">-- Pilih Pengirim --</option>
                            <?php foreach ($departments_list as $dept): ?>
                                <option value="<?= htmlspecialchars($dept) ?>" <?= $doc['from_person'] === $dept ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($dept) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Kepada <span style="color:var(--danger);">*</span></label>
                        <select name="to_person" id="to_person" required>
                            <option value="">-- Pilih Penerima --</option>
                            <?php if ($doc['to_person'] !== '' && !in_array($doc['to_person'], $departments_list, true)): ?>
                                <option value="<?= htmlspecialchars($doc['to_person']) ?>" selected><?= htmlspecialchars($doc['to_person']) ?> (nilai semasa)</option>
                            <?php endif; ?>
                            <?php foreach ($departments_list as $dept): ?>
                                <option value="<?= htmlspecialchars($dept) ?>" <?= $doc['to_person'] === $dept ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($dept) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="hint">Pilihan Daripada dan Kepada mestilah berbeza.</div>
                    </div>
                </div>

                <div class="form-group">
                    <label>Lampiran Fail</label>
                    <input type="file" name="file_upload[]" accept=".pdf,.doc,.docx,.xls,.xlsx" multiple>
                    <div class="hint">Boleh tambah satu atau lebih fail baharu. Maksimum 10MB setiap fail.</div>
                    <?php if (!empty($doc_attachments)): ?>
                    <div class="attachment-list">
                        <?php foreach ($doc_attachments as $attachment): ?>
                        <div class="current-file attachment-item">
                            <div class="attachment-meta">
                                <strong>Lampiran:</strong>
                                <?php if ($can_download_document): ?>
                                <a href="download.php?attachment_id=<?= (int) ($attachment['id'] ?? 0) ?>" target="_blank"><?= htmlspecialchars($attachment['original_name'] ?: basename($attachment['file_path'])) ?></a>
                                <?php else: ?>
                                <span><?= htmlspecialchars($attachment['original_name'] ?: basename($attachment['file_path'])) ?> (tiada akses download)</span>
                                <?php endif; ?>
                            </div>
                            <?php if (!empty($attachment['id'])): ?>
                            <a href="process_document.php?action=delete_attachment&id=<?= $doc_id ?>&folder_id=<?= $folder_id ?>&attachment_id=<?= (int) $attachment['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Padam attachment ini?')">
                                <i class="fas fa-trash-alt"></i> Padam
                            </a>
                            <?php endif; ?>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php else: ?>
                    <div class="current-file">Tiada attachment sedia ada.</div>
                    <?php endif; ?>
                </div>

                <?php echo renderCustomFields($conn, 'document', $custom_data); ?>

                <div class="btn-group">
                    <button type="submit" class="btn btn-primary">
                        <i></i> Simpan Perubahan Fail
                    </button>
                    <a href="view_folder.php?id=<?= $folder_id ?>" class="btn btn-secondary">
                        <i></i> Batal
                    </a>
                </div>
            </form>

        </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>



