<?php
session_start();

require_once __DIR__ . '/../includes/helpers.php';
require_once __DIR__ . '/../includes/layout.php';
require_once __DIR__ . '/../includes/expense_shell.php';
require_once __DIR__ . '/../includes/expense_flow.php';
require_once __DIR__ . '/../includes/expense_categories.php';

if (!isset($_SESSION['authenticated'])) {
    redirect(page_url('signin'));
}

$userId = current_user_id();
if ($userId <= 0) {
    redirect(page_url('signin'));
}

expense_flow_ensure_schema();

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

    $query = http_build_query($merged);
    $url = route_url('analytics/expense_details.php');
    return $query !== '' ? $url . '?' . $query : $url;
}

function analytics_expense_details_date(?string $value): string
{
    $value = trim((string) $value);
    if ($value === '') {
        return '-';
    }

    $ts = strtotime($value);
    return $ts ? date('d/m/Y', $ts) : $value;
}

function analytics_expense_details_item_date(array $item): string
{
    $value = trim((string) ($item['expense_date'] ?? $item['created_at'] ?? ''));
    if ($value === '') {
        return '';
    }

    $timestamp = strtotime($value);
    return $timestamp ? date('Y-m-d', $timestamp) : '';
}

function analytics_expense_details_date_field_options(): array
{
    return [
        'expense_date' => 'Expense Date',
        'submitted_date' => 'Submitted Date',
        'approved_date' => 'Approved Date',
        'expense_created_date' => 'Expense Created Date',
    ];
}

function analytics_expense_details_filter_date(array $item, string $dateField): string
{
    $value = match ($dateField) {
        'submitted_date' => (string) ($item['submitted_at'] ?? ''),
        'approved_date' => (string) ($item['approved_at'] ?? ''),
        'expense_created_date' => (string) ($item['created_at'] ?? ''),
        default => (string) ($item['expense_date'] ?? $item['created_at'] ?? ''),
    };

    $value = trim($value);
    if ($value === '') {
        return '';
    }

    $timestamp = strtotime($value);
    return $timestamp ? date('Y-m-d', $timestamp) : '';
}

function analytics_expense_details_resolve_preset_range(string $preset): array
{
    $preset = strtolower(trim($preset));
    $today = new DateTimeImmutable('today');

    return match ($preset) {
        'today' => ['start' => $today->format('Y-m-d'), 'end' => $today->format('Y-m-d')],
        'yesterday' => ['start' => $today->modify('-1 day')->format('Y-m-d'), 'end' => $today->modify('-1 day')->format('Y-m-d')],
        'this_week' => ['start' => $today->modify('monday this week')->format('Y-m-d'), 'end' => $today->modify('sunday this week')->format('Y-m-d')],
        'this_month' => ['start' => $today->modify('first day of this month')->format('Y-m-d'), 'end' => $today->modify('last day of this month')->format('Y-m-d')],
        'this_quarter' => (function () use ($today): array {
            $month = (int) $today->format('n');
            $quarterStartMonth = (int) (floor(($month - 1) / 3) * 3) + 1;
            $start = $today->setDate((int) $today->format('Y'), $quarterStartMonth, 1);
            return ['start' => $start->format('Y-m-d'), 'end' => $start->modify('+2 months')->modify('last day of this month')->format('Y-m-d')];
        })(),
        'this_year' => ['start' => $today->setDate((int) $today->format('Y'), 1, 1)->format('Y-m-d'), 'end' => $today->setDate((int) $today->format('Y'), 12, 31)->format('Y-m-d')],
        'previous_week' => ['start' => $today->modify('monday last week')->format('Y-m-d'), 'end' => $today->modify('sunday last week')->format('Y-m-d')],
        'previous_month' => (function () use ($today): array {
            $start = $today->modify('first day of last month');
            return ['start' => $start->format('Y-m-d'), 'end' => $start->modify('last day of this month')->format('Y-m-d')];
        })(),
        'previous_quarter' => (function () use ($today): array {
            $month = (int) $today->format('n');
            $quarterStartMonth = (int) (floor(($month - 1) / 3) * 3) + 1;
            $currentQuarterStart = $today->setDate((int) $today->format('Y'), $quarterStartMonth, 1);
            $start = $currentQuarterStart->modify('-3 months');
            return ['start' => $start->format('Y-m-d'), 'end' => $start->modify('+2 months')->modify('last day of this month')->format('Y-m-d')];
        })(),
        'previous_year' => ['start' => $today->setDate((int) $today->format('Y') - 1, 1, 1)->format('Y-m-d'), 'end' => $today->setDate((int) $today->format('Y') - 1, 12, 31)->format('Y-m-d')],
        default => ['start' => '', 'end' => ''],
    };
}

function analytics_expense_details_payment_mode_label(array $item): string
{
    $category = strtolower(trim((string) ($item['category_name'] ?? '')));
    $description = strtolower(trim((string) ($item['description'] ?? '')));

    if ($category !== '' && str_contains($category, 'card')) {
        return 'Corporate Card';
    }

    if ($description !== '' && str_contains($description, 'card')) {
        return 'Corporate Card';
    }

    if ((int) ($item['claim_reimbursement'] ?? 1) === 0) {
        return 'Company Paid';
    }

    return 'Petty Cash';
}

function analytics_expense_details_status_label(array $item): string
{
    $reportId = (int) ($item['report_id'] ?? 0);
    $status = strtolower(trim((string) ($item['report_status'] ?? '')));

    if ($reportId <= 0) {
        return 'Unreported';
    }

    return match ($status) {
        'approved' => 'Approved',
        'awaiting_approval' => 'Submitted',
        'awaiting_reimbursement' => 'Reimbursement',
        default => 'Unsubmitted',
    };
}

function analytics_expense_details_report_code(int $reportId): string
{
    return $reportId > 0 ? 'ER-' . str_pad((string) $reportId, 5, '0', STR_PAD_LEFT) : '-';
}

function analytics_expense_details_field_options(): array
{
    return [
        'payment_mode' => 'Payment Mode',
        'description' => 'Description',
        'amount_band' => 'Expense Amount',
        'category_name' => 'Category',
        'merchant_name' => 'Merchant',
        'report_name' => 'Report',
        'status' => 'Status',
        'currency_code' => 'Currency',
        'receipt_status' => 'Receipt',
        'expense_date' => 'Expense Date',
    ];
}

function analytics_expense_details_operator_options(string $field): array
{
    return match ($field) {
        'expense_date' => [
            'on' => 'is on',
            'before' => 'is before',
            'after' => 'is after',
        ],
        'receipt_status' => [
            'is' => 'is',
            'is_not' => 'is not',
        ],
        default => [
            'is' => 'is in',
            'is_not' => 'is not in',
        ],
    };
}

