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

// TAMBAH INI: Definisi variable $role untuk sidebar consistency
$role = $_SESSION['role'] ?? 'user';

if (!currentUserCan($conn, 'document', 'create')) {
    echo "<script>alert('Anda tidak mempunyai kebenaran untuk mendaftar dokumen.'); window.location='list_folder.php';</script>";
    exit();
}

$user_department = currentUserDepartment($conn);

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

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

if ($folder_id <= 0) {
    if (isset($_SESSION['user_id'])) {
        logActivity($conn, $_SESSION['user_id'], 'create_document_failed',
            "Open add document form failed: invalid folder_id value [$folder_id_raw]");
    }
    header("Location: list_folder.php?error=invalid_folder_id&folder_id=0&source=add_documents");
    exit();
}

$folder_sql = mysqli_prepare($conn, "SELECT id, folder_name, folder_code, department, folder_type, closed_at 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'], 'create_document_failed',
            "Open add document form failed: folder_id $folder_id not found");
    }
    header("Location: list_folder.php?error=folder_not_found&folder_id=$folder_id&source=add_documents");
    exit();
}

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

if (!empty($folder['closed_at'])) {
    echo "<script>alert('Fail ini telah ditutup. Dokumen baru tidak boleh ditambah.'); window.location='view_folder.php?id={$folder_id}';</script>";
    exit();
}

$folder_code = trim($folder['folder_code'] ?? '');
$folder_department = trim((string) ($folder['department'] ?? ''));
$folder_type = normalizeFolderType($folder['folder_type'] ?? 'office');
$is_private_folder = $folder_type === 'sendirian';
$generated_ref_no = generateNextDocumentReference($folder_code);
$generated_file_numbering = generateNextDocumentFileNumbering($conn, $folder_id);

// Guna senarai 12 bahagian standard sistem
$departments_list = getDepartmentList();
$memo_position_options = getMemoPositionOptions();
$folder_department_positions = getDepartmentPositions($folder_department);
$upload_from_position = getMemoDepartmentHeadPosition($folder_department);
if ($upload_from_position === '' && !empty($folder_department_positions)) {
    $upload_from_position = getDisplayPositionForDepartment($folder_department, $folder_department_positions[0]);
}
$document_types = getDocumentTypeList();
$error_message = '';
$form_mode = ($_GET['mode'] ?? '') === 'upload' ? 'upload' : 'add';
$is_upload_mode = $form_mode === 'upload';
$form_title = $is_upload_mode ? 'UPLOAD SURAT SEDIA ADA' : 'TAMBAH FAIL / SURAT BAHARU';
$form_intro = $is_upload_mode
    ? 'Muat naik surat yang telah wujud untuk direkodkan dalam sistem'
    : ($is_private_folder ? 'Masukkan maklumat dokumen dengan format bebas untuk fail personal' : 'Lengkapkan maklumat dokumen mengikut format rasmi');
$submit_label = $is_upload_mode ? 'Upload Surat Ke Fail' : 'Simpan Fail Ke Fail';

