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

// DAPATKAN ROLE UNTUK SIDEBAR CONSISTENCY
$role = $_SESSION['role'] ?? 'user';
$departments_list = getDepartmentList();
$document_types = getDocumentTypeList();
$folder_types = getFolderTypeList();

// Dapatkan parameter carian
$keyword = trim($_GET['keyword'] ?? '');
$ref_no = trim($_GET['ref_no'] ?? '');
$ref_no_query = '';
if ($ref_no !== '') {
    if (preg_match('/^\((\d+)\)$/', $ref_no, $matches)) {
        $ref_no_query = $matches[1];
    } elseif (ctype_digit($ref_no)) {
        $ref_no_query = $ref_no;
    } else {
        $ref_no_query = $ref_no;
    }
}
$subject = trim($_GET['subject'] ?? '');
$doc_date = $_GET['doc_date'] ?? '';
$from_person = trim($_GET['from_person'] ?? '');
$to_person = trim($_GET['to_person'] ?? '');
$doc_type = $_GET['doc_type'] ?? '';
$folder_type = normalizeFolderType($_GET['folder_type'] ?? '');
$has_folder_type_filter = isset($_GET['folder_type']) && $_GET['folder_type'] !== '';
$search_sort_columns = [
    'folder' => ['label' => 'Fail', 'type' => 'text'],
    'reference' => ['label' => 'No. Rujukan', 'type' => 'text'],
    'subject' => ['label' => 'Perkara', 'type' => 'text'],
    'date' => ['label' => 'Tarikh', 'type' => 'date'],
    'from' => ['label' => 'Daripada', 'type' => 'text'],
    'to' => ['label' => 'Kepada', 'type' => 'text'],
    'type' => ['label' => 'Jenis', 'type' => 'text'],
];
$search_sort_state = [
    'office' => [
        'sort' => trim((string) ($_GET['office_sort'] ?? '')),
        'dir' => strtolower(trim((string) ($_GET['office_dir'] ?? ''))),
    ],
    'personal' => [
        'sort' => trim((string) ($_GET['personal_sort'] ?? '')),
        'dir' => strtolower(trim((string) ($_GET['personal_dir'] ?? ''))),
    ],
];
foreach ($search_sort_state as $section_key => $state) {
    if (!isset($search_sort_columns[$state['sort']])
        || ($section_key === 'personal' && in_array($state['sort'], ['reference', 'from', 'to'], true))) {
        $search_sort_state[$section_key]['sort'] = '';
    }
    if (!in_array($state['dir'], ['asc', 'desc'], true)) {
        $search_sort_state[$section_key]['dir'] = 'asc';
    }
}

// Bina query dinamik. Surat berstatus Draf hanya dipaparkan kepada penyedia.
$sql = "SELECT d.*, f.id AS folder_view_id, f.folder_name, f.folder_code, f.folder_type
    FROM documents d
    JOIN folders f ON d.folder_id = f.id
    LEFT JOIN letter_drafts ld ON ld.document_id = d.id AND ld.deleted_at IS NULL
    WHERE d.deleted_at IS NULL
      AND f.deleted_at IS NULL
      AND (
          ld.id IS NULL
          OR NOT (ld.status = 'draf' OR ld.approval_status = 'draft')
          OR ld.created_by = ?
          OR ? = 'superadmin'
      )";
$params = [(int) ($_SESSION['user_id'] ?? 0), $role];
$types = "is";

if (!empty($subject)) { $sql .= " AND d.subject LIKE ?"; $params[] = "%$subject%"; $types .= "s"; }
if (!empty($doc_date)) { $sql .= " AND d.doc_date = ?"; $params[] = $doc_date; $types .= "s"; }
if (!empty($from_person)) { $sql .= " AND d.from_person LIKE ?"; $params[] = "%$from_person%"; $types .= "s"; }
if (!empty($to_person)) { $sql .= " AND d.to_person LIKE ?"; $params[] = "%$to_person%"; $types .= "s"; }
if (!empty($doc_type)) { $sql .= " AND d.doc_type = ?"; $params[] = $doc_type; $types .= "s"; }
if ($has_folder_type_filter) {
    if ($folder_type === 'sendirian') {
        $sql .= " AND f.folder_type = ?";
        $params[] = 'sendirian';
        $types .= "s";
    } else {
        $sql .= " AND (f.folder_type = ? OR f.folder_type IS NULL OR f.folder_type = '')";
        $params[] = 'office';
        $types .= "s";
    }
}
if (!empty($keyword)) {
    $sql .= " AND (d.ref_no LIKE ? OR d.subject LIKE ? OR f.folder_code LIKE ? OR f.folder_name LIKE ?)";
    $params[] = "%$keyword%";
    $params[] = "%$keyword%";
    $params[] = "%$keyword%";
    $params[] = "%$keyword%";
    $types .= "ssss";
}
if ($ref_no_query !== '') {
    $sql .= " AND (d.file_numbering = ? OR d.ref_no LIKE ?)";
    $params[] = $ref_no_query;
    $params[] = "%({$ref_no_query})%";
    $types .= "ss";
}