function analytics_expense_details_value_options(array $items, string $field): array
{
    if ($field === 'payment_mode') {
        $options = [];
        foreach (expense_payment_picker_catalog() as $option) {
            if (($option['kind'] ?? '') === 'heading') {
                continue;
            }
            $label = trim((string) ($option['label'] ?? ''));
            if ($label !== '') {
                $options[$label] = $label;
            }
        }
        if ($options === []) {
            $options = [
                'Bank Remittance' => 'Bank Remittance',
                'Bank Transfer' => 'Bank Transfer',
                'Cash' => 'Cash',
                'Cheque' => 'Cheque',
                'Credit Card' => 'Credit Card',
                'UPI' => 'UPI',
            ];
        }
        return $options;
    }

    $options = [];
    foreach ($items as $item) {
        $value = match ($field) {
            'description' => trim((string) ($item['description'] ?? '')),
            'amount_band' => ((float) ($item['amount'] ?? 0)) > 0 ? expense_flow_format_money((float) ($item['amount'] ?? 0), (string) ($item['currency_code'] ?? 'INR')) : '',
            'category_name' => trim((string) ($item['category_name'] ?? '')) ?: 'Uncategorized',
            'merchant_name' => trim((string) ($item['merchant_name'] ?? '')) ?: 'Unknown Merchant',
            'report_name' => trim((string) ($item['report_title'] ?? '')) ?: 'Unreported',
            'status' => analytics_expense_details_status_label($item),
            'currency_code' => strtoupper(trim((string) ($item['currency_code'] ?? 'INR'))),
            'receipt_status' => trim((string) ($item['receipt_path'] ?? '')) !== '' ? 'Attached' : 'Missing',
            default => '',
        };

        if ($value === '') {
            continue;
        }
        $options[$value] = $value;
    }

    ksort($options, SORT_NATURAL | SORT_FLAG_CASE);
    return $options;
}

function analytics_expense_details_matches_criterion(array $item, string $field, string $operator, string $value): bool
{
    if ($field === '' || $operator === '' || $value === '') {
        return true;
    }

    if ($field === 'expense_date') {
        $itemDate = analytics_expense_details_item_date($item);
        if ($itemDate === '') {
            return false;
        }

        return match ($operator) {
            'on' => $itemDate === $value,
            'before' => $itemDate < $value,
            'after' => $itemDate > $value,
            default => true,
        };
    }

    $itemValue = match ($field) {
        'payment_mode' => analytics_expense_details_payment_mode_label($item),
        'description' => trim((string) ($item['description'] ?? '')),
        'amount_band' => ((float) ($item['amount'] ?? 0)) > 0 ? expense_flow_format_money((float) ($item['amount'] ?? 0), (string) ($item['currency_code'] ?? 'INR')) : '',
        'category_name' => trim((string) ($item['category_name'] ?? '')) ?: 'Uncategorized',
        'merchant_name' => trim((string) ($item['merchant_name'] ?? '')) ?: 'Unknown Merchant',
        'report_name' => trim((string) ($item['report_title'] ?? '')) ?: 'Unreported',
        'status' => analytics_expense_details_status_label($item),
        'currency_code' => strtoupper(trim((string) ($item['currency_code'] ?? 'INR'))),
        'receipt_status' => trim((string) ($item['receipt_path'] ?? '')) !== '' ? 'Attached' : 'Missing',
        default => '',
    };

    if ($operator === 'is') {
        return strcasecmp($itemValue, $value) === 0;
    }

    if ($operator === 'is_not') {
        return strcasecmp($itemValue, $value) !== 0;
    }

    return true;
}

function analytics_expense_report_groups(): array
{
    return [
        [
            'key' => 'expense',
            'title' => 'Expenses',
            'items' => [
                ['label' => 'Expense Details', 'href' => route_url('analytics/expense_details.php')],
                ['label' => 'Expenses by Customer', 'href' => route_url('analytics/expenses_by_customer.php')],
                ['label' => 'Expenses by Category', 'href' => route_url('analytics/expenses_by_category.php')],
                ['label' => 'Expenses by Attendee', 'href' => route_url('analytics/expenses_by_attendee.php')],
                ['label' => 'Expenses by Project', 'href' => route_url('analytics/expenses_by_project.php')],
                ['label' => 'Expenses by Merchant', 'href' => route_url('analytics/expenses_by_merchant.php')],
                ['label' => 'Expenses by Currency', 'href' => route_url('analytics/expenses_by_currency.php')],
            ],
        ],
        [
            'key' => 'report',
            'title' => 'Reports',
            'items' => [
                ['label' => 'Expense Reports Details', 'href' => '#'],
                ['label' => 'Policy Violations', 'href' => '#'],
            ],
        ],
        [
            'key' => 'trip',
            'title' => 'Trips',
            'items' => [
                ['label' => 'Trip Details', 'href' => '#'],
                ['label' => 'Trip Stage Summary', 'href' => '#'],
                ['label' => 'Trip Expense Summary', 'href' => '#'],
                ['label' => 'Trip Summary by Report Status', 'href' => '#'],
            ],
        ],
        [
            'key' => 'activity',
            'title' => 'Activity',
            'items' => [
                ['label' => 'Activity Logs', 'href' => '#'],
            ],
        ],
    ];
}

$datePresets = [
    'today' => 'Today',
    'yesterday' => 'Yesterday',
    'this_week' => 'This Week',
    'this_month' => 'This Month',
    'this_quarter' => 'This Quarter',
    'this_year' => 'This Year',
    'previous_week' => 'Previous Week',
    'previous_month' => 'Previous Month',
    'previous_quarter' => 'Previous Quarter',
    'previous_year' => 'Previous Year',
];

$datePreset = strtolower(trim((string) ($_GET['date_preset'] ?? 'this_month')));
if (!isset($datePresets[$datePreset])) {
    $datePreset = 'this_month';
}

$dateFieldOptions = analytics_expense_details_date_field_options();
$dateField = strtolower(trim((string) ($_GET['date_field'] ?? 'expense_date')));
if (!isset($dateFieldOptions[$dateField])) {
    $dateField = 'expense_date';
}

$showInlineFilters = isset($_GET['show_filters']) ? (string) $_GET['show_filters'] === '1' : false;
$criteriaField = trim((string) ($_GET['criteria_field'] ?? ''));
$criteriaOperator = trim((string) ($_GET['criteria_operator'] ?? ''));
$criteriaValue = trim((string) ($_GET['criteria_value'] ?? ''));

$resolvedRange = analytics_expense_details_resolve_preset_range($datePreset);
$dateStart = (string) ($resolvedRange['start'] ?? '');
$dateEnd = (string) ($resolvedRange['end'] ?? '');

