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

$role = $_SESSION['role'] ?? 'user';
$user_department = currentUserDepartment($conn);
if (!currentUserCan($conn, 'deleted_item', 'read')) {
    echo "<script>alert('Anda tidak mempunyai kebenaran untuk melihat data dipadam.'); window.location='dashboard.php';</script>";
    exit();
}
$can_restore_deleted_items = currentUserCan($conn, 'deleted_item', 'restore');
$can_permanent_delete_deleted_items = $can_restore_deleted_items;
$deleted_item_sort_columns = [
    'folders' => [
        'folder' => ['label' => 'Fail', 'type' => 'text'],
        'department' => ['label' => 'Bahagian', 'type' => 'text'],
        'deleted_at' => ['label' => 'Dipadam Pada', 'type' => 'date'],
        'deleted_by' => ['label' => 'Dipadam Oleh', 'type' => 'text'],
    ],
    'drafts' => [
        'letter' => ['label' => 'Surat', 'type' => 'text'],
        'folder' => ['label' => 'Fail / Dokumen', 'type' => 'text'],
        'record_status' => ['label' => 'Status Rekod', 'type' => 'text'],
        'deleted_at' => ['label' => 'Dipadam Pada', 'type' => 'date'],
        'deleted_by' => ['label' => 'Dipadam Oleh', 'type' => 'text'],
    ],
];
$deleted_item_sort_state = [
    'folders' => [
        'sort' => trim((string) ($_GET['folders_sort'] ?? '')),
        'dir' => strtolower(trim((string) ($_GET['folders_dir'] ?? ''))),
    ],
    'drafts' => [
        'sort' => trim((string) ($_GET['drafts_sort'] ?? '')),
        'dir' => strtolower(trim((string) ($_GET['drafts_dir'] ?? ''))),
    ],
];
foreach ($deleted_item_sort_state as $section_key => $state) {
    if (!isset($deleted_item_sort_columns[$section_key][$state['sort']])) {
        $deleted_item_sort_state[$section_key]['sort'] = '';
    }
    if (!in_array($state['dir'], ['asc', 'desc'], true)) {
        $deleted_item_sort_state[$section_key]['dir'] = 'asc';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'permanent_delete') {
    $delete_type = trim((string) ($_POST['type'] ?? ''));
    $delete_id = (int) ($_POST['id'] ?? 0);

    if (!$can_permanent_delete_deleted_items) {
        header('Location: deleted_items.php?error=permanent_delete_denied');
        exit();
    }

    if ($delete_type === 'folder') {
        permanentDeleteDeletedFolder($conn, $delete_id, $role, $user_department);
    } elseif ($delete_type === 'draft') {
        permanentDeleteDeletedDraft($conn, $delete_id, $role, $user_department);
    }

    header('Location: deleted_items.php?error=permanent_delete_failed');
    exit();
}

if ($role === 'superadmin') {
    $deleted_folders_sql = "SELECT f.*, u.fullname AS deleted_by_name
        FROM folders f
        LEFT JOIN users u ON f.deleted_by = u.id
        WHERE f.deleted_at IS NOT NULL
        ORDER BY f.deleted_at DESC, f.id DESC";
    $deleted_folders = mysqli_fetch_all(mysqli_query($conn, $deleted_folders_sql), MYSQLI_ASSOC);

    $deleted_drafts_sql = "SELECT ld.*, f.folder_name, f.folder_code, f.deleted_at AS folder_deleted_at, d.file_numbering, d.deleted_at AS document_deleted_at, u.fullname AS deleted_by_name
        FROM letter_drafts ld
        LEFT JOIN folders f ON ld.folder_id = f.id
        LEFT JOIN documents d ON ld.document_id = d.id
        LEFT JOIN users u ON ld.deleted_by = u.id
        WHERE ld.deleted_at IS NOT NULL
        ORDER BY ld.deleted_at DESC, ld.id DESC";
    $deleted_drafts = mysqli_fetch_all(mysqli_query($conn, $deleted_drafts_sql), MYSQLI_ASSOC);
} else {
    $folder_stmt = mysqli_prepare($conn, "SELECT f.*, u.fullname AS deleted_by_name
        FROM folders f
        LEFT JOIN users u ON f.deleted_by = u.id
        WHERE f.deleted_at IS NOT NULL AND f.department = ?
        ORDER BY f.deleted_at DESC, f.id DESC");
    mysqli_stmt_bind_param($folder_stmt, "s", $user_department);
    mysqli_stmt_execute($folder_stmt);
    $deleted_folders = mysqli_fetch_all(mysqli_stmt_get_result($folder_stmt), MYSQLI_ASSOC);

    $draft_stmt = mysqli_prepare($conn, "SELECT ld.*, f.folder_name, f.folder_code, f.deleted_at AS folder_deleted_at, d.file_numbering, d.deleted_at AS document_deleted_at, u.fullname AS deleted_by_name
        FROM letter_drafts ld
        LEFT JOIN folders f ON ld.folder_id = f.id
        LEFT JOIN documents d ON ld.document_id = d.id
        LEFT JOIN users u ON ld.deleted_by = u.id
        WHERE ld.deleted_at IS NOT NULL AND ld.department = ?
        ORDER BY ld.deleted_at DESC, ld.id DESC");
    mysqli_stmt_bind_param($draft_stmt, "s", $user_department);
    mysqli_stmt_execute($draft_stmt);
    $deleted_drafts = mysqli_fetch_all(mysqli_stmt_get_result($draft_stmt), MYSQLI_ASSOC);
}
foreach ($deleted_folders as $index => &$folder_row) {
    $folder_row['_default_order'] = $index;
}
unset($folder_row);
foreach ($deleted_drafts as $index => &$draft_row) {
    $draft_row['_default_order'] = $index;
}
unset($draft_row);

sortDeletedItems($deleted_folders, 'folders', $deleted_item_sort_state['folders']['sort'], $deleted_item_sort_state['folders']['dir'], $deleted_item_sort_columns);
sortDeletedItems($deleted_drafts, 'drafts', $deleted_item_sort_state['drafts']['sort'], $deleted_item_sort_state['drafts']['dir'], $deleted_item_sort_columns);

$deleted_folders_pagination = paginateArrayItems($deleted_folders, 'folders_page', 15);
$display_deleted_folders = $deleted_folders_pagination['items'];
$deleted_drafts_pagination = paginateArrayItems($deleted_drafts, 'drafts_page', 15);
$display_deleted_drafts = $deleted_drafts_pagination['items'];

$message_map = [
    'folder_restored' => ['type' => 'success', 'text' => 'Fail berjaya dipulihkan semula.'],
    'draft_restored' => ['type' => 'success', 'text' => 'Surat berjaya dipulihkan semula.'],
    'restore_failed' => ['type' => 'error', 'text' => 'Pemulihan gagal. Sila cuba semula.'],
    'restore_folder_first' => ['type' => 'error', 'text' => 'Pulihkan fail asal terlebih dahulu sebelum memulihkan surat ini.'],
    'folder_missing' => ['type' => 'error', 'text' => 'Surat tidak boleh dipulihkan kerana fail asalnya sudah tiada dalam sistem.'],
    'duplicate_ref_conflict' => ['type' => 'error', 'text' => 'Surat tidak boleh dipulihkan kerana nombor rujukan itu sudah digunakan oleh rekod aktif lain.'],
    'document_not_found' => ['type' => 'error', 'text' => 'Surat dipadam tidak dijumpai.'],
    'draft_not_found' => ['type' => 'error', 'text' => 'Surat dipadam tidak dijumpai.'],
    'folder_permanently_deleted' => ['type' => 'success', 'text' => 'Fail berjaya dipadam secara kekal.'],
    'draft_permanently_deleted' => ['type' => 'success', 'text' => 'Surat berjaya dipadam secara kekal.'],
    'permanent_delete_denied' => ['type' => 'error', 'text' => 'Anda tidak mempunyai kebenaran untuk memadam data secara kekal.'],
    'permanent_delete_failed' => ['type' => 'error', 'text' => 'Padam kekal gagal. Sila cuba semula.'],
    'permanent_delete_active_child' => ['type' => 'error', 'text' => 'Rekod ini tidak boleh dipadam kekal kerana masih mempunyai rekod aktif yang berkaitan.'],
];

$message = null;
if (!empty($_GET['success']) && isset($message_map[$_GET['success']])) {
    $message = $message_map[$_GET['success']];
}
if (!empty($_GET['error']) && isset($message_map[$_GET['error']])) {
    $message = $message_map[$_GET['error']];
}

function getDeletedItemSortValue($row, $section_key, $column) {
    if ($section_key === 'folders') {
        switch ($column) {
            case 'folder':
                return trim((string) (($row['folder_name'] ?? '') . ' ' . ($row['folder_code'] ?? '')));
            case 'department':
                return $row['department'] ?? '';
            case 'deleted_at':
                return strtotime((string) ($row['deleted_at'] ?? '')) ?: 0;
            case 'deleted_by':
                return ($row['deleted_by_name'] ?? '') ?: 'Tidak diketahui';
            default:
                return '';
        }
    }

    switch ($column) {
        case 'letter':
            return trim((string) (($row['subject'] ?? '') . ' ' . formatDraftLetterReferenceDisplay('', $row['ref_no'] ?? '', $row['file_numbering'] ?? '') . ' ' . ($row['doc_type'] ?? '') . ' ' . ($row['status'] ?? '')));
        case 'folder':
            return trim((string) (($row['folder_name'] ?? '') . ' ' . ($row['folder_code'] ?? '')));
        case 'record_status':
            return !empty($row['document_deleted_at']) ? 'Dokumen asal dipadam' : 'Dokumen asal aktif';
        case 'deleted_at':
            return strtotime((string) ($row['deleted_at'] ?? '')) ?: 0;
        case 'deleted_by':
            return ($row['deleted_by_name'] ?? '') ?: 'Tidak diketahui';
        default:
            return '';
    }
}

function sortDeletedItems(&$rows, $section_key, $sort_column, $sort_dir, $sort_columns) {
    if ($sort_column === '' || !isset($sort_columns[$section_key][$sort_column])) {
        return;
    }

    usort($rows, function ($row_a, $row_b) use ($section_key, $sort_column, $sort_dir, $sort_columns) {
        $sort_type = $sort_columns[$section_key][$sort_column]['type'] ?? 'text';
        $value_a = getDeletedItemSortValue($row_a, $section_key, $sort_column);
        $value_b = getDeletedItemSortValue($row_b, $section_key, $sort_column);

        if ($sort_type === 'date' || $sort_type === 'number') {
            $compare = ((float) $value_a) <=> ((float) $value_b);
        } else {
            $compare = strnatcasecmp((string) $value_a, (string) $value_b);
        }

        if ($compare === 0) {
            return ((int) ($row_a['_default_order'] ?? 0)) <=> ((int) ($row_b['_default_order'] ?? 0));
        }

        return $sort_dir === 'desc' ? -$compare : $compare;
    });
}

function buildDeletedItemSortUrl($section_key, $column, $current_sort, $current_dir) {
    $query = $_GET;
    unset($query[$section_key === 'folders' ? 'folders_page' : 'drafts_page']);
    $sort_param = $section_key . '_sort';
    $dir_param = $section_key . '_dir';

    if ($current_sort !== $column) {
        $query[$sort_param] = $column;
        $query[$dir_param] = 'asc';
    } else {
        $query[$sort_param] = $column;
        $query[$dir_param] = $current_dir === 'asc' ? 'desc' : 'asc';
    }

    $base_path = basename((string) ($_SERVER['PHP_SELF'] ?? 'deleted_items.php'));
    $query_string = http_build_query($query);
    return htmlspecialchars($base_path . ($query_string !== '' ? '?' . $query_string : ''));
}

function renderDeletedItemSortableHeader($label, $section_key, $column, $current_sort, $current_dir) {
    $is_active = $current_sort === $column;
    $indicator = $is_active ? ($current_dir === 'desc' ? '&darr;' : '&uarr;') : '&#8597;';
    $aria_sort = $is_active ? ($current_dir === 'desc' ? 'descending' : 'ascending') : 'none';

    echo '<th aria-sort="' . htmlspecialchars($aria_sort) . '">';
    echo '<a class="sort-link' . ($is_active ? ' active' : '') . '" href="' . buildDeletedItemSortUrl($section_key, $column, $current_sort, $current_dir) . '">';
    echo '<span>' . htmlspecialchars($label) . '</span><span class="sort-indicator">' . $indicator . '</span>';
    echo '</a>';
    echo '</th>';
}

function redirectDeletedItems($type, $key) {
    header('Location: deleted_items.php?' . $type . '=' . urlencode($key));
    exit();
}

function fetchDeletedItemIds(mysqli $conn, string $sql, int $id): array {
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, 'i', $id);
    mysqli_stmt_execute($stmt);
    $rows = mysqli_fetch_all(mysqli_stmt_get_result($stmt), MYSQLI_ASSOC);
    return array_values(array_unique(array_map('intval', array_column($rows, 'id'))));
}

function fetchDeletedItemFilesForDocuments(mysqli $conn, array $document_ids): array {
    $document_ids = array_values(array_unique(array_filter(array_map('intval', $document_ids), fn($id) => $id > 0)));
    if (empty($document_ids)) {
        return [];
    }

    $id_list = implode(',', $document_ids);
    $files = [];

    $document_result = mysqli_query($conn, "SELECT id, file_path FROM documents WHERE id IN ($id_list)");
    while ($row = $document_result ? mysqli_fetch_assoc($document_result) : null) {
        $path = trim((string) ($row['file_path'] ?? ''));
        if ($path !== '') {
            $files[] = [
                'path' => $path,
                'document_id' => (int) ($row['id'] ?? 0),
                'attachment_id' => 0,
            ];
        }
    }

    $attachment_result = mysqli_query($conn, "SELECT id, document_id, file_path FROM document_attachments WHERE document_id IN ($id_list)");
    while ($row = $attachment_result ? mysqli_fetch_assoc($attachment_result) : null) {
        $path = trim((string) ($row['file_path'] ?? ''));
        if ($path !== '') {
            $files[] = [
                'path' => $path,
                'document_id' => (int) ($row['document_id'] ?? 0),
                'attachment_id' => (int) ($row['id'] ?? 0),
            ];
        }
    }

    return $files;
}

function deletedItemFileIsReferencedElsewhere(mysqli $conn, string $path, int $document_id, int $attachment_id): bool {
    $path = trim($path);
    if ($path === '') {
        return true;
    }

    $doc_stmt = mysqli_prepare($conn, "SELECT COUNT(*) AS total FROM documents WHERE file_path = ? AND id <> ?");
    mysqli_stmt_bind_param($doc_stmt, 'si', $path, $document_id);
    mysqli_stmt_execute($doc_stmt);
    $doc_count = (int) (mysqli_fetch_assoc(mysqli_stmt_get_result($doc_stmt))['total'] ?? 0);
    if ($doc_count > 0) {
        return true;
    }

    $attachment_stmt = mysqli_prepare($conn, "SELECT COUNT(*) AS total FROM document_attachments WHERE file_path = ? AND id <> ?");
    mysqli_stmt_bind_param($attachment_stmt, 'si', $path, $attachment_id);
    mysqli_stmt_execute($attachment_stmt);
    $attachment_count = (int) (mysqli_fetch_assoc(mysqli_stmt_get_result($attachment_stmt))['total'] ?? 0);

    return $attachment_count > 0;
}

function getSafeDeletedItemPhysicalFiles(mysqli $conn, array $file_rows): array {
    $paths = [];
    foreach ($file_rows as $file_row) {
        $path = trim((string) ($file_row['path'] ?? ''));
        if ($path === '') {
            continue;
        }
        if (deletedItemFileIsReferencedElsewhere(
            $conn,
            $path,
            (int) ($file_row['document_id'] ?? 0),
            (int) ($file_row['attachment_id'] ?? 0)
        )) {
            continue;
        }
        $paths[] = $path;
    }
    return array_values(array_unique($paths));
}

function deleteDeletedItemPhysicalFiles(array $paths): void {
    $allowed_root = realpath(__DIR__ . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'documents');
    if ($allowed_root === false) {
        return;
    }

    foreach ($paths as $path) {
        $path = trim((string) $path);
        if ($path === '') {
            continue;
        }

        $full_path = preg_match('/^[A-Za-z]:[\\\\\\/]/', $path)
            ? $path
            : __DIR__ . DIRECTORY_SEPARATOR . str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path);
        $real_path = realpath($full_path);

        if ($real_path === false || !is_file($real_path)) {
            continue;
        }
        if (strpos($real_path, $allowed_root . DIRECTORY_SEPARATOR) !== 0) {
            continue;
        }
        @unlink($real_path);
    }
}

function deleteDraftNotifications(mysqli $conn, array $draft_ids): void {
    foreach (array_values(array_unique(array_filter(array_map('intval', $draft_ids), fn($id) => $id > 0))) as $draft_id) {
        $entity_id = (string) $draft_id;
        $like_pattern = '%"draft_id":' . $draft_id . '%';
        $stmt = mysqli_prepare($conn, "DELETE FROM push_notifications WHERE entity_id = ? OR payload_json LIKE ?");
        mysqli_stmt_bind_param($stmt, 'ss', $entity_id, $like_pattern);
        mysqli_stmt_execute($stmt);
    }
}

function deleteRowsByIds(mysqli $conn, string $table, string $column, array $ids): void {
    $allowed = [
        'letter_approval_recipients' => ['draft_id'],
        'letter_drafts' => ['id'],
        'document_attachments' => ['document_id'],
        'documents' => ['id'],
    ];
    if (!isset($allowed[$table]) || !in_array($column, $allowed[$table], true)) {
        throw new Exception('permanent_delete_failed');
    }

    $ids = array_values(array_unique(array_filter(array_map('intval', $ids), fn($id) => $id > 0)));
    if (empty($ids)) {
        return;
    }

    $id_list = implode(',', $ids);
    if (!mysqli_query($conn, "DELETE FROM `$table` WHERE `$column` IN ($id_list)")) {
        throw new Exception(mysqli_error($conn));
    }
}

function permanentDeleteDeletedDraft(mysqli $conn, int $draft_id, string $role, string $user_department): void {
    if ($draft_id <= 0) {
        redirectDeletedItems('error', 'draft_not_found');
    }

    $stmt = mysqli_prepare($conn, "SELECT ld.id, ld.document_id, ld.ref_no, ld.subject, ld.department,
            d.id AS document_exists, d.deleted_at AS document_deleted_at
        FROM letter_drafts ld
        LEFT JOIN documents d ON d.id = ld.document_id
        WHERE ld.id = ? AND ld.deleted_at IS NOT NULL
        LIMIT 1");
    mysqli_stmt_bind_param($stmt, 'i', $draft_id);
    mysqli_stmt_execute($stmt);
    $draft = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));

    if (!$draft) {
        redirectDeletedItems('error', 'draft_not_found');
    }
    if ($role !== 'superadmin' && !isSameDepartmentDb($conn, $draft['department'] ?? '', $user_department)) {
        redirectDeletedItems('error', 'permanent_delete_denied');
    }

    $document_id = (int) ($draft['document_id'] ?? 0);
    $delete_document = $document_id > 0 && !empty($draft['document_deleted_at']);
    $document_ids = $delete_document ? [$document_id] : [];
    $physical_files = getSafeDeletedItemPhysicalFiles($conn, fetchDeletedItemFilesForDocuments($conn, $document_ids));

    mysqli_begin_transaction($conn);
    try {
        deleteRowsByIds($conn, 'letter_approval_recipients', 'draft_id', [$draft_id]);
        deleteDraftNotifications($conn, [$draft_id]);

        $draft_delete = mysqli_prepare($conn, "DELETE FROM letter_drafts WHERE id = ? AND deleted_at IS NOT NULL");
        mysqli_stmt_bind_param($draft_delete, 'i', $draft_id);
        if (!mysqli_stmt_execute($draft_delete) || mysqli_stmt_affected_rows($draft_delete) < 1) {
            throw new Exception('permanent_delete_failed');
        }

        if ($delete_document) {
            deleteRowsByIds($conn, 'document_attachments', 'document_id', $document_ids);
            deleteRowsByIds($conn, 'documents', 'id', $document_ids);
        }

        mysqli_commit($conn);
    } catch (Exception $e) {
        mysqli_rollback($conn);
        redirectDeletedItems('error', 'permanent_delete_failed');
    }

    deleteDeletedItemPhysicalFiles($physical_files);
    logActivity(
        $conn,
        (int) ($_SESSION['user_id'] ?? 0),
        'permanent_delete_draft_letter',
        "Padam kekal surat: {$draft['ref_no']} - {$draft['subject']} (Draft ID: {$draft_id})"
    );
    redirectDeletedItems('success', 'draft_permanently_deleted');
}