$sql .= " ORDER BY d.subject ASC, d.ref_no ASC, f.folder_name ASC, d.doc_date DESC";

// Execute query
if (!empty($params)) {
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, $types, ...$params);
    mysqli_stmt_execute($stmt);
    $results = mysqli_fetch_all(mysqli_stmt_get_result($stmt), MYSQLI_ASSOC);
} else {
    $results = mysqli_fetch_all(mysqli_query($conn, $sql), MYSQLI_ASSOC);
}

$office_results = [];
$personal_results = [];
foreach ($results as $result) {
    $normalized_folder_type = normalizeFolderType($result['folder_type'] ?? '');
    $result['folder_type'] = $normalized_folder_type;

    if ($normalized_folder_type === 'sendirian') {
        $personal_results[] = $result;
    } else {
        $office_results[] = $result;
    }
}

foreach ($office_results as $index => &$result) {
    $result['_default_order'] = $index;
}
unset($result);
foreach ($personal_results as $index => &$result) {
    $result['_default_order'] = $index;
}
unset($result);

sortSearchSectionResults($office_results, $search_sort_state['office']['sort'], $search_sort_state['office']['dir'], $search_sort_columns);
sortSearchSectionResults($personal_results, $search_sort_state['personal']['sort'], $search_sort_state['personal']['dir'], $search_sort_columns);

// Dropdown values
$people_list = $departments_list;

function getSearchResultSortValue($result, $column) {
    switch ($column) {
        case 'folder':
            return trim((string) (($result['folder_code'] ?? '') . ' ' . ($result['folder_name'] ?? '')));
        case 'reference':
            return formatDraftLetterReferenceDisplay('', $result['ref_no'] ?? '', $result['file_numbering'] ?? '');
        case 'subject':
            return $result['subject'] ?? '';
        case 'date':
            return strtotime((string) ($result['doc_date'] ?? '')) ?: 0;
        case 'from':
            return $result['from_person'] ?? '';
        case 'to':
            return $result['to_person'] ?? '';
        case 'type':
            return $result['doc_type'] ?? '';
        default:
            return '';
    }
}

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

    usort($results, function ($result_a, $result_b) use ($sort_column, $sort_dir, $sort_columns) {
        $sort_type = $sort_columns[$sort_column]['type'] ?? 'text';
        $value_a = getSearchResultSortValue($result_a, $sort_column);
        $value_b = getSearchResultSortValue($result_b, $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) ($result_a['_default_order'] ?? 0)) <=> ((int) ($result_b['_default_order'] ?? 0));
        }

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