if (isset($_GET['error'])) {
    if ($_GET['error'] === 'missing_ref_no') {
        $error_message = 'Sila masukkan nombor rujukan untuk fail jenis personal.';
    } elseif ($_GET['error'] === 'duplicate_ref_no') {
        $error_message = 'Nombor rujukan ini sudah wujud dalam fail yang sama.';
    } elseif ($_GET['error'] === 'missing_department') {
        $error_message = 'Sila lengkapkan pilihan Daripada dan Kepada.';
    } elseif ($_GET['error'] === 'invalid_position') {
        $error_message = 'Sila pilih jawatan penerima yang sah.';
    } elseif ($_GET['error'] === 'system' && isset($_GET['msg'])) {
        $error_message = 'Ralat sistem: ' . urldecode((string) $_GET['msg']);
    }
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Daftar Fail Baru | 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;
            --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 - SAMA PERSIS DENGAN DASHBOARD.PHP */

        .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 Styles - Compact Card */
        .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: 650px; margin: 0 auto; }
        .form-header { text-align: center; margin-bottom: 25px; }
        .form-header img { width: 70px; margin-bottom: 10px; }
        .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); }
        .hint { font-size: 0.75rem; color: var(--text-muted); margin-top: 4px; }
        .form-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; }
        .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-primary { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; width: 100%; justify-content: center; }
        .btn:hover { opacity: 0.95; }
        .back-link { text-align: center; margin-top: 20px; font-size: 0.9rem; }
        .back-link a { color: var(--primary); text-decoration: none; }
        .back-link a:hover { text-decoration: underline; }
        
        /* Footer */
        .page-footer { text-align: center; padding: 20px; color: var(--text-muted); font-size: 0.8rem; margin-top: 30px; }

        :root {
            --primary: #0077b6;
            --primary-dark: #005f99;
            --secondary: #00b4d8;
            --deep-blue: #023e5f;
            --bg-light: rgba(245, 250, 253, 0.72);
            --bg-card: rgba(255,255,255,0.68);
            --text-main: #163447;
            --text-muted: #2d5367;
            --border: rgba(255,255,255,0.48);
            --sidebar-width: 280px;
            --glass: rgba(255,255,255,0.58);
            --glass-strong: rgba(255,255,255,0.76);
            --shadow-soft: 0 24px 70px rgba(2,62,95,0.16);
        }
        body {
            background:
                linear-gradient(135deg, rgba(245,250,253,0.90), rgba(222,246,252,0.76)),
                url('assets/auth-bg.png') center/cover no-repeat fixed;
            color: var(--text-main);
            overflow-x: hidden;
        }
        body::before {
            content: '';
            position: fixed;
            inset: 0;
            background:
                radial-gradient(circle at 18% 18%, rgba(0,180,216,0.22), transparent 28%),
                radial-gradient(circle at 86% 12%, rgba(0,119,182,0.18), transparent 28%),
                linear-gradient(120deg, rgba(255,255,255,0.28), rgba(255,255,255,0.08));
            pointer-events: none;
            z-index: 0;
        }
        body::after {
            content: '';
            position: fixed;
            width: 520px;
            height: 520px;
            right: -180px;
            bottom: -220px;
            background: rgba(0,180,216,0.18);
            filter: blur(8px);
            transform: rotate(18deg);
            border-radius: 42px;
            pointer-events: none;
            z-index: 0;
        }
        .sidebar {
            background: linear-gradient(180deg, rgba(2,62,95,0.94), rgba(0,119,182,0.84));
            border-right: 1px solid rgba(255,255,255,0.22);
            box-shadow: 18px 0 44px rgba(2,38,60,0.20);
            backdrop-filter: blur(18px) saturate(1.25);
            overflow: hidden;
        }
        .sidebar-header {
            flex: 0 0 auto;
            background: transparent !important;
            border-bottom: 1px solid rgba(255,255,255,0.16);
        }
        .sidebar-header img {
            width: 58px;
            filter: drop-shadow(0 8px 14px rgba(0,0,0,0.22));
        }
        .sidebar-header h3 { color: #fff; font-weight: 800; }
        .sidebar-header p { color: rgba(255,255,255,0.72); }
        .sidebar-menu {
            flex: 1 1 auto;
            min-height: 0;
            overflow-y: auto;
            overflow-x: hidden;
            padding-bottom: 0;
            overscroll-behavior: contain;
            scrollbar-width: thin;
            scrollbar-color: #8f8f8f transparent;
        }
        .sidebar-menu::-webkit-scrollbar { width: 10px; }
        .sidebar-menu::-webkit-scrollbar-track { background: transparent; }
        .sidebar-menu::-webkit-scrollbar-thumb {
            background: #8f8f8f;
            border-radius: 999px;
            border: 2px solid transparent;
            background-clip: content-box;
        }
        .sidebar-menu::-webkit-scrollbar-button {
            display: none;
            width: 0;
            height: 0;
        }
        .sidebar-section { color: rgba(255,255,255,0.58); font-weight: 800; }
        .sidebar-menu li a,
        .sidebar-menu .dropdown-toggle {
            color: rgba(255,255,255,0.88);
        }
        .sidebar-menu li a:hover,
        .sidebar-menu li a.active,
        .sidebar-menu .dropdown-toggle:hover,
        .sidebar-menu .dropdown-toggle.active {
            background: rgba(255,255,255,0.18);
            color: #fff;
            box-shadow: inset 0 0 0 1px rgba(255,255,255,0.18);
        }
        .sidebar-menu .dropdown-menu a { color: rgba(255,255,255,0.78); }
        .sidebar-menu .dropdown-menu a:hover,
        .sidebar-menu .dropdown-menu a.active {
            background: rgba(255,255,255,0.16);
            color: #fff;
        }
        .sidebar-toggle {
            right: 10px;
            top: 28px;
            width: 28px;
            height: 28px;
            background: rgba(255,255,255,0.18);
            border: 1px solid rgba(255,255,255,0.22);
            box-shadow: 0 8px 20px rgba(0,0,0,0.15);
        }
        .main {
            padding: 28px 32px;
            position: relative;
            z-index: 1;
        }
        .top-bar,
        .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(--primary-dark);
            font-weight: 800;
        }
        .form-card {
            border-radius: 22px;
            max-width: 760px;
        }
        .form-header img {
            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);
        }
        .btn {
            border-radius: 12px;
            font-weight: 800;
            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:hover {
            opacity: 0.96;
            transform: translateY(-1px);
        }
        .back-link a {
            color: var(--primary-dark);
            font-weight: 700;
        }
        .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; }
        }
    
        /* 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>MAINPP WORKSPACE</h3>
        </div>
        <ul class="sidebar-menu">
            <?php renderUnifiedSidebarMenu($conn, $role, 'add_documents.php'); ?>
        </ul>
    </aside>

    <!-- MAIN CONTENT -->
    <main class="main">
        <div class="top-bar">
            <h2><i class="fas fa-file-alt"></i> Daftar Fail Baru</h2>
            <?php renderTopBarUserMenu($conn, $role, 'add_documents.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' => $is_upload_mode ? 'Upload Surat' : 'Tambah Surat', 'url' => 'add_documents.php?folder_id=' . $folder_id . ($is_upload_mode ? '&mode=upload' : ''), 'current' => true]
        ]);
        ?>

        <!-- FORM CARD - Compact Design -->
        <div class="form-card">
            <div class="form-header">
                <img src="mainpp.png" alt="Logo MAINPP">
                <h1><?= htmlspecialchars($form_title) ?></h1>
                <p><?= htmlspecialchars($form_intro) ?></p>
            </div>

            <?php if ($error_message !== ''): ?>
            <div style="background:#f8d7da;color:#721c24;padding:12px 14px;border-radius:8px;margin-bottom:18px;border-left:4px solid var(--danger);">
                <?= htmlspecialchars($error_message) ?>
            </div>
            <?php endif; ?>
            
            <form id="documentForm" action="process_document.php?action=add" method="POST" enctype="multipart/form-data">
                <input type="hidden" name="folder_id" value="<?php echo $folder_id; ?>">
                <input type="hidden" name="mode" value="<?= htmlspecialchars($form_mode) ?>">
                
                <!-- No. Rujukan -->
                <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($_POST['ref_no'] ?? '') ?>" required>
                    <?php else: ?>
                        <input type="text" name="ref_no_preview" value="<?= htmlspecialchars(formatDraftLetterReferenceDisplay('', $generated_ref_no, $generated_file_numbering)) ?>" readonly>
                    <?php endif; ?>
                </div>
                
                <!-- Perkara -->
                <div class="form-group">
                    <label>Perkara <span style="color:var(--danger);">*</span></label>
                    <input type="text" name="subject" required>
                </div>
                
                <!-- Tarikh & Jenis Dokumen -->
                <div class="form-row">
                    <div class="form-group">
                        <label>Tarikh <span style="color:var(--danger);">*</span></label>
                        <input type="date" name="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="" disabled selected>-- Pilih Jenis --</option>
                            <?php foreach ($document_types as $document_type): ?>
                                <option value="<?= htmlspecialchars($document_type) ?>"><?= htmlspecialchars($document_type) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <!-- Daripada & Kepada -->
                <div class="form-row">
                    <div class="form-group">
                        <label>Daripada <span style="color:var(--danger);">*</span></label>
                        <?php if ($is_upload_mode): ?>
                        <input type="hidden" name="from_person" id="from_person" value="<?php echo htmlspecialchars($upload_from_position); ?>">
                        <input type="text" value="<?php echo htmlspecialchars($upload_from_position); ?>" readonly>
                        <?php else: ?>
                        <select name="from_person" id="from_person" required>
                            <option value="" disabled selected>-- Pilih Pengirim --</option>
                            <?php foreach ($departments_list as $dept): ?>
                                <option value="<?php echo htmlspecialchars($dept); ?>">
                                    <?php echo htmlspecialchars($dept); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <?php endif; ?>
                    </div>
                    <div class="form-group">
                        <label>Kepada <span style="color:var(--danger);">*</span></label>
                        <select name="to_person" id="to_person" required>
                            <option value="" disabled selected><?= $is_upload_mode ? '-- Pilih Jawatan Penerima --' : '-- Pilih Penerima --' ?></option>
                            <?php if ($is_upload_mode): ?>
                            <?php foreach ($memo_position_options as $group_label => $positions): ?>
                                <optgroup label="<?php echo htmlspecialchars($group_label); ?>">
                                    <?php foreach ($positions as $position): ?>
                                        <option value="<?php echo htmlspecialchars($position); ?>">
                                            <?php echo htmlspecialchars($position); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </optgroup>
                            <?php endforeach; ?>
                            <?php else: ?>
                            <?php foreach ($departments_list as $dept): ?>
                                <option value="<?php echo htmlspecialchars($dept); ?>">
                                    <?php echo htmlspecialchars($dept); ?>
                                </option>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                        <textarea name="to_person_text" id="to_person_text" style="display:none;" placeholder="Masukkan penerima surat rasmi" rows="3"></textarea>
                        <?php if (!$is_upload_mode): ?>
                        <div class="hint">Pilihan Daripada dan Kepada mestilah berbeza.</div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Melalui (Optional for Memo Kelulusan) -->
                <div class="form-group" id="melalui_group" style="display:none;">
                    <label>Melalui (Pilihan)</label>
                    <select name="melalui_person" id="melalui_person">
                        <option value="" disabled selected>-- Pilih Melalui --</option>
                        <option value="">Tiada Pilihan</option>
                        <?php foreach ($memo_position_options as $group_label => $positions): ?>
                            <optgroup label="<?php echo htmlspecialchars($group_label); ?>">
                                <?php foreach ($positions as $position): ?>
                                    <option value="<?php echo htmlspecialchars($position); ?>">
                                        <?php echo htmlspecialchars($position); ?>
                                    </option>
                                <?php endforeach; ?>
                            </optgroup>
                        <?php endforeach; ?>
                    </select>
                    <div class="hint">Pilihan untuk Memo Kelulusan sahaja.</div>
                </div>
                
                <!-- Lampiran Fail -->
                <div class="form-group">
                    <label>Lampiran Surat <?= $is_upload_mode ? '<span style="color:var(--danger);">*</span>' : '(Pilihan)' ?></label>
                    <input type="file" name="file_upload[]" accept=".pdf,.doc,.docx,.xls,.xlsx" <?= $is_upload_mode ? 'required' : '' ?> multiple>
                    <div class="hint">Boleh pilih lebih daripada satu fail. Format: PDF, DOC, XLS (maksimum 10MB setiap fail).</div>
                </div>
                
                <!-- DYNAMIC CUSTOM FIELDS (Akan muncul ikut setting Superadmin) -->
                <?php 
                // Render custom fields untuk module 'document'
                echo renderCustomFields($conn, 'document'); 
                ?>
                
                <!-- Action Buttons -->
                <button type="submit" class="btn btn-primary">
                    <i class="fas <?= $is_upload_mode ? 'fa-upload' : 'fa-save' ?>"></i> <?= htmlspecialchars($submit_label) ?>
                </button>
            </form>
            
            <div class="back-link">
                <a href="view_folder.php?id=<?php echo $folder_id; ?>"><i class="fas fa-arrow-left"></i> Kembali ke Fail</a>
            </div>
        </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?"); }

        const fromPersonSelect = document.getElementById('from_person');
        const toPersonSelect = document.getElementById('to_person');
        const toPersonText = document.getElementById('to_person_text');
        const melaluiGroup = document.getElementById('melalui_group');
        const documentForm = document.getElementById('documentForm');
        let isSubmittingDocument = false;

        // Handle document type changes
        const docTypeSelect = document.querySelector('select[name="doc_type"]');
        if (docTypeSelect) {
            docTypeSelect.addEventListener('change', function() {
                const docType = this.value.toLowerCase();
                
                // Show/hide melalui field for Memo Kelulusan
                if (docType === 'memo kelulusan') {
                    melaluiGroup.style.display = 'block';
                } else {
                    melaluiGroup.style.display = 'none';
                    document.getElementById('melalui_person').value = '';
                }
                
                // Change kepada field for Surat Rasmi
                if (docType === 'surat rasmi') {
                    toPersonSelect.style.display = 'none';
                    toPersonSelect.removeAttribute('required');
                    toPersonText.style.display = 'block';
                    toPersonText.setAttribute('required', 'required');
                } else {
                    toPersonSelect.style.display = 'block';
                    toPersonSelect.setAttribute('required', 'required');
                    toPersonText.style.display = 'none';
                    toPersonText.removeAttribute('required');
                    toPersonText.value = '';
                }
            });
        }

        function validateDepartmentsSelection(changedSelect) {
            if (!fromPersonSelect || !toPersonSelect) return true;
            if (fromPersonSelect.value && toPersonSelect.value && fromPersonSelect.value === toPersonSelect.value) {
                alert("Pilihan Daripada dan Kepada tidak boleh sama.");
                changedSelect.value = "";
                changedSelect.focus();
                return false;
            }
            return true;
        }

        if (fromPersonSelect && toPersonSelect) {
            fromPersonSelect.addEventListener('change', function() {
                validateDepartmentsSelection(fromPersonSelect);
            });
            toPersonSelect.addEventListener('change', function() {
                validateDepartmentsSelection(toPersonSelect);
            });
        }

        if (documentForm) {
            documentForm.addEventListener('submit', async function(e) {
                if (isSubmittingDocument) return;

                if (!validateDepartmentsSelection(toPersonSelect || fromPersonSelect)) {
                    e.preventDefault();
                    return;
                }

                e.preventDefault();

                const submitButton = documentForm.querySelector('button[type="submit"]');
                if (submitButton) {
                    submitButton.disabled = true;
                    submitButton.style.opacity = '0.7';
                    submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Menyemak Fail...';
                }

                try {
                    const response = await fetch('folder_status.php?folder_id=<?= $folder_id ?>', {
                        credentials: 'same-origin',
                        headers: { 'X-Requested-With': 'XMLHttpRequest' }
                    });
                    const data = await response.json();

                    if (!response.ok || !data.exists) {
                        alert(data.message || 'Fail ini tidak lagi wujud atau telah dipadam. Anda akan dibawa semula ke senarai fail.');
                        window.location.href = 'list_folder.php?error=folder_not_found&folder_id=<?= $folder_id ?>&source=pre_submit';
                        return;
                    }

                    if (data.closed) {
                        alert(data.message || 'Fail ini telah ditutup. Dokumen baru tidak boleh ditambah.');
                        window.location.href = 'view_folder.php?id=<?= $folder_id ?>';
                        return;
                    }

                    isSubmittingDocument = true;
                    documentForm.submit();
                } catch (error) {
                    console.warn('Semakan status fail gagal. Teruskan submit untuk pengesahan server.', error);
                    isSubmittingDocument = true;
                    documentForm.submit();
                } finally {
                    if (!isSubmittingDocument && submitButton) {
                        submitButton.disabled = false;
                        submitButton.style.opacity = '';
                        submitButton.innerHTML = '<i class="fas <?= $is_upload_mode ? 'fa-upload' : 'fa-save' ?>"></i> <?= addslashes($submit_label) ?>';
                    }
                }
            });
        }
    </script>
    <?php renderSessionTimeoutScript(); ?>
</body>
</html>