$items = fetch_all(
    'SELECT
        i.id,
        i.report_id,
        i.trip_id,
        i.expense_title,
        i.merchant_name,
        i.category_name,
        i.amount,
        i.currency_code,
        i.expense_date,
        i.claim_reimbursement,
        i.description,
        i.reference_no,
        i.receipt_path,
        i.created_at,
        COALESCE(r.report_title, "") AS report_title,
        COALESCE(r.report_status, "") AS report_status,
        r.submitted_at,
        r.approved_at,
        COALESCE(t.trip_name, "") AS trip_name
     FROM expense_report_items i
     LEFT JOIN expense_reports r
       ON r.id = i.report_id
      AND r.user_id = i.user_id
      AND r.is_deleted = 0
      AND r.deleted_at IS NULL
     LEFT JOIN expense_trips t
       ON t.id = i.trip_id
      AND COALESCE(t.is_deleted, 0) = 0
     WHERE i.user_id = ?
       AND i.is_deleted = 0
       AND i.deleted_at IS NULL
     ORDER BY COALESCE(i.expense_date, i.created_at) DESC, i.id DESC',
    'i',
    [$userId]
);

$items = array_values(array_filter(
    $items,
    static function (array $item) use ($dateStart, $dateEnd, $dateField): bool {
        $itemDate = analytics_expense_details_filter_date($item, $dateField);
        if ($dateStart !== '' && ($itemDate === '' || $itemDate < $dateStart)) {
            return false;
        }

        if ($dateEnd !== '' && ($itemDate === '' || $itemDate > $dateEnd)) {
            return false;
        }

        return true;
    }
));

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

$criteriaOperators = analytics_expense_details_operator_options($criteriaField);
if ($criteriaOperator !== '' && !isset($criteriaOperators[$criteriaOperator])) {
    $criteriaOperator = '';
}

$criteriaValueOptions = analytics_expense_details_value_options($items, $criteriaField);
if ($criteriaField !== 'expense_date' && $criteriaValue !== '' && !isset($criteriaValueOptions[$criteriaValue])) {
    $criteriaValue = '';
}

$filterErrors = [];
if ($showInlineFilters && $criteriaField !== '') {
    if ($criteriaOperator === '') {
        $filterErrors[] = 'Select a comparator for criteria 1.';
    }
    if ($criteriaValue === '') {
        $filterErrors[] = 'Enter a value for criteria 1.';
    }
}

if ($criteriaField !== '' && $criteriaOperator !== '' && $criteriaValue !== '' && $filterErrors === []) {
    $items = array_values(array_filter(
        $items,
        static fn(array $item): bool => analytics_expense_details_matches_criterion($item, $criteriaField, $criteriaOperator, $criteriaValue)
    ));
}

$pageTitleRange = 'From ' . analytics_expense_details_date($dateStart) . ' To ' . analytics_expense_details_date($dateEnd);
$message = flash('expense_success');
$error = flash('expense_error');
$userContext = current_user_context();
$recipientName = trim((string) ($userContext['display_name'] ?? 'Expense user')) ?: 'Expense user';
$recipientEmail = trim((string) ($userContext['email'] ?? ''));
$recipientInitial = strtoupper(substr($recipientName !== '' ? $recipientName : 'E', 0, 1));
$criteriaValueLabel = $criteriaValue;
$scheduleDate = date('d/m/Y');
$reportGroups = analytics_expense_report_groups();
$groupByOptions = ['none' => 'None', 'report' => 'Report', 'customer' => 'Customer', 'expense_date' => 'Expense Date'];
$activeGroupBy = strtolower(trim((string) ($_GET['group_by'] ?? 'none')));
if (!array_key_exists($activeGroupBy, $groupByOptions)) {
    $activeGroupBy = 'none';
}
$shownColumns = [
    'report' => 'Report',
    'receipt' => 'Receipt',
    'payment_mode' => 'Payment Mode',
    'category' => 'Category',
    'expense_date' => 'Expense Date',
    'expense_amount' => 'Expense Amount',
    'expense_amount_fcy' => 'Expense Amount (FCY)',
];
$hiddenColumns = [
    'report_number' => 'Report#',
    'created_by' => 'Created By',
    'employee_id' => 'Employee Id',
    'paid_through' => 'Paid Through',
    'merchant' => 'Merchant',
    'expense_location' => 'Expense Location',
    'project' => 'Project',
    'project_code' => 'Project Code',
    'project_head' => 'Project Head',
    'customer' => 'Customer',
    'reference_number' => 'Reference#',
    'department' => 'Department',
    'exchange_rate' => 'Exchange Rate',
    'account_code' => 'Account Code',
];