function buildSearchSortUrl($section_key, $column, $current_sort, $current_dir) {
    $query = $_GET;
    unset($query[$section_key . '_page']);
    $sort_param = $section_key . '_sort';
    $dir_param = $section_key . '_dir';

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

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

function renderSearchSortableHeader($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="' . buildSearchSortUrl($section_key, $column, $current_sort, $current_dir) . '">';
    echo '<span>' . htmlspecialchars($label) . '</span><span class="sort-indicator">' . $indicator . '</span>';
    echo '</a>';
    echo '</th>';
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Carian Lanjutan | MAINPP WORKSPACE</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <?php renderAppShellAssets(); ?>
    <style>
        :root {
            --primary: #0077b6; --primary-dark: #005f99; --secondary: #00b4d8;
            --deep-blue: #023e5f;
            --superadmin: #6c5ce7; --superadmin-dark: #5b4cdb;
            --bg-light: rgba(245, 250, 253, 0.72); --bg-card: rgba(255, 255, 255, 0.68); --text-main: #163447;
            --text-muted: #2d5367; --border: rgba(255, 255, 255, 0.48); --sidebar-width: 280px;
            --success: #1a9955; --danger: #dc3545; --warning: #ffc107;
            --glass: rgba(255, 255, 255, 0.58);
            --glass-strong: rgba(255, 255, 255, 0.76);
            --shadow-soft: 0 24px 70px rgba(2, 62, 95, 0.16);
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', 'Inter', Tahoma, Geneva, Verdana, sans-serif; }
        body {
            background:
                linear-gradient(135deg, rgba(245, 250, 253, 0.90), rgba(222, 246, 252, 0.76)),
                url('assets/auth-bg.png') center/cover no-repeat fixed;
            min-height: 100vh;
            display: flex;
            color: var(--text-main);
            overflow-x: hidden;
        }

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

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

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

        .sidebar { width: var(--sidebar-width); background: linear-gradient(180deg, rgba(2, 62, 95, 0.94), rgba(0, 119, 182, 0.84)), radial-gradient(circle at 22% 8%, rgba(0, 180, 216, 0.28), transparent 32%); border-right: 1px solid rgba(255, 255, 255, 0.22); position: fixed; height: 100vh; padding: 20px 0; overflow-y: auto; overflow-x: hidden; z-index: 1000; box-shadow: 18px 0 44px rgba(2, 38, 60, 0.20); transition: width 0.3s ease; display:flex; flex-direction:column; backdrop-filter: blur(18px) saturate(1.25); -webkit-backdrop-filter: blur(18px) saturate(1.25); }
        .sidebar.collapsed { width: 70px; }
        .sidebar-header { text-align: center; padding: 0 20px 20px; border-bottom: 1px solid rgba(255, 255, 255, 0.16); margin-bottom: 20px; white-space: nowrap; overflow: hidden; background: transparent !important; }
        .sidebar.collapsed .sidebar-header h3, .sidebar.collapsed .sidebar-header p, .sidebar.collapsed .menu-text { display: none; }
        .sidebar-header img { width: 54px; margin-bottom: 10px; transition: margin 0.3s ease; filter: drop-shadow(0 10px 18px rgba(0,0,0,0.25)); }
        .sidebar.collapsed .sidebar-header img { margin: 0 auto 10px; }
        .sidebar-header h3 { font-size: 1rem; font-weight: 800; color: #fff; margin-bottom: 4px; letter-spacing: 0.01em; }
        .sidebar-header p { font-size: 0.75rem; color: rgba(255,255,255,0.72); }
        .role-badge { display: inline-block; padding: 3px 10px; border-radius: 12px; font-size: 0.7rem; font-weight: 600; margin-left: 8px; }
        .role-badge.user { background: #e6f4ff; color: var(--primary); }
        .role-badge.admin { background: #d4edda; color: var(--success); }
        .role-badge.superadmin { background: linear-gradient(90deg, var(--superadmin), var(--superadmin-dark)); color: #fff; }
        .sidebar-menu { list-style: none; padding: 0 10px; display:flex; flex-direction:column; flex:1; }
        .sidebar-section { padding: 10px 18px 6px; color: rgba(255,255,255,0.58); font-size: 0.72rem; font-weight: 800; text-transform: uppercase; letter-spacing: 0.06em; }
        .sidebar-spacer { margin-top: auto; }
        .sidebar-menu li a { display: flex; align-items: center; gap: 12px; padding: 12px 18px; color: rgba(255,255,255,0.88); text-decoration: none; border-radius: 10px; margin-bottom: 5px; transition: all 0.2s ease; font-size: 0.9rem; white-space: nowrap; }
        .sidebar-menu li a:hover, .sidebar-menu li a.active { background: rgba(255,255,255,0.18); color: #fff; box-shadow: inset 0 0 0 1px rgba(255,255,255,0.18); }
        .sidebar-menu li a i { width: 20px; text-align: center; font-size: 1.1rem; }
        .sidebar-menu .dropdown { position: relative; }
        .sidebar-menu .dropdown-toggle { display: flex; align-items: center; justify-content: space-between; width: 100%; padding: 12px 18px; color: rgba(255,255,255,0.88); background: none; border: none; border-radius: 10px; cursor: pointer; font-size: 0.9rem; text-align: left; transition: all 0.2s ease; }
        .sidebar-menu .dropdown-toggle:hover, .sidebar-menu .dropdown-toggle.active { background: rgba(255,255,255,0.18); color: #fff; box-shadow: inset 0 0 0 1px rgba(255,255,255,0.18); }
        .sidebar-menu .dropdown-toggle i.chevron { transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); font-size: 0.8rem; }
        .sidebar-menu .dropdown.active .dropdown-toggle i.chevron { transform: rotate(180deg); }
        .sidebar-menu .dropdown-menu { display: flex; flex-direction: column; padding-left: 42px; margin-top: 4px; max-height: 0; opacity: 0; overflow: hidden; transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.25s ease; }
        .sidebar-menu .dropdown.active .dropdown-menu { max-height: 260px; opacity: 1; }
        .sidebar-menu .dropdown-menu a { padding: 8px 18px; color: rgba(255,255,255,0.78); text-decoration: none; border-radius: 8px; font-size: 0.85rem; display: flex; align-items: center; gap: 8px; opacity: 0; transform: translateY(-5px); transition: opacity 0.2s ease, transform 0.2s ease; }
        .sidebar-menu .dropdown.active .dropdown-menu a { opacity: 1; transform: translateY(0); }
        .sidebar-menu .dropdown-menu a:hover, .sidebar-menu .dropdown-menu a.active { background: rgba(255,255,255,0.16); color: #fff; }
        .sidebar.collapsed + .main { margin-left: 70px; }
        .sidebar-toggle { position: absolute; right: 10px; top: 20px; width: 28px; height: 28px; background: rgba(255,255,255,0.20); color: #fff; border: 1px solid rgba(255,255,255,0.28); border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 0.7rem; box-shadow: 0 10px 22px rgba(0,0,0,0.14); transition: transform 0.3s ease; z-index: 1001; }
        .sidebar.collapsed .sidebar-toggle { transform: rotate(180deg); }
        .main { position: relative; z-index: 1; margin-left: var(--sidebar-width); flex: 1; padding: 28px 32px; transition: margin-left 0.3s ease; }
        .top-bar { background: var(--glass); padding: 18px 24px; border-radius: 18px; box-shadow: var(--shadow-soft); margin-bottom: 18px; display: flex; justify-content: space-between; align-items: center; border: 1px solid var(--border); backdrop-filter: blur(22px) saturate(1.25); -webkit-backdrop-filter: blur(22px) saturate(1.25); }
        .top-bar h2 { color: var(--primary-dark); font-size: 1.35rem; font-weight: 850; display: flex; align-items: center; gap: 10px; }
        .top-bar h2 i { color: var(--secondary); }
        .user-info { display: flex; align-items: center; gap: 15px; font-size: 0.9rem; color: var(--text-muted); }
        .user-info span { color: var(--primary); font-weight: 600; }
        .user-info a { color: var(--danger); text-decoration: none; font-weight: 500; display: flex; align-items: center; gap: 5px; }
        .user-info a:hover { text-decoration: underline; }
        
        /* Search Panel */
        .search-panel { background: var(--glass); padding: 22px; border-radius: 22px; box-shadow: var(--shadow-soft); margin-bottom: 25px; border: 1px solid var(--border); backdrop-filter: blur(24px) saturate(1.25); -webkit-backdrop-filter: blur(24px) saturate(1.25); }
        .search-panel h4 { color: var(--primary-dark); margin-bottom: 18px; font-size: 1.12rem; font-weight: 850; display: flex; align-items: center; gap: 8px; }
        .search-panel h4 i { color: var(--secondary); }
        .search-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; }
        .form-group { }
        .form-group label { display: block; margin-bottom: 7px; color: var(--text-main); font-weight: 750; font-size: 0.9rem; }
        .form-group input, .form-group select { width: 100%; padding: 11px 14px; border: 1px solid rgba(0,119,182,0.18); border-radius: 12px; font-size: 0.9rem; background: rgba(255,255,255,0.78); color: var(--text-main); }
        .form-group input:focus, .form-group select:focus { border-color: var(--primary); outline: none; box-shadow: 0 0 0 4px rgba(0,119,182,0.13); background: #fff; }
        .search-actions { display: flex; gap: 10px; margin-top: 0; flex-wrap: wrap; align-self: end; padding-bottom: 1px; }
        .btn { padding: 10px 18px; border: none; border-radius: 999px; cursor: pointer; font-size: 0.95rem; font-weight: 850; display: inline-flex; align-items: center; gap: 7px; text-decoration: none; transition: transform 0.2s ease, filter 0.2s ease, box-shadow 0.2s ease; }
        .btn:hover { transform: translateY(-1px); filter: brightness(1.04); }
        .btn-primary { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; }
        .btn-secondary { background: #526b79; color: #fff; }
        .search-actions .btn { width: 40px; min-height: 38px; height: 38px; min-width: 40px; padding: 0; border-radius: 999px; justify-content: center; gap: 0; }
        .search-actions .btn i { margin: 0; }
        .search-actions .btn-secondary { background: rgba(255,255,255,0.70); color: var(--primary); border: 1px solid rgba(0,119,182,0.18); box-shadow: 0 10px 22px rgba(2,62,95,0.08); }
        .disabled-action { opacity: 0.6; cursor: not-allowed; }
        .btn-view { background: linear-gradient(90deg, var(--primary), var(--secondary)); color: #fff; }
        .action-group { display: flex; align-items: center; gap: 6px; flex-wrap: nowrap; white-space: nowrap; }
        .action-group .btn { padding: 6px 14px !important; font-size: 0.8rem !important; border-radius: 6px; text-decoration: none; color: #fff; display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; }
        
        /* Results */
        .results-count { color: var(--text-muted); font-size: 0.9rem; margin-bottom: 15px; font-weight: 650; }
        .results-count strong { color: var(--primary-dark); font-weight: 850; }
        
        /* Card & Table */
        .card { background: var(--glass); border-radius: 22px; box-shadow: var(--shadow-soft); padding: 22px; margin-bottom: 25px; border: 1px solid var(--border); backdrop-filter: blur(24px) saturate(1.25); -webkit-backdrop-filter: blur(24px) saturate(1.25); }
        .table-responsive { overflow-x: auto; border-radius: 18px; border: 1px solid rgba(255,255,255,0.58); background: rgba(255,255,255,0.60); }
        table { width: 100%; border-collapse: collapse; font-size: 0.9rem; min-width: 980px; }
        table th { background: rgba(0,119,182,0.09); color: var(--primary-dark); font-weight: 850; text-align: center; padding: 14px 16px; border-bottom: 1px solid rgba(0,119,182,0.13); }
        .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); }
        .sort-indicator { font-size: 0.78rem; line-height: 1; opacity: 0.78; }
        table td { padding: 14px 16px; border-bottom: 1px solid rgba(0,119,182,0.10); vertical-align: middle; text-align: left; background: rgba(255,255,255,0.66); }
        table tr:hover td { background: rgba(231, 248, 252, 0.72); }
        .badge { padding: 5px 12px; border-radius: 999px; font-size: 0.8rem; font-weight: 700; display: inline-block; }
        .badge-blue { background: #e6f4ff; color: var(--primary-dark); }
        .badge-orange { background: #fff3cd; color: #856404; }
        .folder-name-small { color: var(--text-muted); font-weight: 650; }
        
        .empty-state { text-align:center; vertical-align:middle; padding:50px 20px !important; color:#6c757d; } .empty-state i { display:block; font-size:3rem; margin-bottom:15px; color:#6c757d; opacity:.7; }
        .back-link { display: inline-block; margin-top: 20px; color: var(--primary); text-decoration: none; font-size: 0.9rem; }
        .back-link:hover { text-decoration: underline; }
        .page-footer { text-align: center; padding: 20px; color: var(--text-muted); font-size: 0.8rem; margin-top: 30px; }
        
        /* Element visibility by role */
        .admin-only, .superadmin-only { display: none; }
        body.role-admin .admin-only,
        body.role-superadmin .admin-only,
        body.role-superadmin .superadmin-only { display: block; }

        @media (max-width: 992px) {
            .sidebar { width: 70px; }
            .sidebar .sidebar-header h3, .sidebar .sidebar-header p, .sidebar .menu-text, .sidebar .role-badge, .sidebar .dropdown-menu, .sidebar .sidebar-section { display: none; }
            .main { margin-left: 70px; }
            .sidebar-toggle { display: none; }
        }
        .sidebar {
            overflow: hidden;
        }
        .sidebar-header {
            flex: 0 0 auto;
        }
        .sidebar-menu {
            flex: 1 1 auto;
            min-height: 0;
            overflow-y: auto;
            overflow-x: hidden;
            padding-bottom: 0;
            overscroll-behavior: contain;
            scrollbar-width: thin;
            scrollbar-color: #8f8f8f transparent;
        }
        .sidebar-menu::-webkit-scrollbar {
            width: 10px;
        }
        .sidebar-menu::-webkit-scrollbar-track {
            background: transparent;
        }
        .sidebar-menu::-webkit-scrollbar-thumb {
            background: #8f8f8f;
            border-radius: 999px;
            border: 2px solid transparent;
            background-clip: content-box;
        }
        .sidebar-menu::-webkit-scrollbar-button {
            display: none;
            width: 0;
            height: 0;
        }
    
        /* Button hover animation */
        .main .btn,
        .main .tab-btn,
        .main .action-btn,
        .main .btn-action,
        .main .filter-btn,
        .main .button,
        .main .generate-closing-btn,
        .main .attachment-remove-btn,
        .main .page-add-btn,
        .main .page-delete-btn,
        .main .delete-current-page-btn,
        .main .form-actions a,
        .main .form-actions button,
        .main .filter-actions a,
        .main .filter-actions button,
        .main .document-command a,
        .main .document-command button,
        .main table a[class*="btn"],
        .main table button[class*="btn"],
        .main input[type="submit"],
        .main input[type="button"] {
            transition: transform 0.2s ease, filter 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease, border-color 0.2s ease !important;
            will-change: transform;
        }

        .main .btn:hover:not(:disabled),
        .main .tab-btn:hover:not(:disabled),
        .main .action-btn:hover:not(:disabled),
        .main .btn-action:hover:not(:disabled),
        .main .filter-btn:hover:not(:disabled),
        .main .button:hover:not(:disabled),
        .main .generate-closing-btn:hover:not(:disabled),
        .main .attachment-remove-btn:hover:not(:disabled),
        .main .page-add-btn:hover:not(:disabled),
        .main .page-delete-btn:hover:not(:disabled),
        .main .delete-current-page-btn:hover:not(:disabled),
        .main .form-actions a:hover,
        .main .form-actions button:hover:not(:disabled),
        .main .filter-actions a:hover,
        .main .filter-actions button:hover:not(:disabled),
        .main .document-command a:hover,
        .main .document-command button:hover:not(:disabled),
        .main table a[class*="btn"]:hover,
        .main table button[class*="btn"]:hover:not(:disabled),
        .main input[type="submit"]:hover:not(:disabled),
        .main input[type="button"]:hover:not(:disabled) {
            transform: translateY(-1px);
            filter: brightness(1.04);
            box-shadow: 0 14px 28px rgba(0, 119, 182, 0.18);
        }

        .main .btn:active:not(:disabled),
        .main .tab-btn:active:not(:disabled),
        .main .action-btn:active:not(:disabled),
        .main .btn-action:active:not(:disabled),
        .main .filter-btn:active:not(:disabled),
        .main .button:active:not(:disabled),
        .main .generate-closing-btn:active:not(:disabled),
        .main .attachment-remove-btn:active:not(:disabled),
        .main .page-add-btn:active:not(:disabled),
        .main .page-delete-btn:active:not(:disabled),
        .main .delete-current-page-btn:active:not(:disabled),
        .main .form-actions a:active,
        .main .form-actions button:active:not(:disabled),
        .main .filter-actions a:active,
        .main .filter-actions button:active:not(:disabled),
        .main .document-command a:active,
        .main .document-command button:active:not(:disabled),
        .main table a[class*="btn"]:active,
        .main table button[class*="btn"]:active:not(:disabled),
        .main input[type="submit"]:active:not(:disabled),
        .main input[type="button"]:active:not(:disabled) {
            transform: translateY(0);
            filter: brightness(0.98);
        }
        .main .pagination-wrap {
            padding-right: 24px;
        }
        .main .pagination {
            margin-right: 8px;
        }
        @media (max-width: 640px) {
            .main .pagination-wrap {
                justify-content: center !important;
                padding-right: 0;
            }
            .main .pagination-info {
                width: 100%;
                text-align: center;
            }
            .main .pagination {
                width: 100%;
                justify-content: center;
                margin-right: 0;
            }
        }</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, 'search.php'); ?>
        </ul>
    </aside>

    <!-- MAIN CONTENT -->
    <main class="main">
        <div class="top-bar">
            <h2><i class="fas fa-search"></i> Carian Lanjutan</h2>
            <?php renderTopBarUserMenu($conn, $role, 'search.php'); ?>
        </div>

        <?php
        renderBreadcrumb([
            ['label' => 'Dashboard', 'url' => 'dashboard.php'],
            ['label' => 'Carian Lanjutan', 'url' => 'search.php', 'current' => true]
        ]);
        ?>

        <!-- BORANG CARIAN -->
        <div class="search-panel">
            <form method="GET" action="search.php">
                <?php foreach ($search_sort_state as $sort_section_key => $sort_state): ?>
                    <?php if (($sort_state['sort'] ?? '') !== ''): ?>
                    <input type="hidden" name="<?= htmlspecialchars($sort_section_key) ?>_sort" value="<?= htmlspecialchars($sort_state['sort']) ?>">
                    <input type="hidden" name="<?= htmlspecialchars($sort_section_key) ?>_dir" value="<?= htmlspecialchars($sort_state['dir']) ?>">
                    <?php endif; ?>
                <?php endforeach; ?>
                <h4><i></i> Kriteria Carian</h4>
                <div class="search-grid">
                    <div class="form-group">
                        <label>Kod Fail</label>
                        <input type="text" name="keyword" value="<?php echo htmlspecialchars($keyword); ?>">
                    </div>
                    <div class="form-group">
                        <label>No. Rujukan</label>
                        <input type="text" name="ref_no" value="<?php echo htmlspecialchars($ref_no); ?>">
                    </div>
                    <div class="form-group">
                        <label>Perkara</label>
                        <input type="text" name="subject" value="<?php echo htmlspecialchars($subject); ?>">
                    </div>
                    <div class="form-group">
                        <label>Tarikh</label>
                        <input type="date" name="doc_date" value="<?php echo htmlspecialchars($doc_date); ?>">
                    </div>
                    <div class="form-group">
                        <label>Daripada</label>
                        <select name="from_person">
                            <option value="">-- Semua --</option>
                            <?php foreach ($people_list as $p): ?>
                                <option value="<?php echo htmlspecialchars($p); ?>" <?php if($from_person === $p) echo 'selected'; ?>>
                                    <?php echo htmlspecialchars($p); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Kepada</label>
                        <select name="to_person">
                            <option value="">-- Semua --</option>
                            <?php foreach ($people_list as $p): ?>
                                <option value="<?php echo htmlspecialchars($p); ?>" <?php if($to_person === $p) echo 'selected'; ?>>
                                    <?php echo htmlspecialchars($p); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Jenis Surat</label>
                        <select name="doc_type">
                            <option value="">-- Semua Jenis --</option>
                            <?php foreach ($document_types as $document_type): ?>
                                <option value="<?= htmlspecialchars($document_type) ?>" <?php if($doc_type === $document_type) echo 'selected'; ?>>
                                    <?= htmlspecialchars($document_type) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Jenis Fail</label>
                        <select name="folder_type">
                            <option value="">-- Semua Jenis Fail --</option>
                            <?php foreach ($folder_types as $folder_type_option): ?>
                                <option value="<?= htmlspecialchars($folder_type_option) ?>" <?php if($has_folder_type_filter && $folder_type === normalizeFolderType($folder_type_option)) echo 'selected'; ?>>
                                    <?= htmlspecialchars(getFolderTypeLabel($folder_type_option)) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="search-actions">
                        <button type="submit" class="btn btn-primary" title="Cari" aria-label="Cari">
                            <i class="fas fa-search"></i>
                        </button>
                        <a href="search.php" class="btn btn-secondary" title="Reset" aria-label="Reset">
                            <i class="fas fa-rotate-left"></i>
                        </a>
                    </div>
                </div>
            </form>
        </div>

        <?php
        $result_sections = [
            ['title' => 'Hasil Carian Office', 'key' => 'office', 'results' => $office_results],
            ['title' => 'Hasil Carian Personal', 'key' => 'personal', 'results' => $personal_results]
        ];
        ?>

                    <?php foreach ($result_sections as $section_index => $section): ?>
            <?php
                $section_page_param = $section_index === 0 ? 'office_page' : 'personal_page';
                $section_pagination = paginateArrayItems($section['results'], $section_page_param, 15);
                $section_results = $section_pagination['items'];
                $is_personal_section = $section_index === 1;
                $empty_colspan = $is_personal_section ? 6 : 9;
                $section_key = $section['key'];
                $section_sort = $search_sort_state[$section_key]['sort'] ?? '';
                $section_sort_dir = $search_sort_state[$section_key]['dir'] ?? 'asc';
            ?>

                        <div class="card">

                <div class="results-count">
                    <strong><?= htmlspecialchars($section['title']) ?></strong>: <?= count($section['results']) ?> rekod
                </div>

                <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>Bil.</th>
                            <?php renderSearchSortableHeader('Fail', $section_key, 'folder', $section_sort, $section_sort_dir); ?>
                            <?php if (!$is_personal_section): ?>
                                <?php renderSearchSortableHeader('No. Rujukan', $section_key, 'reference', $section_sort, $section_sort_dir); ?>
                            <?php endif; ?>
                            <?php renderSearchSortableHeader('Perkara', $section_key, 'subject', $section_sort, $section_sort_dir); ?>
                            <?php renderSearchSortableHeader('Tarikh', $section_key, 'date', $section_sort, $section_sort_dir); ?>
                            <?php if (!$is_personal_section): ?>
                                <?php renderSearchSortableHeader('Daripada', $section_key, 'from', $section_sort, $section_sort_dir); ?>
                                <?php renderSearchSortableHeader('Kepada', $section_key, 'to', $section_sort, $section_sort_dir); ?>
                            <?php endif; ?>
                            <?php renderSearchSortableHeader('Jenis', $section_key, 'type', $section_sort, $section_sort_dir); ?>
                            <th>Tindakan</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($section_results)): ?>
                            <tr><td colspan="<?= $empty_colspan ?>" class="empty-state"><i class="fas fa-search"></i><br>Tiada hasil carian untuk kategori ini.</td></tr>
                        <?php else: ?>
                            <?php foreach ($section_results as $i => $r): ?>
                            <tr>
                                <td><?= (int) $section_pagination['offset'] + $i + 1 ?></td>
                                <td>
                                    <span class="badge badge-blue"><?php echo htmlspecialchars($r['folder_code']); ?></span><br>
                                    <small class="folder-name-small"><?php echo htmlspecialchars($r['folder_name']); ?></small>
                                </td>
                                <?php if (!$is_personal_section): ?>
                                    <td><?php echo htmlspecialchars(formatDraftLetterReferenceDisplay('', $r['ref_no'] ?? '', $r['file_numbering'] ?? '')); ?></td>
                                <?php endif; ?>
                                <td><?php echo htmlspecialchars($r['subject']); ?></td>
                                <td><?php echo date('d/m/Y', strtotime($r['doc_date'])); ?></td>
                                <?php if (!$is_personal_section): ?>
                                    <td><?php echo htmlspecialchars($r['from_person']); ?></td>
                                    <td><?php echo htmlspecialchars($r['to_person']); ?></td>
                                <?php endif; ?>
                                <td><span class="badge badge-orange"><?php echo htmlspecialchars($r['doc_type']); ?></span></td>
                                <td>
                                    <?php $folderViewId = (int) ($r['folder_view_id'] ?? $r['folder_id'] ?? 0); ?>
                                    <?php if ($folderViewId > 0): ?>
                                    <div class="action-group">
                                        <a href="view_folder.php?id=<?php echo $folderViewId; ?>" class="btn btn-view" title="Buka fail" aria-label="Buka fail">
                                            <i class="fas fa-folder-open"></i>
                                        </a>
                                    </div>
                                    <?php else: ?>
                                    <div class="action-group">
                                        <span class="btn btn-secondary disabled-action" title="Fail tidak tersedia" aria-label="Fail tidak tersedia">
                                            <i class="fas fa-folder-open"></i>
                                        </span>
                                    </div>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
                <?php renderPaginationControls($section_pagination, 'rekod'); ?>
            </div>
        </div>
        <?php endforeach; ?>

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