<?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';

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

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

expense_flow_ensure_schema();

$pageRoute = isset($pageRoute) ? (string) $pageRoute : 'analytics/expenses_by_merchant.php';
$pageTitle = isset($pageTitle) ? (string) $pageTitle : 'Expenses by Merchant';
$groupFieldKey = isset($groupFieldKey) ? (string) $groupFieldKey : 'merchant_name';
$groupFieldLabel = isset($groupFieldLabel) ? (string) $groupFieldLabel : 'Merchant';
$groupFallback = isset($groupFallback) ? (string) $groupFallback : 'Unknown Merchant';
$summaryCountLabel = isset($summaryCountLabel) ? (string) $summaryCountLabel : 'Total Merchants';
$activeDrawerLabel = $pageTitle;
$showGraph = isset($showGraph) ? (bool) $showGraph : true;
$shownColumns = [
    'group_value' => $groupFieldLabel,
    'expense_amount' => 'Expense Amount',
    'expense_count' => 'Expense Count',
    'average_expense' => 'Average Expense',
    'top_category' => 'Top Category',
    'latest_expense_date' => 'Latest Expense Date',
];
$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',
    'trip_name' => 'Latest Trip',
];

function analytics_dimension_report_url(string $route, 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($route);
    return $query !== '' ? $url . '?' . $query : $url;
}

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

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

function analytics_dimension_report_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_dimension_report_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_dimension_report_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_dimension_report_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_dimension_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' => '#'],
            ],
        ],
    ];
}

$allowedGroupFields = ['merchant_name', 'currency_code', 'project_name', 'attendee_name'];
if (!in_array($groupFieldKey, $allowedGroupFields, true)) {
    $groupFieldKey = 'merchant_name';
}

$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_dimension_report_date_field_options();
$dateField = strtolower(trim((string) ($_GET['date_field'] ?? 'expense_date')));
if (!isset($dateFieldOptions[$dateField])) {
    $dateField = 'expense_date';
}

$resolvedRange = analytics_dimension_report_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.amount,
        i.currency_code,
        i.expense_date,
        i.created_at,
        COALESCE(NULLIF(TRIM(i.merchant_name), ""), "Unknown Merchant") AS merchant_name,
        COALESCE(NULLIF(TRIM(i.category_name), ""), "Uncategorized") AS category_name,
        COALESCE(NULLIF(TRIM(i.project_name), ""), "Unassigned Project") AS project_name,
        COALESCE(NULLIF(TRIM(i.attendee_name), ""), "Unassigned Attendee") AS attendee_name,
        COALESCE(r.report_title, "") AS report_title,
        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_dimension_report_filter_date($item, $dateField);
        if ($dateStart !== '' && ($itemDate === '' || $itemDate < $dateStart)) {
            return false;
        }

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

        return true;
    }
));

$rowsByGroup = [];
$overallExpenseAmount = 0.0;
$overallExpenseCount = count($items);

foreach ($items as $item) {
    $groupValue = trim((string) ($item[$groupFieldKey] ?? '')) ?: $groupFallback;
    $amount = (float) ($item['amount'] ?? 0);
    $overallExpenseAmount += $amount;

    if (!isset($rowsByGroup[$groupValue])) {
        $rowsByGroup[$groupValue] = [
            'group_value' => $groupValue,
            'expense_amount' => 0.0,
            'expense_count' => 0,
            'top_category_counts' => [],
            'latest_expense_date' => '',
            'latest_trip_name' => '',
        ];
    }

    $rowsByGroup[$groupValue]['expense_amount'] += $amount;
    $rowsByGroup[$groupValue]['expense_count']++;

    $categoryName = trim((string) ($item['category_name'] ?? '')) ?: 'Uncategorized';
    if (!isset($rowsByGroup[$groupValue]['top_category_counts'][$categoryName])) {
        $rowsByGroup[$groupValue]['top_category_counts'][$categoryName] = 0;
    }
    $rowsByGroup[$groupValue]['top_category_counts'][$categoryName]++;

    $itemDate = analytics_dimension_report_item_date($item);
    if ($itemDate !== '' && ($rowsByGroup[$groupValue]['latest_expense_date'] === '' || $itemDate > $rowsByGroup[$groupValue]['latest_expense_date'])) {
        $rowsByGroup[$groupValue]['latest_expense_date'] = $itemDate;
        $rowsByGroup[$groupValue]['latest_trip_name'] = trim((string) ($item['trip_name'] ?? ''));
    }
}

