<?php
session_start();
require_once dirname(__DIR__) . '/includes/functions.php';

billing_require_auth();

$user = billing_current_user();
$organization = billing_current_organization();

if (!$user) {
    billing_redirect('signin.php');
}

if (!$organization || empty($organization['onboarding_completed_at'])) {
    billing_redirect('onboarding.php?step=1');
}

$billingActiveNav = 'documents';
$billingTopbarOrganizationName = (string) ($organization['organization_name'] ?? 'Billing');
$billingTopbarUserLabel = (string) ($user['email'] ?? '');
$billingTopbarSearchPlaceholder = 'Search in Documents';

$documentRoot = dirname(__DIR__) . '/assets/uploads/documents';
if (!is_dir($documentRoot)) {
    mkdir($documentRoot, 0777, true);
}

$flashSuccess = billing_flash('documents_success');
$flashError = billing_flash('documents_error');
if (!isset($_SESSION['documents_custom_views']) || !is_array($_SESSION['documents_custom_views'])) {
    $_SESSION['documents_custom_views'] = [];
}

$documentFilterFields = [
    'file_type' => 'File Type',
    'folder' => 'Folder',
    'uploaded_by' => 'Uploaded By',
    'file_name' => 'File Name',
];

$documentFilterComparators = [
    'is' => 'is',
    'is_not' => 'is not',
    'contains' => 'contains',
    'not_contains' => 'does not contain',
    'is_empty' => 'is empty',
    'is_not_empty' => 'is not empty',
];

$documentColumnLabels = [
    'file_name' => 'File Name',
    'uploaded_by' => 'Uploaded By',
    'uploaded_on' => 'Uploaded On',
    'associated_to' => 'Associated To',
    'folder' => 'Folder',
];

$defaultDocumentColumns = ['file_name', 'uploaded_by', 'uploaded_on', 'associated_to', 'folder'];

foreach ($_SESSION['documents_custom_views'] as $existingViewKey => $existingView) {
    if (!is_array($existingView)) {
        unset($_SESSION['documents_custom_views'][$existingViewKey]);
        continue;
    }

    $existingColumns = $existingView['selected_columns'] ?? $defaultDocumentColumns;
    if (!is_array($existingColumns)) {
        $existingColumns = $defaultDocumentColumns;
    }

    $existingColumns = array_values(array_filter($existingColumns, static function ($column) use ($documentColumnLabels): bool {
        return is_string($column) && isset($documentColumnLabels[$column]);
    }));

    if ($existingColumns === []) {
        $existingColumns = $defaultDocumentColumns;
    }

    $_SESSION['documents_custom_views'][$existingViewKey]['selected_columns'] = $existingColumns;
}

$formatBytes = static function (int $bytes): string {
    if ($bytes >= 1024 * 1024 * 1024) {
        return number_format($bytes / (1024 * 1024 * 1024), 2) . ' GB';
    }
    if ($bytes >= 1024 * 1024) {
        return number_format($bytes / (1024 * 1024), 2) . ' MB';
    }
    if ($bytes >= 1024) {
        return number_format($bytes / 1024, 1) . ' KB';
    }

    return $bytes . ' B';
};

$sanitizeFolderName = static function (string $name): string {
    $clean = preg_replace('/[^A-Za-z0-9 _-]/', '', trim($name)) ?? '';
    $clean = preg_replace('/\s+/', ' ', $clean) ?? '';
    return trim($clean);
};

$buildDocumentsUrl = static function (array $params = []) : string {
    $query = array_merge($_GET, $params);
    foreach ($query as $key => $value) {
        if ($value === null || $value === '') {
            unset($query[$key]);
        }
    }

    return 'documents.php' . ($query !== [] ? '?' . http_build_query($query) : '');
};

$csvEscape = static function (string $value): string {
    $escaped = str_replace('"', '""', $value);
    return '"' . $escaped . '"';
};

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string) ($_POST['documents_action'] ?? '');

    if ($action === 'create_folder') {
        $folderName = $sanitizeFolderName((string) ($_POST['folder_name'] ?? ''));
        if ($folderName === '') {
            billing_flash('documents_error', 'Folder name is required.');
            billing_redirect($buildDocumentsUrl(['modal' => 'folder']));
        }

        $folderPath = $documentRoot . DIRECTORY_SEPARATOR . $folderName;
        if (is_dir($folderPath)) {
            billing_flash('documents_error', 'That folder already exists.');
            billing_redirect($buildDocumentsUrl(['modal' => 'folder']));
        }

        if (!mkdir($folderPath, 0777, true) && !is_dir($folderPath)) {
            billing_flash('documents_error', 'Unable to create the folder.');
            billing_redirect($buildDocumentsUrl(['modal' => 'folder']));
        }

        billing_flash('documents_success', 'Folder created successfully.');
        billing_redirect('documents.php?section=allfiles&folder=' . urlencode($folderName));
    }

    if ($action === 'upload_file') {
        $targetFolder = $sanitizeFolderName((string) ($_POST['target_folder'] ?? ''));
        $targetDir = $documentRoot;

        if ($targetFolder !== '') {
            $targetDir .= DIRECTORY_SEPARATOR . $targetFolder;
            if (!is_dir($targetDir)) {
                billing_flash('documents_error', 'Selected folder does not exist.');
                billing_redirect($buildDocumentsUrl());
            }
        }

        if (!isset($_FILES['document_upload']) || (int) ($_FILES['document_upload']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
            billing_flash('documents_error', 'Please choose a file to upload.');
            billing_redirect($buildDocumentsUrl());
        }

        $originalName = basename((string) ($_FILES['document_upload']['name'] ?? 'document'));
        $safeName = preg_replace('/[^A-Za-z0-9._-]/', '-', $originalName) ?: 'document';
        $storedName = date('YmdHis') . '-' . bin2hex(random_bytes(4)) . '-' . $safeName;
        $targetPath = $targetDir . DIRECTORY_SEPARATOR . $storedName;
        $tmpPath = (string) ($_FILES['document_upload']['tmp_name'] ?? '');

        if ($tmpPath === '' || !is_uploaded_file($tmpPath) || !move_uploaded_file($tmpPath, $targetPath)) {
            billing_flash('documents_error', 'Unable to upload the selected file.');
            billing_redirect($buildDocumentsUrl());
        }

        billing_flash('documents_success', 'File uploaded successfully.');
        $redirectFolder = $targetFolder !== '' ? $targetFolder : null;
        billing_redirect($buildDocumentsUrl(['section' => $targetFolder === '' ? 'inbox' : 'allfiles', 'folder' => $redirectFolder]));
    }

    if ($action === 'save_custom_view') {
        $viewName = trim((string) ($_POST['view_name'] ?? ''));
        $favorite = !empty($_POST['favorite']) ? 1 : 0;
        $visibility = (string) ($_POST['visibility'] ?? 'only_me');
        $criteriaField = strtolower(trim((string) ($_POST['criteria_field'] ?? '')));
        $criteriaComparator = strtolower(trim((string) ($_POST['criteria_comparator'] ?? '')));
        $criteriaValue = trim((string) ($_POST['criteria_value'] ?? ''));
        $selectedColumns = $_POST['selected_columns'] ?? $defaultDocumentColumns;

        if ($viewName === '') {
            billing_flash('documents_error', 'Custom view name is required.');
            billing_redirect($buildDocumentsUrl(['modal' => 'custom-view']));
        }

        $allowedVisibility = ['only_me', 'selected_roles', 'everyone'];
        if (!in_array($visibility, $allowedVisibility, true)) {
            $visibility = 'only_me';
        }

        if ($criteriaField !== '' && !isset($documentFilterFields[$criteriaField])) {
            $criteriaField = '';
        }

        if ($criteriaComparator !== '' && !isset($documentFilterComparators[$criteriaComparator])) {
            $criteriaComparator = '';
        }

        if (($criteriaField !== '' || $criteriaComparator !== '' || $criteriaValue !== '') && ($criteriaField === '' || $criteriaComparator === '')) {
            billing_flash('documents_error', 'Choose a valid field and comparator for the custom view criteria.');
            billing_redirect($buildDocumentsUrl(['modal' => 'custom-view']));
        }

        if (!in_array($criteriaComparator, ['is_empty', 'is_not_empty'], true) && $criteriaField !== '' && $criteriaValue === '') {
            billing_flash('documents_error', 'Enter a value for the selected custom view criteria.');
            billing_redirect($buildDocumentsUrl(['modal' => 'custom-view']));
        }

        if (!is_array($selectedColumns)) {
            $selectedColumns = $defaultDocumentColumns;
        }

        $selectedColumns = array_values(array_unique(array_filter(array_map(static function ($column): string {
            return strtolower(trim((string) $column));
        }, $selectedColumns), static function (string $column) use ($documentColumnLabels): bool {
            return isset($documentColumnLabels[$column]);
        })));

        if ($selectedColumns === []) {
            $selectedColumns = $defaultDocumentColumns;
        }

        $slug = strtolower((string) preg_replace('/[^a-z0-9]+/', '-', $viewName));
        $slug = trim($slug, '-');
        if ($slug === '') {
            $slug = 'custom-view-' . count($_SESSION['documents_custom_views']);
        }

        $_SESSION['documents_custom_views'][$slug] = [
            'name' => $viewName,
            'favorite' => $favorite,
            'visibility' => $visibility,
            'criteria' => [
                'field' => $criteriaField,
                'comparator' => $criteriaComparator,
                'value' => $criteriaValue,
            ],
            'selected_columns' => $selectedColumns,
        ];

        billing_flash('documents_success', 'Custom view saved.');
        billing_redirect($buildDocumentsUrl([
            'section' => 'allfiles',
            'folder' => null,
            'type' => 'all',
            'view' => $slug,
            'modal' => null,
        ]));
    }
}