render_expense_shell_start('Expense Details | Analytics | Expense', 'dashboard-page expense-page expense-details-report-page', 'analytics');
?>
<div class="page-surface page-surface--white expense-detail-report-shell">
    <?php if ($message !== null): ?>
        <div class="expense-banner expense-banner--success"><?= e($message) ?></div>
    <?php endif; ?>
    <?php if ($error !== null): ?>
        <div class="expense-banner expense-banner--error"><?= e($error) ?></div>
    <?php endif; ?>

    <section class="expense-report-header">
        <div class="expense-report-header-main">
            <div class="expense-report-breadcrumb-row">
                <button type="button" class="expense-report-nav-button" data-analytics-drawer-open aria-label="Open analytics navigation">
                    <i class="fa-solid fa-bars" aria-hidden="true"></i>
                </button>
                <div class="expense-report-breadcrumb">Expenses</div>
            </div>
            <h1>Expense Details <span>&bull;</span> <?= e($pageTitleRange) ?></h1>
        </div>
        <div class="expense-report-header-actions">
            <button type="button" class="expense-report-icon-button" aria-label="Schedule report" data-expense-report-schedule-open>
                <i class="fa-regular fa-clock" aria-hidden="true"></i>
            </button>
            <div class="expense-report-action-popover" data-expense-report-popover>
                <button type="button" class="expense-report-export-button" data-expense-report-popover-toggle aria-expanded="false">
                Export <i class="fa-solid fa-caret-down" aria-hidden="true"></i>
                </button>
                <div class="expense-report-export-menu" data-expense-report-popover-menu hidden>
                    <div class="expense-report-export-heading">EXPORT AS</div>
                    <button type="button" class="expense-report-export-item is-active">PDF</button>
                    <button type="button" class="expense-report-export-item">XLS (Microsoft Excel 1997-2004 Compatible)</button>
                    <button type="button" class="expense-report-export-item">XLSX (Microsoft Excel)</button>
                    <button type="button" class="expense-report-export-item">CSV (Comma Separated Value)</button>
                    <button type="button" class="expense-report-export-item">Export to Zoho Sheet</button>
                    <div class="expense-report-export-heading">PRINT</div>
                    <button type="button" class="expense-report-export-item">Print</button>
                </div>
            </div>
            <a class="expense-report-close-button" href="<?= e(page_url('analytics')) ?>" aria-label="Close">
                <i class="fa-solid fa-xmark" aria-hidden="true"></i>
            </a>
        </div>
    </section>

    <form method="get" action="<?= e(route_url('analytics/expense_details.php')) ?>" class="expense-report-toolbar-card">
        <div class="expense-report-filter-row">
            <div class="expense-report-filter-label">
                <i class="fa-solid fa-filter" aria-hidden="true"></i>
                <span>Filters :</span>
            </div>

            <label class="expense-report-select">
                <select name="date_field">
                    <?php foreach ($dateFieldOptions as $fieldValue => $fieldLabel): ?>
                        <option value="<?= e($fieldValue) ?>"<?= $dateField === $fieldValue ? ' selected' : '' ?>><?= e($fieldLabel) ?></option>
                    <?php endforeach; ?>
                </select>
                <i class="fa-solid fa-caret-down" aria-hidden="true"></i>
            </label>

            <label class="expense-report-select">
                <select name="date_preset">
                    <?php foreach ($datePresets as $presetValue => $presetLabel): ?>
                        <option value="<?= e($presetValue) ?>"<?= $datePreset === $presetValue ? ' selected' : '' ?>><?= e($presetLabel) ?></option>
                    <?php endforeach; ?>
                </select>
                <i class="fa-solid fa-caret-down" aria-hidden="true"></i>
            </label>

            <input type="hidden" name="show_filters" value="<?= $showInlineFilters ? '1' : '0' ?>" data-expense-report-show-filters>
            <button type="button" class="expense-report-outline-button" data-expense-report-toggle-filters aria-expanded="<?= $showInlineFilters ? 'true' : 'false' ?>">
                <i class="fa-solid fa-circle-plus" aria-hidden="true"></i>
                <span>More Filters</span>
            </button>

            <button type="submit" class="expense-report-primary-button">Run Report</button>
        </div>

        <section class="expense-report-more-filters<?= $showInlineFilters ? ' is-open' : '' ?>" data-expense-report-more-filters<?= $showInlineFilters ? '' : ' hidden' ?>>
            <?php if ($filterErrors !== []): ?>
                <div class="expense-report-error-box">
                    <button type="button" class="expense-report-error-close" data-expense-report-hide-errors aria-label="Dismiss errors">
                        <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                    </button>
                    <ul>
                        <?php foreach ($filterErrors as $filterError): ?>
                            <li><?= e($filterError) ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <div class="expense-report-criteria-row">
                <div class="expense-report-criteria-index">1</div>
                <div class="expense-report-criteria-when">When</div>

                <div class="expense-report-smart-select expense-report-smart-select--wide" data-report-select>
                    <input type="hidden" name="criteria_field" value="<?= e($criteriaField) ?>" data-report-select-value>
                    <button type="button" class="expense-report-smart-toggle<?= $criteriaField !== '' ? ' has-value' : '' ?>" data-report-select-toggle aria-expanded="false">
                        <span data-report-select-label><?= e($criteriaField !== '' ? ($criteriaFields[$criteriaField] ?? 'Select') : 'Select') ?></span>
                        <i class="fa-solid fa-caret-down" aria-hidden="true"></i>
                    </button>
                    <div class="expense-report-smart-menu" data-report-select-menu hidden>
                        <div class="expense-report-smart-search">
                            <i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
                            <input type="search" placeholder="Search" data-report-select-search>
                        </div>
                        <div class="expense-report-smart-list">
                            <div class="expense-report-smart-heading">Expense</div>
                            <?php foreach ($criteriaFields as $fieldValue => $fieldLabel): ?>
                                <button type="button" class="expense-report-smart-option<?= $criteriaField === $fieldValue ? ' is-selected' : '' ?>" data-report-select-option data-option-value="<?= e($fieldValue) ?>" data-option-label="<?= e($fieldLabel) ?>"><?= e($fieldLabel) ?></button>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <div class="expense-report-smart-select expense-report-smart-select--wide" data-report-select>
                    <input type="hidden" name="criteria_operator" value="<?= e($criteriaOperator) ?>" data-report-select-value>
                    <button type="button" class="expense-report-smart-toggle<?= $criteriaOperator !== '' ? ' has-value' : '' ?>" data-report-select-toggle aria-expanded="false">
                        <span data-report-select-label><?= e($criteriaOperator !== '' ? ($criteriaOperators[$criteriaOperator] ?? 'Select') : 'Select') ?></span>
                        <i class="fa-solid fa-caret-down" aria-hidden="true"></i>
                    </button>
                    <div class="expense-report-smart-menu" data-report-select-menu hidden>
                        <div class="expense-report-smart-search">
                            <i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
                            <input type="search" placeholder="Search" data-report-select-search>
                        </div>
                        <div class="expense-report-smart-list">
                            <?php foreach ($criteriaOperators as $operatorValue => $operatorLabel): ?>
                                <button type="button" class="expense-report-smart-option<?= $criteriaOperator === $operatorValue ? ' is-selected' : '' ?>" data-report-select-option data-option-value="<?= e($operatorValue) ?>" data-option-label="<?= e($operatorLabel) ?>"><?= e($operatorLabel) ?></button>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <?php if ($criteriaField === 'expense_date'): ?>
                    <label class="expense-report-date-input">
                        <input type="date" name="criteria_value" value="<?= e($criteriaValue) ?>">
                    </label>
                <?php else: ?>
                    <div class="expense-report-smart-select expense-report-smart-select--value" data-report-select>
                        <input type="hidden" name="criteria_value" value="<?= e($criteriaValue) ?>" data-report-select-value>
                        <button type="button" class="expense-report-smart-toggle expense-report-smart-toggle--tag<?= $criteriaValue !== '' ? ' has-value' : '' ?>" data-report-select-toggle aria-expanded="false">
                            <span class="expense-report-smart-tag-wrap" data-report-select-label>
                                <?php if ($criteriaValue !== ''): ?>
                                    <span class="expense-report-smart-tag"><?= e($criteriaValueLabel) ?> <i class="fa-solid fa-xmark" aria-hidden="true"></i></span>
                                <?php else: ?>
                                    <span>Select</span>
                                <?php endif; ?>
                            </span>
                            <i class="fa-solid fa-caret-down" aria-hidden="true"></i>
                        </button>
                        <div class="expense-report-smart-menu expense-report-smart-menu--value" data-report-select-menu hidden>
                            <div class="expense-report-smart-search">
                                <i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
                                <input type="search" placeholder="Search" data-report-select-search>
                            </div>
                            <div class="expense-report-smart-list">
                                <?php foreach ($criteriaValueOptions as $value => $label): ?>
                                    <button type="button" class="expense-report-smart-option<?= $criteriaValue === $value ? ' is-selected' : '' ?>" data-report-select-option data-option-value="<?= e($value) ?>" data-option-label="<?= e($label) ?>"><?= e($label) ?></button>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <a class="expense-report-remove-criteria" href="<?= e(analytics_expense_details_url([
                    'show_filters' => 1,
                    'criteria_field' => null,
                    'criteria_operator' => null,
                    'criteria_value' => null,
                ])) ?>" aria-label="Remove criteria">
                    <i class="fa-solid fa-circle-minus" aria-hidden="true"></i>
                </a>
            </div>

            <button type="button" class="expense-report-add-criteria">
                <i class="fa-solid fa-circle-plus" aria-hidden="true"></i>
                <span>Add Criteria</span>
            </button>

            <div class="expense-report-more-actions">
                <button type="submit" class="expense-report-primary-button">Run Report</button>
                <a class="expense-report-secondary-button" href="<?= e(analytics_expense_details_url([
                    'date_preset' => 'this_month',
                    'show_filters' => null,
                    'criteria_field' => null,
                    'criteria_operator' => null,
                    'criteria_value' => null,
                ])) ?>">Cancel</a>
            </div>
        </section>
    </form>

    <section class="expense-report-table-card">
        <div class="expense-report-table-tools">
            <div class="expense-report-action-popover" data-expense-report-popover>
                <button type="button" class="expense-report-table-tool" data-expense-report-popover-toggle aria-expanded="false">
                <i class="fa-regular fa-object-group" aria-hidden="true"></i>
                <span>Group by : <strong data-group-by-label><?= e($groupByOptions[$activeGroupBy]) ?></strong></span>
                <span class="expense-report-group-clear" data-group-by-clear<?= $activeGroupBy === 'none' ? ' hidden' : '' ?>>&times;</span>
                <i class="fa-solid fa-caret-down" aria-hidden="true"></i>
                </button>
                <div class="expense-report-group-menu" data-expense-report-popover-menu hidden>
                    <div class="expense-report-smart-search">
                        <i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
                        <input type="search" placeholder="Search" data-group-by-search>
                    </div>
                    <div class="expense-report-smart-list">
                        <div class="expense-report-smart-heading">Expense</div>
                        <?php foreach ($groupByOptions as $groupValue => $groupLabel): ?>
                            <?php if ($groupValue === 'none') { continue; } ?>
                            <button type="button" class="expense-report-smart-option<?= $groupValue === $activeGroupBy ? ' is-selected' : '' ?>" data-group-by-option="<?= e($groupValue) ?>" data-group-by-label-text="<?= e($groupLabel) ?>"><?= e($groupLabel) ?></button>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <button type="button" class="expense-report-table-tool" data-customize-columns-open>
                <i class="fa-regular fa-table-columns" aria-hidden="true"></i>
                <span>Customize columns</span>
                <em data-columns-count><?= count($shownColumns) ?></em>
            </button>
        </div>

        <div class="expense-report-title-block">
            <span><?= e(trim((string) ($_SESSION['user_name'] ?? $_SESSION['user_email'] ?? 'gt')) ?: 'gt') ?></span>
            <h2>Expense Details</h2>
            <p><?= e($pageTitleRange) ?></p>
        </div>

        <div class="expense-report-table-wrap">
            <table class="expense-report-table">
                <thead>
                    <tr>
                        <th data-column="report">REPORT</th>
                        <th data-column="receipt">RECEIPT</th>
                        <th data-column="payment_mode">PAYMENT MODE</th>
                        <th data-column="category">CATEGORY</th>
                        <th data-column="expense_date">EXPENSE DATE</th>
                        <th data-column="expense_amount">EXPENSE AMOUNT</th>
                        <th data-column="expense_amount_fcy">EXPENSE AMOUNT (FCY)</th>
                        <th data-column="merchant" hidden>MERCHANT</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($items === []): ?>
                        <tr>
                            <td colspan="8" class="expense-report-empty-cell">No matching expense found</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($items as $item): ?>
                            <?php
                                $reportId = (int) ($item['report_id'] ?? 0);
                                $reportTitle = trim((string) ($item['report_title'] ?? ''));
                                $receiptPath = trim((string) ($item['receipt_path'] ?? ''));
                                $categoryLabel = trim((string) ($item['category_name'] ?? '')) ?: 'Uncategorized';
                                $currencyCode = strtoupper(trim((string) ($item['currency_code'] ?? 'INR')));
                                $amount = (float) ($item['amount'] ?? 0);
                            ?>
                            <tr>
                                <td data-column="report">
                                    <div class="expense-report-report-cell">
                                        <strong><?= e($reportTitle !== '' ? $reportTitle : 'Unreported') ?></strong>
                                        <span><?= e(analytics_expense_details_report_code($reportId)) ?></span>
                                    </div>
                                </td>
                                <td data-column="receipt">
                                    <span class="expense-report-receipt-pill<?= $receiptPath !== '' ? ' has-receipt' : '' ?>">
                                        <i class="fa-solid <?= $receiptPath !== '' ? 'fa-paperclip' : 'fa-minus' ?>" aria-hidden="true"></i>
                                    </span>
                                </td>
                                <td data-column="payment_mode"><?= e(analytics_expense_details_payment_mode_label($item)) ?></td>
                                <td data-column="category"><?= e($categoryLabel) ?></td>
                                <td data-column="expense_date"><?= e(analytics_expense_details_date((string) ($item['expense_date'] ?? $item['created_at'] ?? ''))) ?></td>
                                <td data-column="expense_amount"><?= e(expense_flow_format_money($amount, 'INR')) ?></td>
                                <td data-column="expense_amount_fcy"><?= e(expense_flow_format_money($amount, $currencyCode)) ?></td>
                                <td data-column="merchant" hidden><?= e(trim((string) ($item['merchant_name'] ?? '')) ?: '-') ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </section>