function permanentDeleteDeletedFolder(mysqli $conn, int $folder_id, string $role, string $user_department): void {
    if ($folder_id <= 0) {
        redirectDeletedItems('error', 'restore_failed');
    }

    $stmt = mysqli_prepare($conn, "SELECT id, folder_code, folder_name, department FROM folders WHERE id = ? AND deleted_at IS NOT NULL LIMIT 1");
    mysqli_stmt_bind_param($stmt, 'i', $folder_id);
    mysqli_stmt_execute($stmt);
    $folder = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));

    if (!$folder) {
        redirectDeletedItems('error', 'restore_failed');
    }
    if ($role !== 'superadmin' && !isSameDepartmentDb($conn, $folder['department'] ?? '', $user_department)) {
        redirectDeletedItems('error', 'permanent_delete_denied');
    }

    $active_docs_stmt = mysqli_prepare($conn, "SELECT COUNT(*) AS total FROM documents WHERE folder_id = ? AND deleted_at IS NULL");
    mysqli_stmt_bind_param($active_docs_stmt, 'i', $folder_id);
    mysqli_stmt_execute($active_docs_stmt);
    $active_docs = (int) (mysqli_fetch_assoc(mysqli_stmt_get_result($active_docs_stmt))['total'] ?? 0);

    $active_drafts_stmt = mysqli_prepare($conn, "SELECT COUNT(*) AS total FROM letter_drafts WHERE folder_id = ? AND deleted_at IS NULL");
    mysqli_stmt_bind_param($active_drafts_stmt, 'i', $folder_id);
    mysqli_stmt_execute($active_drafts_stmt);
    $active_drafts = (int) (mysqli_fetch_assoc(mysqli_stmt_get_result($active_drafts_stmt))['total'] ?? 0);

    if ($active_docs > 0 || $active_drafts > 0) {
        redirectDeletedItems('error', 'permanent_delete_active_child');
    }

    $draft_ids = fetchDeletedItemIds($conn, "SELECT id FROM letter_drafts WHERE folder_id = ? AND deleted_at IS NOT NULL", $folder_id);
    $document_ids = fetchDeletedItemIds($conn, "SELECT id FROM documents WHERE folder_id = ? AND deleted_at IS NOT NULL", $folder_id);
    $physical_files = getSafeDeletedItemPhysicalFiles($conn, fetchDeletedItemFilesForDocuments($conn, $document_ids));

    mysqli_begin_transaction($conn);
    try {
        deleteRowsByIds($conn, 'letter_approval_recipients', 'draft_id', $draft_ids);
        deleteDraftNotifications($conn, $draft_ids);
        deleteRowsByIds($conn, 'letter_drafts', 'id', $draft_ids);
        deleteRowsByIds($conn, 'document_attachments', 'document_id', $document_ids);
        deleteRowsByIds($conn, 'documents', 'id', $document_ids);

        $folder_delete = mysqli_prepare($conn, "DELETE FROM folders WHERE id = ? AND deleted_at IS NOT NULL");
        mysqli_stmt_bind_param($folder_delete, 'i', $folder_id);
        if (!mysqli_stmt_execute($folder_delete) || mysqli_stmt_affected_rows($folder_delete) < 1) {
            throw new Exception('permanent_delete_failed');
        }

        mysqli_commit($conn);
    } catch (Exception $e) {
        mysqli_rollback($conn);
        redirectDeletedItems('error', 'permanent_delete_failed');
    }

    deleteDeletedItemPhysicalFiles($physical_files);
    logActivity(
        $conn,
        (int) ($_SESSION['user_id'] ?? 0),
        'permanent_delete_folder',
        "Padam kekal fail: {$folder['folder_code']} - {$folder['folder_name']} (ID: {$folder_id})"
    );
    redirectDeletedItems('success', 'folder_permanently_deleted');
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data Dipadam | 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 { 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; }
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; margin-bottom: 25px; }
        .stat-card { background: var(--bg-card); padding: 20px; border-radius: 12px; border: 1px solid var(--border); box-shadow: 0 2px 10px rgba(0,0,0,0.04); }
        .stat-card h3 { font-size: 1.9rem; color: var(--primary); margin-bottom: 8px; }
        .stat-card p { color: var(--text-muted); font-size: 0.9rem; }
        .alert { padding: 14px 18px; border-radius: 10px; margin-bottom: 20px; border-left: 4px solid transparent; }
        .alert.success { background: #d4edda; color: #155724; border-left-color: var(--success); }
        .alert.error { background: #f8d7da; color: #721c24; border-left-color: var(--danger); }
        .card { background: var(--bg-card); border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.04); padding: 22px; margin-bottom: 25px; border: 1px solid var(--border); }
        .card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 18px; padding-bottom: 14px; border-bottom: 1px solid var(--border); }
        .card-title { color: var(--primary); font-size: 1.15rem; font-weight: 600; display: flex; align-items: center; gap: 8px; }
        .table-responsive { overflow-x: auto; }
        table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
        table th { background: #f8fafc; color: var(--primary); font-weight: 600; text-align: center; padding: 14px 16px; border-bottom: 2px solid var(--border); white-space: nowrap; }
        .sort-link { color: inherit; display: inline-flex; align-items: center; justify-content: center; gap: 6px; text-decoration: none; width: 100%; }
        .sort-link:hover, .sort-link.active { color: var(--primary-dark); }
        .sort-indicator { font-size: 0.78rem; line-height: 1; opacity: 0.82; }
        table td { padding: 14px 16px; border-bottom: 1px solid var(--border); vertical-align: top; text-align: left; }
        table td.empty-state { text-align: center; }
        table tr:hover { background: #f8fbfd; }
        .badge { padding: 5px 12px; border-radius: 20px; font-size: 0.78rem; font-weight: 500; display: inline-block; }
        .badge-folder { background: #e6f4ff; color: var(--primary); }
        .badge-document { background: #fff3cd; color: #856404; }
        .badge-warning { background: #ffe9cc; color: #8a5a00; }
        .badge-success { background: #d4edda; color: #155724; }
        .btn { padding: 9px 18px; border: none; border-radius: 8px; text-decoration: none; font-size: 0.88rem; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; font-weight: 500; }
        .btn:hover { opacity: 0.95; }
        .btn-restore { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; }
        .btn-permanent-delete { background: linear-gradient(90deg, #dc3545, #ef4444); color: #fff; }
        .btn-disabled { background: #d9dee4; color: #6c757d; cursor: not-allowed; }
        .action-group { display: flex; align-items: center; gap: 8px; flex-wrap: nowrap; white-space: nowrap; }
        .action-group form { margin: 0; display: inline-flex; }
        .action-group .btn {
            width: 40px;
            height: 40px;
            min-width: 40px;
            min-height: 40px;
            padding: 0;
            border-radius: 999px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 0;
            white-space: nowrap;
        }
        .action-group .btn i { margin: 0; }
        .empty-state { text-align: center; padding: 36px 20px; color: var(--text-muted); }
        .empty-state i { font-size: 2.5rem; margin-bottom: 10px; opacity: 0.5; }
        .meta { color: var(--text-muted); font-size: 0.85rem; line-height: 1.5; }
        .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.56); }
        .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,
        .stat-card,
        .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 {
            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); }
        .card-title {
            color: var(--deep-blue);
            font-weight: 800;
        }
        .stat-card,
        .card {
            border-radius: 22px;
        }
        .stat-card h3 {
            color: var(--deep-blue);
            font-weight: 800;
        }
        .stat-card {
            border-top: 4px solid var(--secondary);
        }
        table {
            border-collapse: separate;
            border-spacing: 0;
        }
        table th {
            background: rgba(255,255,255,0.70);
            color: var(--deep-blue);
            border-bottom: 1px solid rgba(0,119,182,0.16);
        }
        .sort-link {
            color: inherit;
        }
        .sort-link:hover,
        .sort-link.active {
            color: var(--primary);
        }
        table td {
            border-bottom: 1px solid rgba(0,119,182,0.10);
        }
        table tr:hover {
            background: rgba(255,255,255,0.42);
        }
        .badge {
            font-weight: 700;
            border: 1px solid rgba(255,255,255,0.48);
        }
        .btn-restore {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            box-shadow: 0 12px 24px rgba(0,119,182,0.18);
        }
        .btn-permanent-delete {
            background: linear-gradient(135deg, #dc3545, #ef4444);
            box-shadow: 0 12px 24px rgba(220,53,69,0.18);
        }
        .btn-disabled {
            background: rgba(255,255,255,0.58);
            border: 1px solid rgba(0,119,182,0.14);
        }
        .alert {
            border-radius: 14px;
            border: 1px solid rgba(255,255,255,0.48);
            backdrop-filter: blur(18px);
        }
        .empty-state {
            background: rgba(255,255,255,0.28);
            border-radius: 18px;
        }
        .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: 768px) {
            .top-bar, .card-header { flex-direction: column; align-items: flex-start; gap: 12px; }
        }
    
        /* 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>MAINPP WORKSPACE</h3>
        </div>
        <ul class="sidebar-menu">
            <?php renderUnifiedSidebarMenu($conn, $role, 'deleted_items.php'); ?>
        </ul>
    </aside>

    <main class="main">
        <div class="top-bar">
            <h2><i class="fas fa-trash-restore"></i> Data Dipadam</h2>
            <?php renderTopBarUserMenu($conn, $role, 'deleted_items.php'); ?>
        </div>

        <?php
        renderBreadcrumb([
            ['label' => 'Dashboard', 'url' => 'dashboard.php'],
            ['label' => 'Data Dipadam', 'url' => 'deleted_items.php', 'current' => true]
        ]);
        ?>

        <?php if ($message): ?>
            <div class="alert <?= htmlspecialchars($message['type']) ?>"><?= htmlspecialchars($message['text']) ?></div>
        <?php endif; ?>

        <div class="stats-grid">
            <div class="stat-card">
                <h3><?= count($deleted_folders) ?></h3>
                <p>Fail Dalam Data Dipadam</p>
            </div>
            <div class="stat-card">
                <h3><?= count($deleted_drafts) ?></h3>
                <p>Surat Dalam Data Dipadam</p>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <div class="card-title"><i class="fas fa-folder"></i> Fail Dipadam</div>
            </div>
            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>Bil.</th>
                            <?php renderDeletedItemSortableHeader('Fail', 'folders', 'folder', $deleted_item_sort_state['folders']['sort'], $deleted_item_sort_state['folders']['dir']); ?>
                            <?php renderDeletedItemSortableHeader('Bahagian', 'folders', 'department', $deleted_item_sort_state['folders']['sort'], $deleted_item_sort_state['folders']['dir']); ?>
                            <?php renderDeletedItemSortableHeader('Dipadam Pada', 'folders', 'deleted_at', $deleted_item_sort_state['folders']['sort'], $deleted_item_sort_state['folders']['dir']); ?>
                            <?php renderDeletedItemSortableHeader('Dipadam Oleh', 'folders', 'deleted_by', $deleted_item_sort_state['folders']['sort'], $deleted_item_sort_state['folders']['dir']); ?>
                            <th>Tindakan</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($display_deleted_folders)): ?>
                            <tr>
                                <td colspan="6" class="empty-state">
                                    <i class="fas fa-inbox"></i><br>
                                    Tiada fail dipadam buat masa ini.
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($display_deleted_folders as $i => $folder): ?>
                                <tr>
                                    <td><?= (int) $deleted_folders_pagination['offset'] + $i + 1 ?></td>
                                    <td>
                                        <strong><?= htmlspecialchars($folder['folder_name']) ?></strong><br>
                                        <span class="badge badge-folder"><?= htmlspecialchars($folder['folder_code']) ?></span>
                                    </td>
                                    <td><?= htmlspecialchars($folder['department'] ?: '-') ?></td>
                                    <td><?= date('d/m/Y H:i', strtotime($folder['deleted_at'])) ?></td>
                                    <td><?= htmlspecialchars($folder['deleted_by_name'] ?: 'Tidak diketahui') ?></td>
                                    <td>
                                        <div class="action-group">
                                            <?php if ($can_restore_deleted_items): ?>
                                            <a href="process_folder.php?action=restore&id=<?= (int) $folder['id'] ?>" class="btn btn-restore" onclick="return confirm('Pulihkan fail ini semula?')" title="Pulihkan" aria-label="Pulihkan">
                                                <i class="fas fa-undo"></i>
                                            </a>
                                            <form method="POST" action="deleted_items.php" onsubmit="return confirm('Adakah anda pasti mahu memadam rekod ini secara kekal? Rekod yang telah dipadam tidak boleh dipulihkan semula.');">
                                                <input type="hidden" name="action" value="permanent_delete">
                                                <input type="hidden" name="type" value="folder">
                                                <input type="hidden" name="id" value="<?= (int) $folder['id'] ?>">
                                                <button type="submit" class="btn btn-permanent-delete" title="Padam" aria-label="Padam">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                            <?php else: ?>
                                            <span class="btn btn-disabled" title="Tiada kebenaran" aria-label="Tiada kebenaran"><i class="fas fa-ban"></i></span>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
                <?php renderPaginationControls($deleted_folders_pagination, 'fail'); ?>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <div class="card-title"><i class="fas fa-file-signature"></i> Surat Dipadam</div>
            </div>
            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>Bil.</th>
                            <?php renderDeletedItemSortableHeader('Surat', 'drafts', 'letter', $deleted_item_sort_state['drafts']['sort'], $deleted_item_sort_state['drafts']['dir']); ?>
                            <?php renderDeletedItemSortableHeader('Fail / Dokumen', 'drafts', 'folder', $deleted_item_sort_state['drafts']['sort'], $deleted_item_sort_state['drafts']['dir']); ?>
                            <?php renderDeletedItemSortableHeader('Status Rekod', 'drafts', 'record_status', $deleted_item_sort_state['drafts']['sort'], $deleted_item_sort_state['drafts']['dir']); ?>
                            <?php renderDeletedItemSortableHeader('Dipadam Pada', 'drafts', 'deleted_at', $deleted_item_sort_state['drafts']['sort'], $deleted_item_sort_state['drafts']['dir']); ?>
                            <?php renderDeletedItemSortableHeader('Dipadam Oleh', 'drafts', 'deleted_by', $deleted_item_sort_state['drafts']['sort'], $deleted_item_sort_state['drafts']['dir']); ?>
                            <th>Tindakan</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($display_deleted_drafts)): ?>
                            <tr>
                                <td colspan="7" class="empty-state">
                                    <i class="fas fa-inbox"></i><br>
                                    Tiada surat dipadam buat masa ini.
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($display_deleted_drafts as $i => $draft): ?>
                                <tr>
                                    <td><?= (int) $deleted_drafts_pagination['offset'] + $i + 1 ?></td>
                                    <td>
                                        <strong><?= htmlspecialchars($draft['subject']) ?></strong><br>
                                        <span class="badge badge-document"><?= htmlspecialchars(formatDraftLetterReferenceDisplay('', $draft['ref_no'] ?? '', $draft['file_numbering'] ?? '')) ?></span>
                                        <div class="meta">
                                            Tarikh surat: <?= !empty($draft['letter_date']) ? date('d/m/Y', strtotime($draft['letter_date'])) : '-' ?><br>
                                            Jenis: <?= htmlspecialchars($draft['doc_type'] ?: '-') ?><br>
                                            Status draf: <?= htmlspecialchars($draft['status'] ?: '-') ?>
                                        </div>
                                    </td>
                                    <td>
                                        <strong><?= htmlspecialchars($draft['folder_name'] ?: 'Fail tidak dijumpai') ?></strong><br>
                                        <div class="meta"><?= htmlspecialchars($draft['folder_code'] ?: '-') ?></div>
                                        <?php if (!empty($draft['folder_deleted_at'])): ?>
                                            <span class="badge badge-warning">Fail asal turut dipadam</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if (!empty($draft['document_deleted_at'])): ?>
                                            <span class="badge badge-warning">Dokumen asal dipadam</span>
                                        <?php else: ?>
                                            <span class="badge badge-success">Dokumen asal aktif</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= date('d/m/Y H:i', strtotime($draft['deleted_at'])) ?></td>
                                    <td><?= htmlspecialchars($draft['deleted_by_name'] ?: 'Tidak diketahui') ?></td>
                                    <td>
                                        <div class="action-group">
                                            <?php if (!$can_restore_deleted_items): ?>
                                                <span class="btn btn-disabled" title="Tiada kebenaran" aria-label="Tiada kebenaran"><i class="fas fa-ban"></i></span>
                                            <?php else: ?>
                                                <a href="process_draft_letter.php?action=restore&id=<?= (int) $draft['id'] ?>" class="btn btn-restore" onclick="return confirm('Pulihkan surat ini semula?')" title="Pulihkan" aria-label="Pulihkan">
                                                    <i class="fas fa-undo"></i>
                                                </a>
                                                <form method="POST" action="deleted_items.php" onsubmit="return confirm('Adakah anda pasti mahu memadam rekod ini secara kekal? Rekod yang telah dipadam tidak boleh dipulihkan semula.');">
                                                    <input type="hidden" name="action" value="permanent_delete">
                                                    <input type="hidden" name="type" value="draft">
                                                    <input type="hidden" name="id" value="<?= (int) $draft['id'] ?>">
                                                    <button type="submit" class="btn btn-permanent-delete" title="Padam" aria-label="Padam">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
                <?php renderPaginationControls($deleted_drafts_pagination, 'surat'); ?>
            </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?");
        }
    </script>
    <?php renderSessionTimeoutScript(); ?>
</body>
</html>