$groupRows = array_values($rowsByGroup);
foreach ($groupRows as &$row) {
    $row['average_amount'] = $row['expense_count'] > 0 ? $row['expense_amount'] / $row['expense_count'] : 0.0;
    arsort($row['top_category_counts']);
    $row['top_category'] = array_key_first($row['top_category_counts']) ?? 'Uncategorized';
}
unset($row);

usort(
    $groupRows,
    static function (array $left, array $right): int {
        $amountCompare = ($right['expense_amount'] <=> $left['expense_amount']);
        if ($amountCompare !== 0) {
            return $amountCompare;
        }

        return strcasecmp((string) $left['group_value'], (string) $right['group_value']);
    }
);

$topAmount = 0.0;
foreach ($groupRows as $row) {
    if ((float) $row['expense_amount'] > $topAmount) {
        $topAmount = (float) $row['expense_amount'];
    }
}

$pageTitleRange = 'From ' . analytics_dimension_report_date($dateStart) . ' To ' . analytics_dimension_report_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));
$scheduleDate = date('d/m/Y');
$reportGroups = analytics_dimension_report_groups();
$workspaceLabel = trim((string) ($_SESSION['user_name'] ?? $_SESSION['user_email'] ?? 'gt')) ?: 'gt';

render_expense_shell_start($pageTitle . ' | 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><?= e($pageTitle) ?> <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>
                    <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($pageRoute)) ?>" 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>

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

    <section class="expense-report-table-card">
        <div class="expense-report-table-tools">
            <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($workspaceLabel) ?></span>
            <h2><?= e($pageTitle) ?></h2>
            <p><?= e($pageTitleRange) ?></p>
        </div>

        <?php if ($showGraph): ?>
            <div class="expense-customer-chart-card">
                <div class="expense-chart-shell<?= $groupRows === [] ? ' is-empty' : '' ?>">
                    <div class="expense-chart-y-axis">
                        <?php foreach (['5 K', '4 K', '3 K', '2 K', '1 K', '0'] as $axisLabel): ?>
                            <span><?= e($axisLabel) ?></span>
                        <?php endforeach; ?>
                    </div>
                    <div class="expense-chart-plot">
                        <?php if ($groupRows === []): ?>
                            <div class="expense-chart-grid">
                                <?php for ($index = 0; $index < 8; $index++): ?>
                                    <div class="expense-chart-column is-placeholder">
                                        <div class="expense-chart-column-bar" style="height: 100%"></div>
                                        <span>--</span>
                                    </div>
                                <?php endfor; ?>
                            </div>
                        <?php else: ?>
                            <div class="expense-chart-grid">
                                <?php foreach (array_slice($groupRows, 0, 8) as $row): ?>
                                    <?php
                                    $height = $topAmount > 0 ? max(12, (int) round(((float) $row['expense_amount'] / $topAmount) * 100)) : 0;
                                    $chartLabel = trim((string) $row['group_value']);
                                    $chartLabel = function_exists('mb_substr') ? mb_substr($chartLabel, 0, 10) : substr($chartLabel, 0, 10);
                                    ?>
                                    <div class="expense-chart-column" title="<?= e((string) $row['group_value']) ?> - <?= e(expense_flow_format_money((float) $row['expense_amount'], 'INR')) ?>">
                                        <div class="expense-chart-column-bar" style="height: <?= e((string) $height) ?>%"></div>
                                        <span><?= e($chartLabel !== '' ? $chartLabel : '--') ?></span>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <div class="expense-report-table-wrap">
            <table class="expense-report-table">
                <thead>
                    <tr>
                        <th data-column="group_value"><?= e(strtoupper($groupFieldLabel)) ?></th>
                        <th data-column="expense_amount">EXPENSE AMOUNT</th>
                        <th data-column="expense_count">EXPENSE COUNT</th>
                        <th data-column="average_expense">AVERAGE EXPENSE</th>
                        <th data-column="top_category">TOP CATEGORY</th>
                        <th data-column="latest_expense_date">LATEST EXPENSE DATE</th>
                        <th data-column="trip_name" hidden>LATEST TRIP</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($groupRows === []): ?>
                        <tr>
                            <td colspan="6" class="expense-report-empty-cell">No matching expense found</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($groupRows as $row): ?>
                            <tr>
                                <td data-column="group_value">
                                    <div class="expense-report-report-cell">
                                        <strong><?= e((string) $row['group_value']) ?></strong>
                                        <span><?= e(trim((string) ($row['latest_trip_name'] ?? '')) !== '' ? (string) $row['latest_trip_name'] : 'No linked trip') ?></span>
                                    </div>
                                </td>
                                <td data-column="expense_amount"><?= e(expense_flow_format_money((float) $row['expense_amount'], 'INR')) ?></td>
                                <td data-column="expense_count"><?= e((string) $row['expense_count']) ?></td>
                                <td data-column="average_expense"><?= e(expense_flow_format_money((float) $row['average_amount'], 'INR')) ?></td>
                                <td data-column="top_category"><?= e((string) $row['top_category']) ?></td>
                                <td data-column="latest_expense_date"><?= e($row['latest_expense_date'] !== '' ? analytics_dimension_report_date((string) $row['latest_expense_date']) : '-') ?></td>
                                <td data-column="trip_name" hidden><?= e(trim((string) ($row['latest_trip_name'] ?? '')) !== '' ? (string) $row['latest_trip_name'] : '-') ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </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-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">
                    <button type="button" class="expense-report-smart-toggle">
                        <span><?= e($recipientName) ?></span>
                        <i class="fa-solid fa-caret-down" aria-hidden="true"></i>
                    </button>
                    <div class="expense-report-smart-menu expense-report-smart-menu--recipient" hidden>
                        <div class="expense-report-smart-list">
                            <div class="expense-report-recipient-option">
                                <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>
                            </div>
                        </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>

            <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-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><?= e($activeDrawerLabel) ?></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((string) $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'] === $activeDrawerLabel ? ' is-active' : '' ?>" href="<?= e((string) $item['href']) ?>">
                                <?= e((string) $item['label']) ?>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </section>
            <?php endforeach; ?>
        </nav>
    </aside>
</div>

<style>
.expense-customer-summary-card,
.expense-customer-chart-card {
    border: 1px solid #e3e8f4;
    border-radius: 18px;
    background: #fff;
}

.expense-customer-chart-card {
    padding: 20px 20px 8px;
    margin-bottom: 24px;
}

.expense-chart-shell {
    display: grid;
    grid-template-columns: 56px minmax(0, 1fr);
    gap: 16px;
    min-height: 340px;
}

.expense-chart-y-axis {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: flex-end;
    padding: 8px 0 32px;
    color: #5f6f8e;
    font-size: 13px;
}

.expense-chart-plot {
    position: relative;
    min-height: 320px;
    border-left: 1px solid #edf1f8;
    border-bottom: 1px solid #edf1f8;
    background-image: linear-gradient(to top, rgba(233, 239, 250, 0.75) 1px, transparent 1px);
    background-size: 100% 20%;
}

.expense-chart-grid {
    height: 100%;
    display: grid;
    grid-template-columns: repeat(8, minmax(48px, 1fr));
    align-items: end;
    gap: 18px;
    padding: 0 18px 32px;
}

.expense-chart-column {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: end;
    align-items: center;
    gap: 10px;
}

.expense-chart-column-bar {
    width: 100%;
    min-height: 12px;
    border-radius: 14px 14px 0 0;
    background: linear-gradient(180deg, #dfe8ff 0%, #8cb0ff 100%);
}

.expense-chart-column.is-placeholder .expense-chart-column-bar {
    background: rgba(233, 239, 250, 0.92);
}

.expense-chart-column span {
    color: #263858;
    font-size: 12px;
    line-height: 1;
    text-align: center;
}

@media (max-width: 900px) {
    .expense-chart-shell {
        grid-template-columns: 40px minmax(0, 1fr);
        gap: 10px;
        min-height: 260px;
    }

    .expense-chart-plot {
        min-height: 240px;
    }

    .expense-chart-grid {
        gap: 10px;
        padding: 0 10px 28px;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', () => {
  const popovers = Array.from(document.querySelectorAll('[data-expense-report-popover]'));
  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 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 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 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;
      }
    });
  };

  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');
    });
  });

  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').forEach((card) => {
    card.addEventListener('click', () => {
      const group = card.parentElement;
      group?.querySelectorAll('.expense-report-frequency-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);
  });

  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 insidePopover = popovers.some((popover) => popover.contains(target));
    if (!insidePopover) {
      closePopovers();
    }
  });

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