</div>

<div class="expense-report-schedule-modal" data-expense-report-schedule-modal aria-hidden="true">
    <div class="expense-report-schedule-backdrop" data-expense-report-schedule-close></div>
    <section class="expense-report-schedule-panel" role="dialog" aria-modal="true" aria-labelledby="expenseScheduleTitle">
        <header class="expense-report-schedule-header">
            <h2 id="expenseScheduleTitle"><i class="fa-regular fa-clock" aria-hidden="true"></i> Schedule Report</h2>
            <button type="button" class="expense-report-schedule-close" data-expense-report-schedule-close aria-label="Close">
                <i class="fa-solid fa-xmark" aria-hidden="true"></i>
            </button>
        </header>

        <form class="expense-report-schedule-form">
            <section class="expense-report-schedule-section">
                <label class="expense-report-schedule-label">Schedule Frequency</label>
                <div class="expense-report-frequency-grid">
                    <?php foreach (['Weekly', 'Monthly', 'Quarterly', 'Yearly'] as $index => $frequency): ?>
                        <label class="expense-report-frequency-card<?= $index === 0 ? ' is-active' : '' ?>">
                            <input type="radio" name="schedule_frequency" value="<?= e(strtolower($frequency)) ?>"<?= $index === 0 ? ' checked' : '' ?>>
                            <span><?= e($frequency) ?></span>
                        </label>
                    <?php endforeach; ?>
                </div>

                <div class="expense-report-schedule-two-col">
                    <label class="expense-report-schedule-field">
                        <span>Start Date</span>
                        <input type="text" value="<?= e($scheduleDate) ?>">
                    </label>

                    <div class="expense-report-schedule-field">
                        <span>Time</span>
                        <div class="expense-report-time-row">
                            <label class="expense-report-time-select">
                                <select>
                                    <?php for ($hour = 1; $hour <= 12; $hour++): ?>
                                        <option value="<?= sprintf('%02d', $hour) ?>"<?= $hour === 6 ? ' selected' : '' ?>><?= sprintf('%02d', $hour) ?></option>
                                    <?php endfor; ?>
                                </select>
                                <i class="fa-solid fa-caret-down" aria-hidden="true"></i>
                            </label>
                            <span class="expense-report-time-sep">:</span>
                            <label class="expense-report-time-select">
                                <select>
                                    <option value="00" selected>00</option>
                                    <option value="15">15</option>
                                    <option value="30">30</option>
                                    <option value="45">45</option>
                                </select>
                                <i class="fa-solid fa-caret-down" aria-hidden="true"></i>
                            </label>
                        </div>
                        <small>06 Hours 00 Minutes</small>
                    </div>
                </div>
            </section>

            <section class="expense-report-schedule-section">
                <label class="expense-report-schedule-label expense-report-schedule-label--required">Email Recipients</label>
                <div class="expense-report-smart-select expense-report-smart-select--recipient" data-report-select>
                    <input type="hidden" value="<?= e($recipientEmail) ?>" data-report-select-value>
                    <button type="button" class="expense-report-smart-toggle" data-report-select-toggle aria-expanded="false">
                        <span data-report-select-label>Select</span>
                        <i class="fa-solid fa-caret-down" aria-hidden="true"></i>
                    </button>
                    <div class="expense-report-smart-menu expense-report-smart-menu--recipient" data-report-select-menu hidden>
                        <div class="expense-report-smart-search">
                            <i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
                            <input type="search" placeholder="Search" data-report-select-search>
                        </div>
                        <div class="expense-report-smart-list">
                            <button type="button" class="expense-report-recipient-option" data-report-select-option data-option-value="<?= e($recipientEmail) ?>" data-option-label="<?= e($recipientName) ?>">
                                <span class="expense-report-recipient-avatar"><?= e($recipientInitial) ?></span>
                                <span class="expense-report-recipient-copy">
                                    <strong><?= e($recipientName) ?></strong>
                                    <span><?= e($recipientEmail !== '' ? $recipientEmail : 'No email found') ?></span>
                                </span>
                            </button>
                        </div>
                    </div>
                </div>

                <label class="expense-report-schedule-label">Additional Recipients</label>
                <textarea rows="3" placeholder=""></textarea>
                <p class="expense-report-schedule-hint">Enter multiple email addresses, separated by commas.</p>
            </section>

            <section class="expense-report-schedule-section expense-report-schedule-attach">
                <label class="expense-report-schedule-label">Attach report as</label>
                <div class="expense-report-format-grid">
                    <?php foreach (['PDF', 'CSV', 'XLS'] as $index => $format): ?>
                        <label class="expense-report-format-card<?= $index === 0 ? ' is-active' : '' ?>">
                            <input type="radio" name="attach_format" value="<?= e(strtolower($format)) ?>"<?= $index === 0 ? ' checked' : '' ?>>
                            <span><?= e($format) ?></span>
                        </label>
                    <?php endforeach; ?>
                </div>
            </section>

            <p class="expense-report-schedule-note"><span>Note:</span> The generated report will contain a maximum of 20000 records.</p>

            <footer class="expense-report-schedule-footer">
                <button type="submit" class="expense-report-primary-button">Save</button>
                <button type="button" class="expense-report-secondary-button" data-expense-report-schedule-close>Cancel</button>
            </footer>
        </form>
    </section>