$section = strtolower(trim((string) ($_GET['section'] ?? 'allfiles')));
$allowedSections = ['allfiles', 'inbox', 'trash'];
if (!in_array($section, $allowedSections, true)) {
    $section = 'allfiles';
}

$selectedFolder = $sanitizeFolderName((string) ($_GET['folder'] ?? ''));
$fileTypeFilter = strtolower(trim((string) ($_GET['type'] ?? 'all')));
$selectedView = trim((string) ($_GET['view'] ?? ''));
$sortBy = strtolower(trim((string) ($_GET['sort_by'] ?? 'uploaded_on')));
$sortOrder = strtolower(trim((string) ($_GET['sort_order'] ?? 'desc')));
$customViews = $_SESSION['documents_custom_views'];
$allowedTypeFilters = ['all', 'images', 'pdf', 'docs', 'sheets', 'other'];
if (!in_array($sortBy, ['uploaded_on', 'file_name', 'uploaded_by', 'folder'], true)) {
    $sortBy = 'uploaded_on';
}
if (!in_array($sortOrder, ['asc', 'desc'], true)) {
    $sortOrder = 'desc';
}
if (!in_array($fileTypeFilter, $allowedTypeFilters, true)) {
    $fileTypeFilter = 'all';
}

$folderEntries = glob($documentRoot . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR);
$folders = [];
if (is_array($folderEntries)) {
    foreach ($folderEntries as $folderPath) {
        $folderName = basename($folderPath);
        $folderFiles = glob($folderPath . DIRECTORY_SEPARATOR . '*');
        $folderFileCount = 0;
        if (is_array($folderFiles)) {
            foreach ($folderFiles as $folderFile) {
                if (is_file($folderFile)) {
                    $folderFileCount++;
                }
            }
        }

        $folders[] = [
            'name' => $folderName,
            'count' => $folderFileCount,
            'modified_ts' => is_dir($folderPath) ? ((int) filemtime($folderPath) ?: 0) : 0,
        ];
    }
}

usort($folders, static function (array $left, array $right): int {
    return strcmp(strtolower((string) $left['name']), strtolower((string) $right['name']));
});

$allFiles = [];
$rootEntries = glob($documentRoot . DIRECTORY_SEPARATOR . '*');
if (is_array($rootEntries)) {
    foreach ($rootEntries as $entry) {
        if (!is_file($entry)) {
            continue;
        }

        $basename = basename($entry);
        $displayName = preg_replace('/^\d{14}-[a-f0-9]+-/i', '', $basename) ?: $basename;
        $ext = strtolower((string) pathinfo($displayName, PATHINFO_EXTENSION));
        $timestamp = (int) (filemtime($entry) ?: time());
        $allFiles[] = [
            'name' => $displayName,
            'stored_name' => $basename,
            'path' => $entry,
            'relative_url' => 'assets/uploads/documents/' . rawurlencode($basename),
            'folder' => '',
            'size' => (int) (filesize($entry) ?: 0),
            'ext' => strtoupper($ext !== '' ? $ext : 'FILE'),
            'ext_key' => $ext,
            'uploaded_by' => 'Me',
            'uploaded_ts' => $timestamp,
            'uploaded_on' => date('d/m/Y h:i A', $timestamp),
            'associated_to' => '',
            'details' => '',
        ];
    }
}

foreach ($folders as $folder) {
    $folderName = (string) $folder['name'];
    $folderFiles = glob($documentRoot . DIRECTORY_SEPARATOR . $folderName . DIRECTORY_SEPARATOR . '*');
    if (!is_array($folderFiles)) {
        continue;
    }

    foreach ($folderFiles as $entry) {
        if (!is_file($entry)) {
            continue;
        }

        $basename = basename($entry);
        $displayName = preg_replace('/^\d{14}-[a-f0-9]+-/i', '', $basename) ?: $basename;
        $ext = strtolower((string) pathinfo($displayName, PATHINFO_EXTENSION));
        $timestamp = (int) (filemtime($entry) ?: time());
        $allFiles[] = [
            'name' => $displayName,
            'stored_name' => $basename,
            'path' => $entry,
            'relative_url' => 'assets/uploads/documents/' . rawurlencode($folderName) . '/' . rawurlencode($basename),
            'folder' => $folderName,
            'size' => (int) (filesize($entry) ?: 0),
            'ext' => strtoupper($ext !== '' ? $ext : 'FILE'),
            'ext_key' => $ext,
            'uploaded_by' => 'Me',
            'uploaded_ts' => $timestamp,
            'uploaded_on' => date('d/m/Y h:i A', $timestamp),
            'associated_to' => '',
            'details' => '',
        ];
    }
}

$detectType = static function (string $extension): string {
    $extension = strtolower($extension);
    if (in_array($extension, ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'bmp'], true)) {
        return 'images';
    }
    if ($extension === 'pdf') {
        return 'pdf';
    }
    if (in_array($extension, ['doc', 'docx', 'txt', 'rtf'], true)) {
        return 'docs';
    }
    if (in_array($extension, ['csv', 'xls', 'xlsx'], true)) {
        return 'sheets';
    }

    return 'other';
};

foreach ($allFiles as &$file) {
    $file['type_group'] = $detectType((string) $file['ext_key']);
}
unset($file);

usort($allFiles, static function (array $left, array $right) use ($sortBy, $sortOrder): int {
    if ($sortBy === 'file_name') {
        $result = strcasecmp((string) ($left['name'] ?? ''), (string) ($right['name'] ?? ''));
    } elseif ($sortBy === 'uploaded_by') {
        $result = strcasecmp((string) ($left['uploaded_by'] ?? ''), (string) ($right['uploaded_by'] ?? ''));
    } elseif ($sortBy === 'folder') {
        $result = strcasecmp((string) ($left['folder'] ?? ''), (string) ($right['folder'] ?? ''));
    } else {
        $result = ((int) ($left['uploaded_ts'] ?? 0)) <=> ((int) ($right['uploaded_ts'] ?? 0));
    }

    return $sortOrder === 'asc' ? $result : ($result * -1);
});

$inboxFiles = array_values(array_filter($allFiles, static function (array $file): bool {
    return (string) ($file['folder'] ?? '') === '';
}));

$visibleFiles = $section === 'inbox' ? $inboxFiles : $allFiles;

if ($selectedFolder !== '') {
    $visibleFiles = array_values(array_filter($allFiles, static function (array $file) use ($selectedFolder): bool {
        return (string) ($file['folder'] ?? '') === $selectedFolder;
    }));
}

if ($fileTypeFilter !== 'all') {
    $visibleFiles = array_values(array_filter($visibleFiles, static function (array $file) use ($fileTypeFilter): bool {
        return (string) ($file['type_group'] ?? 'other') === $fileTypeFilter;
    }));
}

if ($selectedView !== '' && isset($customViews[$selectedView]['criteria']) && is_array($customViews[$selectedView]['criteria'])) {
    $criteria = $customViews[$selectedView]['criteria'];
    $criteriaField = strtolower(trim((string) ($criteria['field'] ?? '')));
    $criteriaComparator = strtolower(trim((string) ($criteria['comparator'] ?? '')));
    $criteriaValue = trim((string) ($criteria['value'] ?? ''));

    $visibleFiles = array_values(array_filter($visibleFiles, static function (array $file) use ($criteriaField, $criteriaComparator, $criteriaValue): bool {
        if ($criteriaField === '' || $criteriaComparator === '') {
            return true;
        }

        $haystack = '';
        if ($criteriaField === 'file_type') {
            $haystack = (string) ($file['type_group'] ?? '');
        } elseif ($criteriaField === 'folder') {
            $haystack = (string) ($file['folder'] ?? '');
        } elseif ($criteriaField === 'uploaded_by') {
            $haystack = (string) ($file['uploaded_by'] ?? '');
        } elseif ($criteriaField === 'file_name') {
            $haystack = (string) ($file['name'] ?? '');
        }

        $left = strtolower(trim($haystack));
        $right = strtolower(trim($criteriaValue));

        if ($criteriaComparator === 'is') {
            return $left === $right;
        }
        if ($criteriaComparator === 'is_not') {
            return $left !== $right;
        }
        if ($criteriaComparator === 'contains') {
            return $right === '' ? true : strpos($left, $right) !== false;
        }
        if ($criteriaComparator === 'not_contains') {
            return $right === '' ? true : strpos($left, $right) === false;
        }
        if ($criteriaComparator === 'is_empty') {
            return $left === '';
        }
        if ($criteriaComparator === 'is_not_empty') {
            return $left !== '';
        }

        return true;
    }));
}

if ((string) ($_GET['export'] ?? '') !== '') {
    $exportMode = strtolower(trim((string) ($_GET['export'] ?? '')));
    $exportFiles = $exportMode === 'all' ? $allFiles : $visibleFiles;

    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="documents-' . date('Ymd-His') . '.csv"');

    echo implode(',', [
        $csvEscape('File Name'),
        $csvEscape('Uploaded By'),
        $csvEscape('Uploaded On'),
        $csvEscape('Folder'),
        $csvEscape('Type'),
        $csvEscape('Size'),
    ]) . "\r\n";

    foreach ($exportFiles as $file) {
        echo implode(',', [
            $csvEscape((string) ($file['name'] ?? '')),
            $csvEscape((string) ($file['uploaded_by'] ?? '')),
            $csvEscape((string) ($file['uploaded_on'] ?? '')),
            $csvEscape((string) ($file['folder'] ?? '')),
            $csvEscape((string) ($file['ext'] ?? '')),
            $csvEscape($formatBytes((int) ($file['size'] ?? 0))),
        ]) . "\r\n";
    }
    exit;
}