</div>

<div class="expense-report-customize-modal" data-customize-columns-modal aria-hidden="true">
    <div class="expense-report-schedule-backdrop" data-customize-columns-close></div>
    <section class="expense-report-customize-panel" role="dialog" aria-modal="true" aria-labelledby="customizeColumnsTitle">
        <header class="expense-report-schedule-header">
            <h2 id="customizeColumnsTitle">Customize columns</h2>
            <button type="button" class="expense-report-schedule-close" data-customize-columns-close aria-label="Close">
                <i class="fa-solid fa-xmark" aria-hidden="true"></i>
            </button>
        </header>
        <div class="expense-report-customize-body">
            <section class="expense-report-customize-list-wrap">
                <h3>COLUMNS HIDDEN</h3>
                <div class="expense-report-customize-box">
                    <div class="expense-report-customize-search">
                        <i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
                        <input type="search" data-customize-hidden-search>
                    </div>
                    <div class="expense-report-customize-list" data-customize-hidden-list>
                        <?php foreach ($hiddenColumns as $columnKey => $columnLabel): ?>
                            <button type="button" class="expense-report-customize-item" data-column-key="<?= e($columnKey) ?>" data-column-label="<?= e($columnLabel) ?>">
                                <span><?= e($columnLabel) ?></span>
                                <i class="fa-solid fa-plus" aria-hidden="true"></i>
                            </button>
                        <?php endforeach; ?>
                    </div>
                </div>
            </section>
            <div class="expense-report-customize-arrow">
                <i class="fa-solid fa-arrow-right" aria-hidden="true"></i>
            </div>
            <section class="expense-report-customize-list-wrap">
                <h3>COLUMNS SHOWN</h3>
                <div class="expense-report-customize-box">
                    <div class="expense-report-customize-list is-shown" data-customize-shown-list>
                        <?php foreach ($shownColumns as $columnKey => $columnLabel): ?>
                            <div class="expense-report-customize-item is-static" data-column-key="<?= e($columnKey) ?>" data-column-label="<?= e($columnLabel) ?>">
                                <span><?= e($columnLabel) ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </section>
        </div>
        <footer class="expense-report-schedule-footer expense-report-customize-footer">
            <button type="button" class="expense-report-primary-button" data-customize-columns-run>Run Report</button>
            <button type="button" class="expense-report-secondary-button" data-customize-columns-close>Close</button>
        </footer>
    </section>
</div>

<div class="expense-report-analytics-drawer" data-analytics-drawer aria-hidden="true">
    <div class="expense-report-analytics-backdrop" data-analytics-drawer-close></div>
    <aside class="expense-report-analytics-panel">
        <header class="expense-report-analytics-header">
            <h2>Analytics</h2>
            <button type="button" class="expense-report-analytics-close" data-analytics-drawer-close aria-label="Close">
                <i class="fa-solid fa-xmark" aria-hidden="true"></i>
            </button>
        </header>
        <div class="expense-report-analytics-picker">
            <button type="button" class="expense-report-analytics-picker-toggle">
                <span>Expense Details</span>
                <i class="fa-solid fa-caret-down" aria-hidden="true"></i>
            </button>
        </div>
        <nav class="expense-report-analytics-groups">
            <?php foreach ($reportGroups as $group): ?>
                <section class="expense-report-analytics-group<?= $group['key'] === 'expense' ? ' is-open' : '' ?>" data-analytics-group>
                    <button type="button" class="expense-report-analytics-group-toggle" data-analytics-group-toggle>
                        <span><i class="fa-regular fa-folder" aria-hidden="true"></i><?= e($group['title']) ?></span>
                        <i class="fa-solid fa-angle-right" aria-hidden="true"></i>
                    </button>
                    <div class="expense-report-analytics-group-list"<?= $group['key'] === 'expense' ? '' : ' hidden' ?>>
                        <?php foreach ($group['items'] as $item): ?>
                            <a class="expense-report-analytics-link<?= $item['label'] === 'Expense Details' ? ' is-active' : '' ?>" href="<?= e($item['href']) ?>">
                                <?= e($item['label']) ?>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </section>
            <?php endforeach; ?>
        </nav>
    </aside>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
  const toggleButton = document.querySelector('[data-expense-report-toggle-filters]');
  const moreFilters = document.querySelector('[data-expense-report-more-filters]');
  const showFiltersInput = document.querySelector('[data-expense-report-show-filters]');
  const errorBox = document.querySelector('.expense-report-error-box');
  const errorClose = document.querySelector('[data-expense-report-hide-errors]');
  const selectWrappers = Array.from(document.querySelectorAll('[data-report-select]'));
  const scheduleModal = document.querySelector('[data-expense-report-schedule-modal]');
  const scheduleOpen = document.querySelector('[data-expense-report-schedule-open]');
  const scheduleCloseButtons = Array.from(document.querySelectorAll('[data-expense-report-schedule-close]'));
  const scheduleForm = scheduleModal?.querySelector('form');
  const popovers = Array.from(document.querySelectorAll('[data-expense-report-popover]'));
  const customizeModal = document.querySelector('[data-customize-columns-modal]');
  const customizeOpen = document.querySelector('[data-customize-columns-open]');
  const customizeCloseButtons = Array.from(document.querySelectorAll('[data-customize-columns-close]'));
  const hiddenList = document.querySelector('[data-customize-hidden-list]');
  const shownList = document.querySelector('[data-customize-shown-list]');
  const hiddenSearch = document.querySelector('[data-customize-hidden-search]');
  const columnsCount = document.querySelector('[data-columns-count]');
  const tableColumns = Array.from(document.querySelectorAll('[data-column]'));
  const groupByLabel = document.querySelector('[data-group-by-label]');
  const groupByClear = document.querySelector('[data-group-by-clear]');
  const groupBySearch = document.querySelector('[data-group-by-search]');
  const groupByOptions = Array.from(document.querySelectorAll('[data-group-by-option]'));
  const analyticsDrawer = document.querySelector('[data-analytics-drawer]');
  const analyticsDrawerOpen = document.querySelector('[data-analytics-drawer-open]');
  const analyticsDrawerCloseButtons = Array.from(document.querySelectorAll('[data-analytics-drawer-close]'));
  const analyticsGroupToggles = Array.from(document.querySelectorAll('[data-analytics-group-toggle]'));

  const closeSelects = (except = null) => {
    selectWrappers.forEach((wrapper) => {
      if (wrapper === except) {
        return;
      }
      const toggle = wrapper.querySelector('[data-report-select-toggle]');
      const menu = wrapper.querySelector('[data-report-select-menu]');
      toggle?.setAttribute('aria-expanded', 'false');
      if (menu) {
        menu.hidden = true;
      }
    });
  };

  const closePopovers = (except = null) => {
    popovers.forEach((popover) => {
      if (popover === except) {
        return;
      }
      const toggle = popover.querySelector('[data-expense-report-popover-toggle]');
      const menu = popover.querySelector('[data-expense-report-popover-menu]');
      toggle?.setAttribute('aria-expanded', 'false');
      if (menu) {
        menu.hidden = true;
      }
    });
  };

  if (toggleButton && moreFilters && showFiltersInput) {
    toggleButton.addEventListener('click', () => {
      const open = moreFilters.hasAttribute('hidden');
      moreFilters.hidden = !open;
      moreFilters.classList.toggle('is-open', open);
      showFiltersInput.value = open ? '1' : '0';
      toggleButton.setAttribute('aria-expanded', open ? 'true' : 'false');
    });
  }

  if (errorBox && errorClose) {
    errorClose.addEventListener('click', () => {
      errorBox.style.display = 'none';
    });
  }

  popovers.forEach((popover) => {
    const toggle = popover.querySelector('[data-expense-report-popover-toggle]');
    const menu = popover.querySelector('[data-expense-report-popover-menu]');
    toggle?.addEventListener('click', (event) => {
      event.preventDefault();
      const willOpen = menu?.hidden ?? true;
      closePopovers(willOpen ? popover : null);
      if (menu) {
        menu.hidden = !willOpen;
      }
      toggle.setAttribute('aria-expanded', willOpen ? 'true' : 'false');
    });
  });

  selectWrappers.forEach((wrapper) => {
    const toggle = wrapper.querySelector('[data-report-select-toggle]');
    const menu = wrapper.querySelector('[data-report-select-menu]');
    const search = wrapper.querySelector('[data-report-select-search]');
    const valueInput = wrapper.querySelector('[data-report-select-value]');
    const label = wrapper.querySelector('[data-report-select-label]');
    const options = Array.from(wrapper.querySelectorAll('[data-report-select-option]'));

    toggle?.addEventListener('click', (event) => {
      event.preventDefault();
      const willOpen = menu?.hidden ?? true;
      closeSelects(willOpen ? wrapper : null);
      if (menu) {
        menu.hidden = !willOpen;
      }
      toggle.setAttribute('aria-expanded', willOpen ? 'true' : 'false');
      if (willOpen) {
        search?.focus();
      }
    });

    search?.addEventListener('input', () => {
      const needle = (search.value || '').trim().toLowerCase();
      options.forEach((option) => {
        const matches = needle === '' || (option.textContent || '').toLowerCase().includes(needle);
        option.hidden = !matches;
      });
    });

    options.forEach((option) => {
      option.addEventListener('click', () => {
        const nextValue = option.getAttribute('data-option-value') || '';
        const nextLabel = option.getAttribute('data-option-label') || 'Select';
        if (valueInput) {
          valueInput.value = nextValue;
        }
        if (label) {
          if (toggle?.classList.contains('expense-report-smart-toggle--tag') && nextValue !== '') {
            label.innerHTML = `<span class="expense-report-smart-tag">${nextLabel} <i class="fa-solid fa-xmark" aria-hidden="true"></i></span>`;
          } else {
            label.textContent = nextLabel;
          }
        }
        toggle?.classList.add('has-value');
        options.forEach((item) => item.classList.remove('is-selected'));
        option.classList.add('is-selected');
        closeSelects();
        if (valueInput?.getAttribute('name') === 'criteria_field') {
          wrapper.closest('form')?.submit();
        }
      });
    });
  });

  const setScheduleOpen = (open) => {
    if (!scheduleModal) {
      return;
    }
    scheduleModal.classList.toggle('is-open', open);
    scheduleModal.setAttribute('aria-hidden', open ? 'false' : 'true');
    document.body.classList.toggle('expense-report-modal-open', open);
  };

  scheduleOpen?.addEventListener('click', () => setScheduleOpen(true));
  scheduleCloseButtons.forEach((button) => {
    button.addEventListener('click', () => setScheduleOpen(false));
  });
  scheduleForm?.addEventListener('submit', (event) => {
    event.preventDefault();
    setScheduleOpen(false);
  });

  document.querySelectorAll('.expense-report-frequency-card, .expense-report-format-card').forEach((card) => {
    card.addEventListener('click', () => {
      const group = card.parentElement;
      group?.querySelectorAll('.expense-report-frequency-card, .expense-report-format-card').forEach((item) => item.classList.remove('is-active'));
      card.classList.add('is-active');
      const input = card.querySelector('input');
      if (input) {
        input.checked = true;
      }
    });
  });

  const setCustomizeOpen = (open) => {
    if (!customizeModal) {
      return;
    }
    customizeModal.classList.toggle('is-open', open);
    customizeModal.setAttribute('aria-hidden', open ? 'false' : 'true');
  };

  const syncColumns = () => {
    const shownKeys = Array.from(shownList?.querySelectorAll('[data-column-key]') || []).map((item) => item.getAttribute('data-column-key'));
    if (columnsCount) {
      columnsCount.textContent = String(shownKeys.length);
    }
    tableColumns.forEach((cell) => {
      const key = cell.getAttribute('data-column');
      cell.hidden = !shownKeys.includes(key);
    });
  };

  const syncHiddenSearch = () => {
    const needle = (hiddenSearch?.value || '').trim().toLowerCase();
    Array.from(hiddenList?.querySelectorAll('[data-column-key]') || []).forEach((item) => {
      const labelText = item.getAttribute('data-column-label') || item.textContent || '';
      item.hidden = needle !== '' && !labelText.toLowerCase().includes(needle);
    });
  };

  customizeOpen?.addEventListener('click', () => setCustomizeOpen(true));
  customizeCloseButtons.forEach((button) => {
    button.addEventListener('click', () => setCustomizeOpen(false));
  });

  hiddenList?.addEventListener('click', (event) => {
    const button = event.target.closest('[data-column-key]');
    if (!button || !shownList) {
      return;
    }
    const key = button.getAttribute('data-column-key');
    const labelText = button.getAttribute('data-column-label') || '';
    const item = document.createElement('div');
    item.className = 'expense-report-customize-item is-static';
    item.setAttribute('data-column-key', key);
    item.setAttribute('data-column-label', labelText);
    item.innerHTML = `<span>${labelText}</span>`;
    shownList.appendChild(item);
    button.remove();
    syncColumns();
    syncHiddenSearch();
  });

  hiddenSearch?.addEventListener('input', syncHiddenSearch);

  document.querySelector('[data-customize-columns-run]')?.addEventListener('click', () => {
    syncColumns();
    setCustomizeOpen(false);
  });

  groupByOptions.forEach((option) => {
    option.addEventListener('click', () => {
      const nextLabel = option.getAttribute('data-group-by-label-text') || 'None';
      if (groupByLabel) {
        groupByLabel.textContent = nextLabel;
      }
      if (groupByClear) {
        groupByClear.hidden = false;
      }
      groupByOptions.forEach((item) => item.classList.remove('is-selected'));
      option.classList.add('is-selected');
      closePopovers();
    });
  });

  groupByClear?.addEventListener('click', (event) => {
    event.stopPropagation();
    if (groupByLabel) {
      groupByLabel.textContent = 'None';
    }
    groupByClear.hidden = true;
    groupByOptions.forEach((item) => item.classList.remove('is-selected'));
  });

  groupBySearch?.addEventListener('input', () => {
    const needle = (groupBySearch.value || '').trim().toLowerCase();
    groupByOptions.forEach((option) => {
      option.hidden = needle !== '' && !(option.textContent || '').toLowerCase().includes(needle);
    });
  });

  const setAnalyticsDrawerOpen = (open) => {
    if (!analyticsDrawer) {
      return;
    }
    analyticsDrawer.classList.toggle('is-open', open);
    analyticsDrawer.setAttribute('aria-hidden', open ? 'false' : 'true');
  };

  analyticsDrawerOpen?.addEventListener('click', () => setAnalyticsDrawerOpen(true));
  analyticsDrawerCloseButtons.forEach((button) => {
    button.addEventListener('click', () => setAnalyticsDrawerOpen(false));
  });

  analyticsGroupToggles.forEach((toggle) => {
    toggle.addEventListener('click', () => {
      const section = toggle.closest('[data-analytics-group]');
      const list = section?.querySelector('.expense-report-analytics-group-list');
      const isOpen = section?.classList.contains('is-open');
      section?.classList.toggle('is-open', !isOpen);
      if (list) {
        list.hidden = isOpen;
      }
    });
  });

  document.addEventListener('click', (event) => {
    const target = event.target;
    const insideSelect = selectWrappers.some((wrapper) => wrapper.contains(target));
    if (!insideSelect) {
      closeSelects();
    }
    const insidePopover = popovers.some((popover) => popover.contains(target));
    if (!insidePopover) {
      closePopovers();
    }
  });

  syncColumns();
});
</script>
<?php render_expense_shell_end(); ?>