$documentCount = count($allFiles);
$inboxCount = count($inboxFiles);
$storageUsed = 0;
$latestUploadLabel = 'No uploads';
$typeCounts = [
    'images' => 0,
    'pdf' => 0,
    'docs' => 0,
    'sheets' => 0,
    'other' => 0,
];

foreach ($allFiles as $index => $file) {
    $storageUsed += (int) ($file['size'] ?? 0);
    $typeKey = (string) ($file['type_group'] ?? 'other');
    $typeCounts[$typeKey] = ($typeCounts[$typeKey] ?? 0) + 1;
    if ($index === 0) {
        $latestUploadLabel = (string) ($file['uploaded_on'] ?? 'No uploads');
    }
}

$pageTitle = $section === 'inbox' ? 'Files' : 'All Documents';
$currentUserName = (string) ($user['business_name'] ?? $user['name'] ?? preg_replace('/@.*$/', '', $billingTopbarUserLabel) ?? 'User');
$openModal = (string) ($_GET['modal'] ?? '');
$selectedFolderExists = $selectedFolder !== '' && in_array($selectedFolder, array_column($folders, 'name'), true);
if ($selectedFolder !== '' && !$selectedFolderExists) {
    $selectedFolder = '';
}

if ($selectedFolder !== '') {
    $pageTitle = $selectedFolder;
}

if ($selectedView !== '' && isset($customViews[$selectedView]['name'])) {
    $pageTitle = (string) $customViews[$selectedView]['name'];
}

$activeCustomViewCriteriaLabel = '';
if ($selectedView !== '' && isset($customViews[$selectedView]['criteria']) && is_array($customViews[$selectedView]['criteria'])) {
    $criteria = $customViews[$selectedView]['criteria'];
    $criteriaField = strtolower(trim((string) ($criteria['field'] ?? '')));
    $criteriaComparator = strtolower(trim((string) ($criteria['comparator'] ?? '')));
    $criteriaValue = trim((string) ($criteria['value'] ?? ''));

    if ($criteriaField !== '' && $criteriaComparator !== '' && isset($documentFilterFields[$criteriaField], $documentFilterComparators[$criteriaComparator])) {
        $activeCustomViewCriteriaLabel = $documentFilterFields[$criteriaField] . ' ' . $documentFilterComparators[$criteriaComparator];
        if (!in_array($criteriaComparator, ['is_empty', 'is_not_empty'], true) && $criteriaValue !== '') {
            $activeCustomViewCriteriaLabel .= ': ' . $criteriaValue;
        }
    }
}

$selectedDocumentColumns = $defaultDocumentColumns;
if ($selectedView !== '' && isset($customViews[$selectedView]['selected_columns']) && is_array($customViews[$selectedView]['selected_columns'])) {
    $selectedDocumentColumns = array_values(array_filter($customViews[$selectedView]['selected_columns'], static function ($column) use ($documentColumnLabels): bool {
        return is_string($column) && isset($documentColumnLabels[$column]);
    }));
    if ($selectedDocumentColumns === []) {
        $selectedDocumentColumns = $defaultDocumentColumns;
    }
}

$availableDocumentColumns = array_values(array_diff(array_keys($documentColumnLabels), $selectedDocumentColumns));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="<?php echo billing_escape(billing_base_href()); ?>">
<title>Documents</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;700;800&display=swap">
<link rel="stylesheet" href="Payslip_Project/assets/fontawesome/css/all.min.css">
<link rel="stylesheet" href="assets/billing.css?v=20260507-documents-zoho">
<style>
.billing-documents-page {
    --zoho-sidebar-bg: #242a43;
    --zoho-sidebar-active: #2cb47a;
    --zoho-sidebar-text: #ffffff;
    --zoho-sidebar-muted: #7f88a8;
    --zoho-border: #e6e9ef;
    --zoho-row-border: #eef1f5;
    --zoho-heading: #0f1728;
    --zoho-subtle: #6c7892;
    --zoho-bg: #f7f8fb;
    --zoho-link: #2669e8;
    --zoho-green: #22bc78;
    --zoho-shadow: 0 1px 3px rgba(16, 24, 40, 0.08), 0 10px 24px rgba(16, 24, 40, 0.06);
}

.billing-documents-page .billing-verify-strip {
    display: none;
}

.billing-documents-page .dashboard-shell.customer-shell {
    align-items: stretch;
}

.billing-documents-page .dashboard-content.billing-app-page {
    padding: 16px 14px 20px;
    background: #f6f8fb;
}

.billing-maintenance-strip {
    min-height: 58px;
    padding: 0 18px;
    border-radius: 0;
    border: 1px solid #d9eadb;
    border-top: 2px solid #2ab36b;
    background: #e9f7ef;
    color: #334155;
    font-size: 13px;
    box-shadow: none;
}

.billing-maintenance-strip a {
    color: #2669e8;
    font-weight: 500;
}

.billing-docs-legacy {
    min-height: calc(100vh - 120px);
    border: 0;
    background: #fff;
    overflow: hidden;
}

.billing-docs-panel {
    position: sticky;
    top: 0;
    min-height: calc(100vh - 120px);
    height: auto;
    padding: 24px 18px 20px;
    gap: 20px;
    background: #262d46;
    color: var(--zoho-sidebar-text);
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.billing-docs-panel-top {
    padding: 0;
}

.billing-docs-back {
    margin-bottom: 18px;
    color: #ffffff;
    font-size: 14px;
    font-weight: 500;
    opacity: 0.96;
}

.billing-docs-panel-top h1 {
    margin: 0;
    font-size: 18px;
    font-weight: 500;
    letter-spacing: 0;
    color: #fff;
}

.billing-docs-menu {
    gap: 10px;
    padding: 0;
}

.billing-docs-menu-item {
    min-height: 36px;
    padding: 0 10px;
    border: 0;
    border-radius: 10px;
    background: transparent;
    color: #fff;
    font-size: 13px;
    font-weight: 500;
    gap: 10px;
    box-shadow: none;
    transition: background-color .18s ease, color .18s ease, transform .18s ease;
}

.billing-docs-menu-item strong {
    min-width: 24px;
    height: 24px;
    margin-left: auto;
    padding: 0 8px;
    border-radius: 999px;
    background: var(--zoho-green);
    color: #fff;
    font-size: 12px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.billing-docs-menu-item.is-active {
    background: #2fb67b;
    color: #fff;
    font-weight: 600;
}

.billing-docs-menu-item:hover {
    background: rgba(255, 255, 255, 0.08);
    color: #fff;
}

.billing-docs-menu-item.is-active:hover {
    background: #2fb67b;
    transform: translateX(1px);
}

.billing-docs-folder-box {
    margin-top: 0;
    padding: 0;
    border-radius: 0;
    background: transparent;
    gap: 10px;
    flex: 1 1 auto;
    min-height: 0;
    display: flex;
    flex-direction: column;
}

.billing-docs-folder-head {
    margin-bottom: 6px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.billing-docs-folder-head span {
    font-size: 11px;
    letter-spacing: 0.06em;
    color: rgba(255, 255, 255, 0.44);
    font-weight: 500;
}

.billing-docs-folder-head-actions {
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.billing-docs-folder-head-actions a,
.billing-docs-folder-head-actions button {
    width: 24px;
    height: 24px;
    border: 0;
    border-radius: 0;
    background: transparent;
    color: #fff;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
    cursor: pointer;
    padding: 0;
    opacity: 0.95;
    transition: background-color .18s ease, opacity .18s ease, transform .18s ease;
}

.billing-docs-folder-head-actions a:hover,
.billing-docs-folder-head-actions button:hover {
    background: rgba(255, 255, 255, 0.08);
    border-radius: 6px;
    transform: translateY(-1px);
}

.billing-docs-folder-list {
    display: grid;
    gap: 4px;
    align-content: start;
    min-height: 0;
}

.billing-docs-folder-item {
    min-height: 34px;
    padding: 0;
    border-radius: 0;
    background: transparent;
    justify-content: stretch;
}

.billing-docs-folder-link {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    gap: 8px;
    width: 100%;
    text-decoration: none;
    padding: 4px 0;
    border-radius: 0;
    outline: none;
    transition: color .18s ease, transform .18s ease, opacity .18s ease;
}

.billing-docs-folder-link span {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    min-width: 0;
    color: #fff;
    font-size: 13px;
    font-weight: 500;
}

.billing-docs-folder-link:hover {
    transform: translateX(1px);
}

.billing-docs-folder-link:hover span,
.billing-docs-folder-link:hover strong {
    color: #ffffff;
}

.billing-docs-folder-link em {
    font-style: normal;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.billing-docs-folder-link strong {
    display: none;
}

.billing-docs-folder-link.is-active {
    background: rgba(43, 178, 116, 0.18);
    outline: 1px solid rgba(43, 178, 116, 0.45);
    border-radius: 8px;
    padding: 6px 10px;
    margin-left: -10px;
    margin-right: -10px;
    outline: none;
}

.billing-docs-folder-link.is-active span,
.billing-docs-folder-link.is-active strong {
    color: #ffffff;
}

.billing-docs-folder-empty {
    color: rgba(255, 255, 255, 0.72);
    font-size: 13px;
}

.billing-docs-storage {
    display: none;
}

.billing-docs-trash {
    margin-top: auto;
    padding: 0;
    min-height: 36px;
    border-radius: 0;
    color: #fff;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 10px;
    font-size: 13px;
    font-weight: 500;
    transition: background-color .18s ease, transform .18s ease;
}

.billing-docs-trash:hover {
    background: rgba(255, 255, 255, 0.08);
    border-radius: 8px;
    transform: translateX(1px);
}

.billing-docs-board {
    padding: 0;
    gap: 0;
    align-content: stretch;
    background: #fff;
    min-height: calc(100vh - 220px);
    display: grid;
    grid-template-rows: auto auto 1fr;
}

.billing-docs-content-shell {
    position: relative;
}

.billing-docs-flash {
    margin-bottom: 14px;
    padding: 10px 14px;
    border-radius: 6px;
    font-size: 13px;
    box-shadow: none;
}

.billing-docs-board-top {
    padding: 20px 24px;
    border-radius: 0;
    background: transparent;
    border-bottom: 1px solid #e6ebf2;
    box-shadow: none;
    align-items: center;
}

.billing-docs-kicker {
    display: none;
}

.billing-docs-board-top h2 {
    margin: 0;
    font-size: 20px;
    line-height: 1.1;
    color: var(--zoho-heading);
    font-weight: 700;
}

.billing-docs-actions {
    gap: 10px;
}

.billing-docs-soft-btn,
.billing-docs-primary-btn,
.billing-reports-icon-btn {
    min-height: 40px;
    padding: 0 15px;
    border-radius: 6px;
    border: 1px solid var(--zoho-border);
    background: #f4f8ff;
    color: #2c63db;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    font-weight: 500;
    font-size: 13px;
    box-shadow: none;
}

.billing-docs-primary-btn {
    min-height: 41px;
    padding: 0 17px;
    border-color: #22b36f;
    background: #21bf73;
    color: #fff;
    font-size: 13px;
}

.billing-docs-primary-btn i,
.billing-reports-icon-btn i {
    font-size: 12px;
}

.billing-reports-icon-btn {
    width: 42px;
    min-height: 41px;
    justify-content: center;
    padding: 0;
    background: #f6f6f7;
    color: #232a3a;
}

.billing-docs-filterbar {
    min-height: 56px;
    padding: 0 24px;
    border-radius: 0;
    background: transparent;
    border-bottom: 1px solid #e6ebf2;
    gap: 8px;
}

.billing-docs-filter-layout {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}

.billing-docs-filterbar span {
    color: #1d2436;
    font-size: 13px;
    font-weight: 500;
    letter-spacing: 0;
    text-transform: uppercase;
}

.billing-docs-filterbar button,
.billing-docs-filter-trigger {
    min-height: auto;
    padding: 0;
    border: 0;
    border-radius: 0;
    background: transparent;
    color: #40537b;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    cursor: pointer;
    font-size: 13px;
    font-weight: 500;
    box-shadow: none;
}

.billing-docs-filter-trigger i:last-child,
.billing-docs-filterbar button i:last-child {
    color: #2f76e4;
    font-size: 13px;
}

.billing-docs-inline-details {
    position: relative;
}

.billing-docs-inline-details > summary {
    list-style: none;
    cursor: pointer;
}

.billing-docs-inline-details > summary:focus {
    outline: none;
}

.billing-docs-inline-details > summary::-webkit-details-marker {
    display: none;
}

.billing-docs-inline-details[open] > summary {
    position: relative;
    z-index: 21;
}

.billing-docs-inline-details[open] > .billing-docs-primary-btn,
.billing-docs-inline-details[open] > .billing-reports-icon-btn,
.billing-docs-inline-details[open] > .billing-docs-filter-trigger {
    box-shadow: 0 0 0 2px rgba(71, 133, 232, 0.18);
}

.billing-docs-popover {
    width: auto;
    min-width: 250px;
    padding: 6px;
    border-radius: 8px;
    background: #fff;
    border: 1px solid #e6ebf2;
    box-shadow: var(--zoho-shadow);
}

.billing-docs-popover--menu {
    min-width: 240px;
}

.billing-docs-popover-search {
    padding: 6px;
    border-bottom: 1px solid #edf1f6;
}

.billing-docs-popover-search input {
    width: 100%;
    min-height: 40px;
    padding: 0 12px;
    border: 1px solid #d8e2ef;
    border-radius: 8px;
    font: inherit;
    font-size: 13px;
    color: #22304a;
    outline: none;
}

.billing-docs-popover-search input:focus {
    border-color: #4785e8;
    box-shadow: 0 0 0 2px rgba(71, 133, 232, 0.14);
}

.billing-docs-popover-empty {
    display: none;
    padding: 12px 14px 10px;
    color: #7b869b;
    font-size: 12px;
}

.billing-docs-title-trigger {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 6px 10px;
    margin-left: -10px;
    border-radius: 10px;
    color: inherit;
    text-decoration: none;
    cursor: pointer;
}

.billing-docs-title-trigger:hover {
    background: #f3f6fb;
}

.billing-docs-view-popover {
    min-width: 316px;
    max-width: 316px;
    padding: 0;
    overflow: hidden;
    border-radius: 14px;
}

.billing-docs-view-popover-header {
    padding: 16px 16px 10px;
    border-bottom: 1px solid #edf1f6;
    background: #fff;
}

.billing-docs-view-popover-title {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    margin: 0;
    padding: 0 2px;
    color: #0f1728;
    font-size: 15px;
    font-weight: 700;
}

.billing-docs-view-list {
    max-height: 360px;
    overflow: auto;
    padding: 8px 6px;
}

.billing-docs-view-item {
    width: 100%;
    min-height: 46px;
    padding: 0 14px;
    border: 0;
    border-radius: 10px;
    background: transparent;
    color: #334155;
    display: flex;
    align-items: center;
    justify-content: space-between;
    text-decoration: none;
    font-size: 14px;
    gap: 14px;
}

.billing-docs-view-item:hover {
    background: #f5f8fd;
}

.billing-docs-view-item.is-active {
    background: #4785e8;
    color: #fff;
}

.billing-docs-view-item-label {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.billing-docs-view-item-icon {
    color: inherit;
    opacity: 0.72;
    font-size: 14px;
}

.billing-docs-view-footer {
    padding: 14px 16px;
    border-top: 1px solid #edf1f6;
}

.billing-docs-view-create {
    color: #2563eb;
    text-decoration: none;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.billing-docs-customview-grid {
    display: grid;
    gap: 30px;
}

.billing-docs-customview-row {
    display: grid;
    grid-template-columns: minmax(0, 1fr) auto;
    gap: 28px;
    align-items: center;
}

.billing-docs-customview-box {
    border: 1px solid #e6ebf2;
    border-radius: 14px;
    padding: 20px;
}

.billing-docs-customview-criteria {
    display: grid;
    grid-template-columns: 56px repeat(3, minmax(0, 1fr)) auto auto;
    gap: 12px;
    align-items: end;
}

.billing-docs-customview-title {
    margin: 0 0 14px;
    font-size: 17px;
    color: #111827;
}

.billing-docs-customview-index {
    min-height: 42px;
    padding: 0 12px;
    border: 1px solid #d8e2ef;
    border-radius: 10px;
    background: #f8fafc;
    color: #475467;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    font-weight: 600;
}

.billing-docs-favorite-toggle {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    color: #111827;
    font-size: 15px;
    font-weight: 500;
    white-space: nowrap;
}

.billing-docs-favorite-toggle input {
    position: absolute;
    opacity: 0;
    pointer-events: none;
}

.billing-docs-favorite-toggle .favorite-star {
    width: 20px;
    height: 20px;
    color: #98a2b3;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    transition: color .18s ease, transform .18s ease;
}

.billing-docs-favorite-toggle input:checked + .favorite-star {
    color: #f59e0b;
    transform: scale(1.04);
}

.billing-docs-criteria-actions {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    min-height: 42px;
}

.billing-docs-criteria-icon {
    width: 38px;
    height: 38px;
    border: 1px solid #d8e2ef;
    border-radius: 10px;
    background: #fff;
    color: #667085;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
}

.billing-docs-add-criterion {
    margin-top: 14px;
    border: 0;
    background: transparent;
    color: #2563eb;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    font: inherit;
    font-size: 15px;
    cursor: pointer;
    padding: 0;
}

.billing-docs-columns-grid {
    display: grid;
    grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
    border: 1px solid #e6ebf2;
    border-radius: 14px;
    overflow: hidden;
    background: #fff;
}

.billing-docs-columns-panel {
    min-width: 0;
}

.billing-docs-columns-panel + .billing-docs-columns-panel {
    border-left: 1px solid #e6ebf2;
}

.billing-docs-columns-heading {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 0 16px;
    min-height: 44px;
    border-bottom: 1px solid #eef2f6;
    color: #475467;
    font-size: 12px;
    font-weight: 700;
    letter-spacing: 0.06em;
}

.billing-docs-columns-search {
    padding: 12px 16px 10px;
}

.billing-docs-columns-search input {
    width: 100%;
    min-height: 42px;
    padding: 0 14px;
    border: 1px solid #d8e2ef;
    border-radius: 10px;
    font: inherit;
    color: #22304a;
}

.billing-docs-columns-list {
    max-height: 260px;
    overflow: auto;
    padding: 6px;
}

.billing-docs-column-item {
    min-height: 42px;
    padding: 0 12px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    gap: 10px;
    color: #101828;
    font-size: 14px;
}

.billing-docs-column-item:hover {
    background: #f8fafc;
}

.billing-docs-column-grip {
    color: #98a2b3;
    font-size: 14px;
}

.billing-docs-column-item label {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    width: 100%;
    cursor: pointer;
}

.billing-docs-column-item input {
    width: 16px;
    height: 16px;
}

.billing-docs-visibility-options {
    display: flex;
    gap: 14px;
    flex-wrap: wrap;
}

.billing-docs-visibility-option {
    min-height: 40px;
    padding: 0 14px;
    border: 1px solid #d8e2ef;
    border-radius: 10px;
    display: inline-flex;
    align-items: center;
    gap: 10px;
}

.billing-docs-menu-item-row {
    position: relative;
}

.billing-docs-menu-item-row > a {
    position: relative;
}

.billing-docs-submenu {
    position: absolute;
    top: 0;
    right: calc(100% + 8px);
    min-width: 200px;
    padding: 6px;
    border: 1px solid #e6ebf2;
    border-radius: 10px;
    background: #fff;
    box-shadow: var(--zoho-shadow);
    display: none;
    z-index: 25;
}

.billing-docs-menu-item-row.is-open > .billing-docs-submenu {
    display: block;
}

.billing-docs-popover-anchor {
    position: absolute;
    top: calc(100% + 4px);
    right: 0;
    z-index: 22;
}

.billing-docs-popover-anchor--left {
    left: 0;
    right: auto;
}

.billing-docs-menu-title {
    padding: 10px 10px 8px;
    color: #8b8fa1;
    font-size: 11px;
    font-weight: 700;
    letter-spacing: 0.06em;
}

.billing-docs-popover--menu button,
.billing-docs-popover--menu a {
    width: 100%;
    min-height: 42px;
    padding: 0 14px;
    border: 0;
    border-radius: 8px;
    background: transparent;
    color: #3a455e;
    display: flex;
    align-items: center;
    text-decoration: none;
    font: inherit;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    justify-content: space-between;
}

.billing-docs-popover--menu button.is-active,
.billing-docs-popover--menu a.is-active {
    background: #4685e9;
    color: #fff;
}

.billing-docs-table-card {
    background: #fff;
    border-radius: 0;
    border: 0;
    box-shadow: none;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    min-height: 0;
    margin-right: 0;
}

.billing-docs-table-head {
    padding: 10px 14px 0;
    min-height: 44px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    border-bottom: 0;
    background: #fff;
}

.billing-docs-table-tools {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    color: #73809a;
}

.billing-docs-table-tools i {
    font-size: 15px;
}

.app-table-wrap {
    flex: 1 1 auto;
    min-height: 0;
    overflow: auto;
}

.app-table.app-table--documents {
    width: 100%;
    border-collapse: collapse;
}

.app-table.app-table--documents thead th {
    padding: 0 18px;
    height: 46px;
    border-bottom: 1px solid var(--zoho-border);
    background: #fbfbfd;
    color: #74809a;
    font-size: 11px;
    font-weight: 700;
    letter-spacing: 0;
    text-align: left;
    white-space: nowrap;
}

.app-table.app-table--documents tbody td {
    padding: 0 18px;
    height: 50px;
    border-bottom: 1px solid var(--zoho-row-border);
    background: #fff;
    color: #1d2436;
    font-size: 13px;
    vertical-align: middle;
}

.app-table.app-table--documents tbody tr:hover td {
    background: #fafbfd;
}

.app-table.app-table--documents thead th:first-child,
.app-table.app-table--documents tbody td:first-child {
    width: 38px;
    padding-right: 0;
}

.billing-docs-file {
    gap: 12px;
}

.billing-docs-file-badge {
    min-width: 42px;
    padding: 5px 8px;
    border-radius: 999px;
    background: #eef3ff;
    color: #2c66ec;
    font-size: 11px;
    font-weight: 800;
    box-shadow: none;
    text-align: center;
}

.billing-docs-row-link {
    color: #1d2436;
    text-decoration: none;
    font-weight: 500;
}

.billing-docs-row-link:hover {
    color: var(--zoho-link);
    text-decoration: none;
}

.billing-docs-file-name {
    color: inherit;
    font-weight: 600;
    font-size: 13px;
    line-height: 1.25;
}

.billing-docs-file-sub {
    margin-top: 4px;
    color: #7c8798;
    font-size: 13px;
}

.billing-docs-empty {
    padding: 44px 24px;
    text-align: center;
    color: #607188;
}

.billing-docs-empty strong {
    display: block;
    margin-bottom: 8px;
    color: #17314f;
    font-size: 18px;
}

.billing-docs-metrics {
    margin: 20px 24px 24px;
}

.billing-docs-upload-input {
    display: none;
}

.billing-docs-modal {
    position: fixed;
    inset: 0;
    z-index: 90;
    display: grid;
    place-items: center;
    padding: 18px;
    background: rgba(25, 33, 49, 0.55);
}

.billing-docs-modal-dialog {
    width: min(625px, 100%);
    border-radius: 14px;
    background: #fff;
    box-shadow: 0 12px 32px rgba(17, 24, 39, 0.2);
    overflow: hidden;
}

.billing-docs-modal-header {
    min-height: 82px;
    padding: 0 26px;
    border-bottom: 1px solid #eceef3;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
}

.billing-docs-modal-dialog h3 {
    margin: 0;
    color: #101828;
    font-size: 22px;
    font-weight: 700;
}

.billing-docs-modal-close {
    width: 36px;
    height: 36px;
    border-radius: 999px;
    color: #667085;
    background: #fff;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    text-decoration: none;
}

.billing-docs-modal-dialog form {
    padding: 26px 26px 0;
}

.billing-docs-modal-field {
    margin-bottom: 22px;
}

.billing-docs-modal-label {
    display: block;
    margin: 0 0 10px;
    color: #ef4444;
    font-size: 14px;
    font-weight: 500;
}

.billing-docs-modal-dialog input[type="text"] {
    width: 100%;
    min-height: 46px;
    padding: 0 14px;
    border-radius: 10px;
    border: 1px solid #cbd8f0;
    outline: 0;
    font: inherit;
    color: #17314f;
    font-size: 15px;
}

.billing-docs-modal-dialog select {
    width: 100%;
    min-height: 46px;
    padding: 0 14px;
    border-radius: 10px;
    border: 1px solid #cbd8f0;
    outline: 0;
    font: inherit;
    color: #17314f;
    font-size: 15px;
    background: #fff;
}

.billing-docs-permissions {
    margin-top: 6px;
    gap: 10px;
    color: #394960;
}

.billing-docs-permissions label {
    gap: 10px;
    font-size: 15px;
}

.billing-docs-modal-custom-box {
    margin-top: 10px;
    padding: 4px;
    border: 1px solid #d7dfed;
    border-radius: 10px;
    background: #fff;
}

.billing-docs-modal-custom-box-inner {
    min-height: 38px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    padding: 0 10px;
}

.billing-docs-modal-custom-left {
    display: flex;
    align-items: center;
    gap: 6px;
    flex-wrap: wrap;
}

.billing-docs-custom-chip,
.billing-docs-custom-role {
    min-height: 34px;
    border-radius: 6px;
    background: #eef1f7;
    color: #33465e;
    font-size: 14px;
}

.billing-docs-modal-note {
    margin-top: 18px;
    padding: 14px 16px;
    border-radius: 14px;
    background: #eaf4ff;
    color: #506b91;
    line-height: 1.55;
    font-size: 14px;
}

.billing-docs-modal-note i {
    margin-right: 8px;
    color: #3d85ea;
}

.billing-docs-modal-actions {
    gap: 12px;
    margin-top: 24px;
    padding: 16px 26px 24px;
    border-top: 1px solid #eceef3;
    display: flex;
    align-items: center;
}

.billing-docs-modal-actions .billing-docs-primary-btn,
.billing-docs-modal-actions .billing-docs-soft-btn {
    min-height: 40px;
    padding: 0 20px;
    border-radius: 8px;
    font-size: 14px;
}

.billing-docs-modal-actions .billing-docs-soft-btn {
    background: #fff;
    color: #1f2937;
}

@media (max-width: 1200px) {
    .billing-docs-legacy {
        grid-template-columns: 240px minmax(0, 1fr);
    }

    .billing-docs-panel {
        width: 240px;
    }
}

@media (max-width: 900px) {
    .billing-docs-legacy {
        grid-template-columns: 1fr;
    }

    .billing-docs-panel {
        position: relative;
        width: 100%;
        min-height: auto;
        height: auto;
        padding: 18px 14px;
    }

    .billing-docs-board {
        min-height: auto;
        padding: 16px;
    }

    .billing-docs-board-top {
        flex-direction: column;
        align-items: flex-start;
        gap: 14px;
    }

    .billing-docs-folder-box {
        flex: unset;
    }

    .billing-docs-customview-row,
    .billing-docs-customview-criteria {
        grid-template-columns: 1fr;
    }

    .billing-docs-columns-grid {
        grid-template-columns: 1fr;
    }

    .billing-docs-columns-panel + .billing-docs-columns-panel {
        border-left: 0;
        border-top: 1px solid #e6ebf2;
    }
}
</style>
</head>
<body class="billing-dashboard-page billing-documents-page">
<div class="dashboard-shell customer-shell">
    <?php include dirname(__DIR__) . '/includes/app_sidebar.php'; ?>
    <div class="dashboard-main customer-main">
        <?php include dirname(__DIR__) . '/includes/topbar.php'; ?>
        <main class="dashboard-content billing-app-page">
            <div class="billing-maintenance-strip">
                <span>Planned India Data Center Maintenance on 10th May 2026 and 17th May 2026, between 06.30AM to 09.30AM IST.</span>
                <a href="reports.php">Know more</a>
            </div>

            <section class="app-screen app-screen--documents billing-docs-legacy">
                <aside class="app-doc-sidebar billing-docs-panel">
                    <div class="billing-docs-panel-top">
                        <a class="billing-docs-back" href="dashboard.php"><i class="fa-solid fa-angle-left"></i> Back</a>
                        <h1>Documents</h1>
                    </div>

                    <nav class="app-doc-nav billing-docs-menu">
                        <a href="documents.php?section=allfiles<?php echo $selectedFolder !== '' ? '&folder=' . urlencode($selectedFolder) : ''; ?>" class="app-doc-nav-link billing-docs-menu-item <?php echo $section === 'allfiles' ? 'is-active' : ''; ?>">
                            <i class="fa-regular fa-folder-open"></i>
                            <span>All Documents</span>
                        </a>
                        <a href="documents.php?section=inbox" class="app-doc-nav-link billing-docs-menu-item <?php echo $section === 'inbox' ? 'is-active' : ''; ?>">
                            <i class="fa-regular fa-folder"></i>
                            <span>Inbox</span>
                            <strong><?php echo $inboxCount; ?></strong>
                        </a>
                    </nav>

                    <section class="app-doc-folders billing-docs-folder-box">
                        <div class="app-doc-folders-head billing-docs-folder-head">
                            <span>FOLDERS</span>
                            <div class="app-doc-folders-actions billing-docs-folder-head-actions">
                                <button type="button" aria-label="Search folders"><i class="fa-solid fa-magnifying-glass"></i></button>
                                <a href="<?php echo billing_escape($buildDocumentsUrl(['modal' => 'folder'])); ?>" aria-label="Add folder"><i class="fa-solid fa-plus"></i></a>
                            </div>
                        </div>
                        <div class="billing-docs-folder-list">
                            <?php if ($folders === []): ?>
                                <div class="billing-docs-folder-empty">No folders created yet.</div>
                            <?php else: ?>
                                <?php foreach ($folders as $folder): ?>
                                    <?php $isFolderActive = $selectedFolder !== '' && $selectedFolder === (string) $folder['name']; ?>
                                    <div class="billing-docs-folder-item">
                                        <a class="app-doc-folder-item billing-docs-folder-link <?php echo $isFolderActive ? 'is-active' : ''; ?>" href="documents.php?section=allfiles&folder=<?php echo urlencode((string) $folder['name']); ?>">
                                            <span><i class="fa-regular fa-folder"></i><em><?php echo billing_escape((string) $folder['name']); ?></em></span>
                                            <strong><?php echo (int) $folder['count']; ?></strong>
                                        </a>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </section>

                    <div class="billing-docs-storage">
                        <div class="billing-docs-storage-icon"><i class="fa-solid fa-box-archive"></i></div>
                        <div>
                            <div class="billing-docs-storage-title">Storage Used</div>
                            <div class="billing-docs-storage-copy"><?php echo billing_escape($formatBytes($storageUsed)); ?> across <?php echo $documentCount; ?> files</div>
                        </div>
                    </div>

                    <a href="documents.php?section=trash" class="app-doc-trash billing-docs-trash"><i class="fa-regular fa-trash-can"></i><span>Trash</span></a>
                </aside>

                <div class="app-doc-content billing-docs-board billing-docs-content-shell">
                    <?php if ($flashSuccess !== null): ?>
                        <div class="billing-docs-flash billing-docs-flash--success"><?php echo billing_escape($flashSuccess); ?></div>
                    <?php endif; ?>
                    <?php if ($flashError !== null): ?>
                        <div class="billing-docs-flash billing-docs-flash--error"><?php echo billing_escape($flashError); ?></div>
                    <?php endif; ?>

                    <div class="app-page-heading app-page-heading--docs billing-docs-board-top">
                        <div>
                            <p class="billing-docs-kicker">Documents</p>
                            <details class="billing-docs-inline-details">
                                <summary class="billing-docs-title-trigger">
                                    <h2><?php echo billing_escape($pageTitle); ?></h2>
                                    <i class="fa-solid fa-angle-down"></i>
                                </summary>
                                <div class="billing-docs-popover billing-docs-view-popover billing-docs-popover-anchor popover-anchor--left billing-docs-popover-anchor--left">
                                    <div class="billing-docs-view-popover-header">
                                        <div class="billing-docs-view-popover-title">All Profiles <i class="fa-solid fa-angle-up"></i></div>
                                    </div>
                                    <div class="billing-docs-view-list">
                                        <a class="billing-docs-view-item <?php echo $selectedView === '' && $selectedFolder === '' && $section === 'allfiles' ? 'is-active' : ''; ?>" href="documents.php?section=allfiles" data-filter-option>
                                            <span class="billing-docs-view-item-label">All</span>
                                            <i class="fa-regular fa-star billing-docs-view-item-icon"></i>
                                        </a>
                                        <a class="billing-docs-view-item <?php echo $section === 'inbox' ? 'is-active' : ''; ?>" href="documents.php?section=inbox" data-filter-option>
                                            <span class="billing-docs-view-item-label">Inbox</span>
                                            <i class="fa-regular fa-star billing-docs-view-item-icon"></i>
                                        </a>
                                        <?php foreach ($folders as $folder): ?>
                                            <a class="billing-docs-view-item <?php echo $selectedFolder === (string) $folder['name'] ? 'is-active' : ''; ?>" href="documents.php?section=allfiles&folder=<?php echo urlencode((string) $folder['name']); ?>" data-filter-option>
                                                <span class="billing-docs-view-item-label"><?php echo billing_escape((string) $folder['name']); ?></span>
                                                <i class="fa-regular fa-star billing-docs-view-item-icon"></i>
                                            </a>
                                        <?php endforeach; ?>
                                        <?php foreach ($customViews as $viewKey => $view): ?>
                                            <a class="billing-docs-view-item <?php echo $selectedView === (string) $viewKey ? 'is-active' : ''; ?>" href="<?php echo billing_escape($buildDocumentsUrl(['section' => 'allfiles', 'folder' => null, 'type' => 'all', 'view' => $viewKey])); ?>" data-filter-option>
                                                <span class="billing-docs-view-item-label"><?php echo billing_escape((string) ($view['name'] ?? 'Custom View')); ?></span>
                                                <i class="fa-<?php echo !empty($view['favorite']) ? 'solid' : 'regular'; ?> fa-star billing-docs-view-item-icon"></i>
                                            </a>
                                        <?php endforeach; ?>
                                    </div>
                                    <div class="billing-docs-popover-empty" data-filter-empty>No matching options</div>
                                    <div class="billing-docs-view-footer">
                                        <a class="billing-docs-view-create" href="<?php echo billing_escape($buildDocumentsUrl(['modal' => 'custom-view'])); ?>">
                                            <i class="fa-solid fa-circle-plus"></i>
                                            <span>New Custom View</span>
                                        </a>
                                    </div>
                                </div>
                            </details>
                        </div>
                        <div class="app-doc-actions billing-docs-actions">
                            <?php if ($section === 'inbox'): ?>
                                <a class="billing-docs-soft-btn" href="#"><i class="fa-regular fa-copy"></i> Available Autoscans: <?php echo $inboxCount; ?></a>
                                <a class="billing-docs-soft-btn" href="#"><i class="fa-regular fa-envelope"></i> Configure</a>
                            <?php endif; ?>

                            <details class="billing-docs-inline-details">
                                <summary class="billing-docs-primary-btn">Upload File <i class="fa-solid fa-angle-down"></i></summary>
                                <div class="billing-docs-popover billing-docs-popover--menu billing-docs-popover-anchor">
                                    <button type="button" data-upload-trigger="documentUploadInput">Attach From Desktop</button>
                                    <button type="button">Attach From Cloud</button>
                                </div>
                            </details>

                            <?php if ($section === 'allfiles'): ?>
                                <details class="billing-docs-inline-details">
                                    <summary class="billing-reports-icon-btn" aria-label="More actions"><i class="fa-solid fa-ellipsis-vertical"></i></summary>
                                    <div class="billing-docs-popover billing-docs-popover--menu billing-docs-popover-anchor">
                                        <div class="billing-docs-menu-item-row" data-submenu-row>
                                            <a href="#" data-submenu-trigger>Sort by <i class="fa-solid fa-angle-right"></i></a>
                                            <div class="billing-docs-submenu">
                                                <a href="<?php echo billing_escape($buildDocumentsUrl(['sort_by' => 'uploaded_on', 'sort_order' => $sortBy === 'uploaded_on' && $sortOrder === 'desc' ? 'asc' : 'desc'])); ?>" class="<?php echo $sortBy === 'uploaded_on' ? 'is-active' : ''; ?>">Uploaded On <?php if ($sortBy === 'uploaded_on'): ?><i class="fa-solid fa-arrow-<?php echo $sortOrder === 'asc' ? 'up' : 'down'; ?>"></i><?php endif; ?></a>
                                                <a href="<?php echo billing_escape($buildDocumentsUrl(['sort_by' => 'file_name', 'sort_order' => $sortBy === 'file_name' && $sortOrder === 'desc' ? 'asc' : 'desc'])); ?>" class="<?php echo $sortBy === 'file_name' ? 'is-active' : ''; ?>">File Name</a>
                                                <a href="<?php echo billing_escape($buildDocumentsUrl(['sort_by' => 'uploaded_by', 'sort_order' => $sortBy === 'uploaded_by' && $sortOrder === 'desc' ? 'asc' : 'desc'])); ?>" class="<?php echo $sortBy === 'uploaded_by' ? 'is-active' : ''; ?>">Uploaded By</a>
                                                <a href="<?php echo billing_escape($buildDocumentsUrl(['sort_by' => 'folder', 'sort_order' => $sortBy === 'folder' && $sortOrder === 'desc' ? 'asc' : 'desc'])); ?>" class="<?php echo $sortBy === 'folder' ? 'is-active' : ''; ?>">Folder</a>
                                            </div>
                                        </div>
                                        <a href="#">Import Documents</a>
                                        <div class="billing-docs-menu-divider"></div>
                                        <div class="billing-docs-menu-item-row" data-submenu-row>
                                            <a href="#" data-submenu-trigger>Export <i class="fa-solid fa-angle-right"></i></a>
                                            <div class="billing-docs-submenu">
                                                <a href="<?php echo billing_escape($buildDocumentsUrl(['export' => 'current'])); ?>">Export Current View</a>
                                                <a href="<?php echo billing_escape($buildDocumentsUrl(['export' => 'all'])); ?>">Export All Documents</a>
                                            </div>
                                        </div>
                                        <a href="<?php echo billing_escape($buildDocumentsUrl()); ?>">Refresh List</a>
                                    </div>
                                </details>
                            <?php endif; ?>
                        </div>
                    </div>

                    <?php if ($section === 'allfiles'): ?>
                        <div class="app-doc-filterbar billing-docs-filterbar">
                            <div class="billing-docs-filter-layout">
                                <span>FILTER BY :</span>
                                <details class="billing-docs-inline-details">
                                    <summary class="billing-docs-filter-trigger">File Type: <?php echo billing_escape(ucfirst($fileTypeFilter)); ?> <i class="fa-solid fa-angle-down"></i></summary>
                                    <div class="billing-docs-popover billing-docs-popover--menu billing-docs-popover-anchor popover-anchor--left billing-docs-popover-anchor--left">
                                        <div class="billing-docs-popover-search">
                                            <input type="search" placeholder="Search" data-filter-search>
                                        </div>
                                        <a href="<?php echo billing_escape($buildDocumentsUrl(['type' => 'all'])); ?>" class="<?php echo $fileTypeFilter === 'all' ? 'is-active' : ''; ?>" data-filter-option>All</a>
                                        <a href="<?php echo billing_escape($buildDocumentsUrl(['type' => 'images'])); ?>" class="<?php echo $fileTypeFilter === 'images' ? 'is-active' : ''; ?>" data-filter-option>Images</a>
                                        <a href="<?php echo billing_escape($buildDocumentsUrl(['type' => 'pdf'])); ?>" class="<?php echo $fileTypeFilter === 'pdf' ? 'is-active' : ''; ?>" data-filter-option>PDF</a>
                                        <a href="<?php echo billing_escape($buildDocumentsUrl(['type' => 'docs'])); ?>" class="<?php echo $fileTypeFilter === 'docs' ? 'is-active' : ''; ?>" data-filter-option>Docs</a>
                                        <a href="<?php echo billing_escape($buildDocumentsUrl(['type' => 'sheets'])); ?>" class="<?php echo $fileTypeFilter === 'sheets' ? 'is-active' : ''; ?>" data-filter-option>Sheets</a>
                                        <div class="billing-docs-popover-empty" data-filter-empty>No matching options</div>
                                    </div>
                                </details>
                                <?php if ($activeCustomViewCriteriaLabel !== ''): ?>
                                    <span class="billing-docs-filter-chip is-active">Custom View: <?php echo billing_escape($activeCustomViewCriteriaLabel); ?></span>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="app-doc-filterbar billing-docs-filterbar">
                            <div class="billing-docs-filter-layout">
                                <span>FILTER BY :</span>
                                <button type="button">Status: All <i class="fa-solid fa-angle-down"></i></button>
                            </div>
                        </div>
                    <?php endif; ?>

                    <div class="billing-docs-table-card">
                        <?php if ($section === 'allfiles'): ?>
                            <div class="billing-docs-table-head">
                                <div></div>
                                <div class="billing-docs-table-tools">
                                    <i class="fa-solid fa-magnifying-glass"></i>
                                </div>
                            </div>
                        <?php endif; ?>
                        <div class="app-table-wrap">
                            <?php if ($section === 'trash'): ?>
                                <div class="billing-docs-empty">
                                    <strong>Trash is empty</strong>
                                    Deleted documents are not being tracked yet in this page.
                                </div>
                            <?php else: ?>
                                <table class="app-table app-table--documents">
                                    <thead>
                                        <tr>
                                            <th><input type="checkbox" aria-label="Select all files"></th>
                                            <?php if ($section === 'inbox'): ?>
                                                <th>FILE NAME</th>
                                                <th>DETAILS</th>
                                                <th>UPLOADED ON</th>
                                            <?php else: ?>
                                                <?php foreach ($selectedDocumentColumns as $columnKey): ?>
                                                    <?php if ($columnKey === 'file_name'): ?>
                                                        <th>FILE NAME</th>
                                                    <?php elseif (isset($documentColumnLabels[$columnKey])): ?>
                                                        <th><?php echo billing_escape(strtoupper((string) $documentColumnLabels[$columnKey])); ?></th>
                                                    <?php endif; ?>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if ($visibleFiles === []): ?>
                                            <tr>
                                                <td class="app-table-empty" colspan="<?php echo $section === 'allfiles' ? count($selectedDocumentColumns) + 1 : 4; ?>">
                                                    No documents found for this view.
                                                </td>
                                            </tr>
                                        <?php else: ?>
                                            <?php foreach ($visibleFiles as $file): ?>
                                                <tr>
                                                    <td><input type="checkbox" aria-label="Select file"></td>
                                                    <?php if ($section === 'inbox'): ?>
                                                        <td>
                                                            <div class="app-file-name billing-docs-file">
                                                                <span class="app-file-badge billing-docs-file-badge"><?php echo billing_escape((string) $file['ext']); ?></span>
                                                                <div>
                                                                    <a class="billing-docs-row-link" href="<?php echo billing_escape((string) $file['relative_url']); ?>" target="_blank" rel="noopener">
                                                                        <div class="billing-docs-file-name"><?php echo billing_escape((string) $file['name']); ?></div>
                                                                    </a>
                                                                    <div class="billing-docs-file-sub"><?php echo billing_escape($formatBytes((int) $file['size'])); ?></div>
                                                                </div>
                                                            </div>
                                                        </td>
                                                        <td></td>
                                                        <td><?php echo billing_escape((string) $file['uploaded_on']); ?></td>
                                                    <?php else: ?>
                                                        <?php foreach ($selectedDocumentColumns as $columnKey): ?>
                                                            <?php if ($columnKey === 'file_name'): ?>
                                                                <td>
                                                                    <div class="app-file-name billing-docs-file">
                                                                        <span class="app-file-badge billing-docs-file-badge"><?php echo billing_escape((string) $file['ext']); ?></span>
                                                                        <div>
                                                                            <a class="billing-docs-row-link" href="<?php echo billing_escape((string) $file['relative_url']); ?>" target="_blank" rel="noopener">
                                                                                <div class="billing-docs-file-name"><?php echo billing_escape((string) $file['name']); ?></div>
                                                                            </a>
                                                                        </div>
                                                                    </div>
                                                                </td>
                                                            <?php elseif ($columnKey === 'uploaded_by'): ?>
                                                                <td><?php echo billing_escape((string) $file['uploaded_by']); ?></td>
                                                            <?php elseif ($columnKey === 'uploaded_on'): ?>
                                                                <td><?php echo billing_escape((string) $file['uploaded_on']); ?></td>
                                                            <?php elseif ($columnKey === 'associated_to'): ?>
                                                                <td><?php echo $file['associated_to'] !== '' ? billing_escape((string) $file['associated_to']) : ''; ?></td>
                                                            <?php elseif ($columnKey === 'folder'): ?>
                                                                <td><?php echo $file['folder'] !== '' ? billing_escape((string) $file['folder']) : ''; ?></td>
                                                            <?php endif; ?>
                                                        <?php endforeach; ?>
                                                    <?php endif; ?>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="billing-docs-metrics">
                        <article class="billing-docs-metric">
                            <span>Total Files</span>
                            <strong><?php echo $documentCount; ?></strong>
                        </article>
                        <article class="billing-docs-metric">
                            <span>Latest Upload</span>
                            <strong><?php echo billing_escape($latestUploadLabel); ?></strong>
                        </article>
                        <article class="billing-docs-metric">
                            <span>Storage</span>
                            <strong><?php echo billing_escape($formatBytes($storageUsed)); ?></strong>
                        </article>
                    </div>
                </div>
            </section>

            <form id="documentUploadForm" action="documents.php" method="post" enctype="multipart/form-data">
                <input type="hidden" name="documents_action" value="upload_file">
                <input type="hidden" name="target_folder" value="<?php echo billing_escape($selectedFolder); ?>">
                <input class="billing-docs-upload-input" id="documentUploadInput" type="file" name="document_upload">
            </form>

            <?php if ($openModal === 'folder'): ?>
                <div class="billing-docs-modal">
                    <div class="billing-docs-modal-dialog">
                        <div class="billing-docs-modal-header">
                            <h3>New Folder</h3>
                            <a class="billing-docs-modal-close" href="<?php echo billing_escape($buildDocumentsUrl(['modal' => null])); ?>" aria-label="Close">&times;</a>
                        </div>
                        <form action="documents.php" method="post">
                            <input type="hidden" name="documents_action" value="create_folder">

                            <div class="billing-docs-modal-field">
                                <label class="billing-docs-modal-label" for="folder_name">Folder Name*</label>
                                <input id="folder_name" type="text" name="folder_name" required autofocus>
                            </div>

                            <div class="billing-docs-modal-field">
                                <label class="billing-docs-modal-label">Folder Permissions*</label>
                                <div class="billing-docs-permissions">
                                    <label>
                                        <input type="radio" name="folder_permission" value="all" checked>
                                        <span>All users with permission to access documents.</span>
                                    </label>
                                    <label>
                                        <input type="radio" name="folder_permission" value="custom">
                                        <span>Custom</span>
                                    </label>
                                </div>
                                <div class="billing-docs-modal-custom-box">
                                    <div class="billing-docs-modal-custom-box-inner">
                                        <div class="billing-docs-modal-custom-left">
                                            <span class="billing-docs-custom-chip"><?php echo billing_escape($currentUserName); ?> <span class="billing-docs-custom-chip-close">&times;</span></span>
                                            <span class="billing-docs-custom-role">Admin</span>
                                        </div>
                                        <i class="fa-solid fa-angle-down"></i>
                                    </div>
                                </div>
                            </div>

                            <div class="billing-docs-modal-note"><i class="fa-solid fa-circle-info"></i>By default, this folder is visible to all admins in b2lmobitech Billing and to admins in your integrated apps: b2lmobitech Books.</div>

                            <div class="billing-docs-modal-actions">
                                <button class="billing-docs-primary-btn" type="submit">Save</button>
                                <a class="billing-docs-soft-btn" href="<?php echo billing_escape($buildDocumentsUrl(['modal' => null])); ?>">Cancel</a>
                            </div>
                        </form>
                    </div>
                </div>
            <?php endif; ?>

            <?php if ($openModal === 'custom-view'): ?>
                <div class="billing-docs-modal">
                    <div class="billing-docs-modal-dialog" style="width:min(980px,100%);">
                        <div class="billing-docs-modal-header">
                            <h3>New Custom View</h3>
                            <a class="billing-docs-modal-close" href="<?php echo billing_escape($buildDocumentsUrl(['modal' => null])); ?>" aria-label="Close"><i class="fa-solid fa-xmark"></i></a>
                        </div>
                        <form action="documents.php" method="post">
                            <input type="hidden" name="documents_action" value="save_custom_view">
                            <div class="billing-docs-customview-grid">
                                <div class="billing-docs-customview-row">
                                    <div class="billing-docs-modal-field" style="margin-bottom:0;">
                                        <label class="billing-docs-modal-label" for="view_name">Name*</label>
                                        <input id="view_name" type="text" name="view_name" required autofocus>
                                    </div>
                                    <label class="billing-docs-favorite-toggle">
                                        <input type="checkbox" name="favorite" value="1">
                                        <span class="favorite-star"><i class="fa-regular fa-star"></i></span>
                                        <span>Mark as Favorite</span>
                                    </label>
                                </div>

                                <div>
                                    <h4 class="billing-docs-customview-title">Define the criteria (if any)</h4>
                                    <div class="billing-docs-customview-criteria">
                                        <div class="billing-docs-customview-index">1</div>
                                        <div class="billing-docs-modal-field" style="margin-bottom:0;">
                                            <select id="criteria_field" name="criteria_field">
                                                <option value="">Select a field</option>
                                                <?php foreach ($documentFilterFields as $fieldValue => $fieldLabel): ?>
                                                    <option value="<?php echo billing_escape($fieldValue); ?>"><?php echo billing_escape($fieldLabel); ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="billing-docs-modal-field" style="margin-bottom:0;">
                                            <select id="criteria_comparator" name="criteria_comparator">
                                                <option value="">Select a comparator</option>
                                                <?php foreach ($documentFilterComparators as $comparatorValue => $comparatorLabel): ?>
                                                    <option value="<?php echo billing_escape($comparatorValue); ?>"><?php echo billing_escape(ucfirst($comparatorLabel)); ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="billing-docs-modal-field" style="margin-bottom:0;">
                                            <input id="criteria_value" type="text" name="criteria_value" placeholder="Examples: pdf, Contracts, invoice">
                                        </div>
                                        <div class="billing-docs-criteria-actions">
                                            <span class="billing-docs-criteria-icon"><i class="fa-solid fa-plus"></i></span>
                                            <span class="billing-docs-criteria-icon"><i class="fa-regular fa-trash-can"></i></span>
                                        </div>
                                    </div>
                                    <button class="billing-docs-add-criterion" type="button"><i class="fa-solid fa-circle-plus"></i><span>Add Criterion</span></button>
                                </div>

                                <div>
                                    <h4 class="billing-docs-customview-title">Columns Preference:</h4>
                                    <div class="billing-docs-columns-grid">
                                        <div class="billing-docs-columns-panel">
                                            <div class="billing-docs-columns-heading">AVAILABLE COLUMNS</div>
                                            <div class="billing-docs-columns-search">
                                                <input type="search" placeholder="Search" data-column-search="available">
                                            </div>
                                            <div class="billing-docs-columns-list" data-column-list="available">
                                                <?php foreach ($availableDocumentColumns as $columnKey): ?>
                                                    <div class="billing-docs-column-item" data-column-option>
                                                        <label>
                                                            <i class="fa-solid fa-grip-vertical billing-docs-column-grip"></i>
                                                            <input type="checkbox" value="<?php echo billing_escape($columnKey); ?>">
                                                            <span><?php echo billing_escape((string) $documentColumnLabels[$columnKey]); ?></span>
                                                        </label>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                        <div class="billing-docs-columns-panel">
                                            <div class="billing-docs-columns-heading"><i class="fa-regular fa-circle-check"></i> SELECTED COLUMNS</div>
                                            <div class="billing-docs-columns-list" data-column-list="selected">
                                                <?php foreach ($selectedDocumentColumns as $columnKey): ?>
                                                    <div class="billing-docs-column-item" data-column-option>
                                                        <label>
                                                            <i class="fa-solid fa-grip-vertical billing-docs-column-grip"></i>
                                                            <?php if ($columnKey === 'file_name'): ?>
                                                                <input type="hidden" name="selected_columns[]" value="file_name">
                                                                <input type="checkbox" checked disabled>
                                                            <?php else: ?>
                                                                <input type="checkbox" name="selected_columns[]" value="<?php echo billing_escape($columnKey); ?>" checked>
                                                            <?php endif; ?>
                                                            <span><?php echo billing_escape((string) $documentColumnLabels[$columnKey]); ?><?php echo $columnKey === 'file_name' ? ' *' : ''; ?></span>
                                                        </label>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="billing-docs-modal-actions">
                                <button class="billing-docs-primary-btn" type="submit">Save</button>
                                <a class="billing-docs-soft-btn" href="<?php echo billing_escape($buildDocumentsUrl(['modal' => null])); ?>">Cancel</a>
                            </div>
                        </form>
                    </div>
                </div>
            <?php endif; ?>
        </main>
    </div>
</div>
<script src="assets/billing.js?v=20260507-documents-zoho"></script>
<script>
document.querySelectorAll('.billing-docs-inline-details').forEach(function (details) {
    details.addEventListener('toggle', function () {
        if (!details.open) {
            return;
        }

        document.querySelectorAll('.billing-docs-inline-details').forEach(function (other) {
            if (other !== details) {
                other.open = false;
            }
        });

        var searchInput = details.querySelector('[data-filter-search]');
        if (searchInput) {
            setTimeout(function () {
                searchInput.focus();
                searchInput.select();
            }, 0);
        }

        details.querySelectorAll('[data-submenu-row]').forEach(function (row) {
            row.classList.remove('is-open');
        });
    });
});

document.addEventListener('click', function (event) {
    document.querySelectorAll('.billing-docs-inline-details[open]').forEach(function (details) {
        if (!details.contains(event.target)) {
            details.open = false;
        }
    });
});

document.addEventListener('keydown', function (event) {
    if (event.key === 'Escape') {
        document.querySelectorAll('.billing-docs-inline-details[open]').forEach(function (details) {
            details.open = false;
        });
    }
});

document.querySelectorAll('[data-filter-search]').forEach(function (input) {
    input.addEventListener('input', function () {
        var details = input.closest('.billing-docs-inline-details');
        if (!details) {
            return;
        }

        var query = input.value.trim().toLowerCase();
        var options = details.querySelectorAll('[data-filter-option]');
        var visibleCount = 0;

        options.forEach(function (option) {
            var text = option.textContent.trim().toLowerCase();
            var match = query === '' || text.indexOf(query) !== -1;
            option.style.display = match ? '' : 'none';
            if (match) {
                visibleCount += 1;
            }
        });

        var empty = details.querySelector('[data-filter-empty]');
        if (empty) {
            empty.style.display = visibleCount === 0 ? 'block' : 'none';
        }
    });
});

document.querySelectorAll('[data-column-search]').forEach(function (input) {
    input.addEventListener('input', function () {
        var panel = input.closest('.billing-docs-columns-panel');
        if (!panel) {
            return;
        }

        var query = input.value.trim().toLowerCase();
        panel.querySelectorAll('[data-column-option]').forEach(function (option) {
            var text = option.textContent.trim().toLowerCase();
            option.style.display = query === '' || text.indexOf(query) !== -1 ? '' : 'none';
        });
    });
});

document.querySelectorAll('[data-submenu-trigger]').forEach(function (trigger) {
    trigger.addEventListener('click', function (event) {
        event.preventDefault();
        var row = trigger.closest('[data-submenu-row]');
        if (!row) {
            return;
        }

        var details = trigger.closest('.billing-docs-inline-details');
        if (!details) {
            return;
        }

        details.querySelectorAll('[data-submenu-row]').forEach(function (otherRow) {
            if (otherRow !== row) {
                otherRow.classList.remove('is-open');
            }
        });

        row.classList.toggle('is-open');
    });
});

document.addEventListener('click', function (event) {
    var trigger = event.target.closest('[data-upload-trigger]');
    if (!trigger) {
        return;
    }

    var inputId = trigger.getAttribute('data-upload-trigger');
    var input = document.getElementById(inputId);
    if (input) {
        input.click();
    }
});

var uploadInput = document.getElementById('documentUploadInput');
if (uploadInput) {
    uploadInput.addEventListener('change', function () {
        if (uploadInput.files && uploadInput.files.length > 0) {
            document.getElementById('documentUploadForm').submit();
        }
    });
}

document.querySelectorAll('.billing-docs-favorite-toggle input').forEach(function (input) {
    var star = input.parentElement ? input.parentElement.querySelector('.favorite-star i') : null;
    if (!star) {
        return;
    }

    var syncStar = function () {
        star.classList.toggle('fa-solid', input.checked);
        star.classList.toggle('fa-regular', !input.checked);
    };

    syncStar();
    input.addEventListener('change', syncStar);
});
</script>
</body>
</html>
