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

billing_require_auth();
billing_ensure_expense_support();

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

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

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

if (!isset($_SESSION['expense_custom_views']) || !is_array($_SESSION['expense_custom_views'])) {
    $_SESSION['expense_custom_views'] = [];
}

$billingActiveNav = 'expenses';
$billingTopbarOrganizationName = (string) ($organization['organization_name'] ?? 'Billing');
$billingTopbarUserLabel = (string) ($user['email'] ?? '');

$buildExpenseUrl = static function (array $changes = []): string {
    $query = $_GET;
    foreach ($changes as $key => $value) {
        if ($value === null || $value === '') {
            unset($query[$key]);
        } else {
            $query[$key] = $value;
        }
    }

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

$normalizeExpenseFilterKey = static function (string $value): string {
    $value = strtolower(trim($value));
    if ($value === '') {
        return 'all';
    }
    if (strpos($value, 'status.') === 0) {
        $value = substr($value, 7);
    }
    return str_replace(['_', '-'], ' ', $value);
};

$expenseStatusViews = [
    'all' => 'All',
    'unbilled' => 'Unbilled',
    'invoiced' => 'Invoiced',
    'reimbursed' => 'Reimbursed',
    'billable' => 'Billable',
    'non billable' => 'Non-Billable',
    'with receipts' => 'With Receipts',
    'without receipts' => 'Without Receipts',
    'from zoho expense' => 'From Zoho Expense',
];

$criteriaFieldOptions = [
    'status' => 'Status',
    'expense_account' => 'Expense Account',
    'reference_number' => 'Reference#',
    'customer_name' => 'Customer Name',
    'amount' => 'Amount',
];

$criteriaComparatorOptions = [
    'is' => 'is',
    'is_not' => 'is not',
    'contains' => 'contains',
    'not_contains' => 'does not contain',
    'greater_than' => 'is greater than',
    'less_than' => 'is less than',
];

$availableColumns = [
    'reference_number' => 'Reference#',
    'report_name' => 'Report Name',
    'report_number' => 'Report Number',
    'customer_name' => 'Customer Name',
    'status' => 'Status',
];

$selectedColumns = [
    'date' => 'Date *',
    'expense_account' => 'Expense Account *',
    'amount' => 'Amount *',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string) ($_POST['expense_action'] ?? '') === 'upload_desktop') {
    $uploadedFiles = billing_store_uploaded_files('expense_receipts', 'expense_receipts');
    if ($uploadedFiles !== []) {
        $_SESSION['billing_pending_expense_attachments'] = $uploadedFiles;
    }
    billing_redirect('expense_new.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string) ($_POST['expense_action'] ?? '') === 'save_custom_view') {
    $viewName = trim((string) ($_POST['view_name'] ?? ''));
    $favorite = !empty($_POST['favorite']) ? 1 : 0;
    $visibility = (string) ($_POST['visibility'] ?? 'only_me');
    $criteriaField = strtolower(trim((string) ($_POST['criteria_field'] ?? '')));
    $criteriaComparator = strtolower(trim((string) ($_POST['criteria_comparator'] ?? '')));
    $criteriaValue = trim((string) ($_POST['criteria_value'] ?? ''));

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

    if ($criteriaField !== '' && !isset($criteriaFieldOptions[$criteriaField])) {
        $criteriaField = '';
    }
    if ($criteriaComparator !== '' && !isset($criteriaComparatorOptions[$criteriaComparator])) {
        $criteriaComparator = '';
    }
    if (($criteriaField !== '' || $criteriaComparator !== '' || $criteriaValue !== '') && ($criteriaField === '' || $criteriaComparator === '')) {
        billing_flash('error', 'Choose a valid field and comparator for the custom view.');
        billing_redirect($buildExpenseUrl(['modal' => 'custom-view']));
    }
    if (in_array($criteriaComparator, ['is', 'is_not', 'contains', 'not_contains', 'greater_than', 'less_than'], true) && $criteriaField !== '' && $criteriaValue === '') {
        billing_flash('error', 'Enter a value for the selected criterion.');
        billing_redirect($buildExpenseUrl(['modal' => 'custom-view']));
    }

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

    $_SESSION['expense_custom_views'][$slug] = [
        'name' => $viewName,
        'favorite' => $favorite,
        'visibility' => in_array($visibility, ['only_me', 'selected_roles', 'everyone'], true) ? $visibility : 'only_me',
        'criteria' => [
            'field' => $criteriaField,
            'comparator' => $criteriaComparator,
            'value' => $criteriaValue,
        ],
    ];

    billing_flash('success', 'Custom view saved.');
    billing_redirect($buildExpenseUrl(['view' => $slug, 'filter_by' => null, 'modal' => null]));
}

$expenses = billing_get_expenses((int) $user['id'], (int) $organization['id']);
usort($expenses, static function (array $left, array $right): int {
    $leftDate = (string) ($left['created_at'] ?? $left['expense_date'] ?? '');
    $rightDate = (string) ($right['created_at'] ?? $right['expense_date'] ?? '');
    return strcmp($rightDate, $leftDate);
});

$customViews = $_SESSION['expense_custom_views'];
$selectedFilter = $normalizeExpenseFilterKey((string) ($_GET['filter_by'] ?? 'all'));
$selectedView = trim((string) ($_GET['view'] ?? ''));
$openModal = (string) ($_GET['modal'] ?? '');
$flashSuccess = billing_flash('success');
$flashError = billing_flash('error');

$matchesExpenseFilter = static function (array $expense, string $filterKey) use ($normalizeExpenseFilterKey): bool {
    if ($filterKey === 'all') {
        return true;
    }

    $status = $normalizeExpenseFilterKey((string) ($expense['status_label'] ?? ''));
    $hasAttachment = !empty($expense['attachments']);

    return match ($filterKey) {
        'non billable' => $status === 'non billable',
        'billable' => $status === 'billable',
        'unbilled' => $status === 'unbilled',
        'invoiced' => $status === 'invoiced',
        'reimbursed' => $status === 'reimbursed',
        'with receipts' => $hasAttachment,
        'without receipts' => !$hasAttachment,
        'from zoho expense' => false,
        default => $status === $filterKey,
    };
};

$expenseFieldValue = static function (array $expense, string $field) use ($normalizeExpenseFilterKey) {
    return match ($field) {
        'status' => $normalizeExpenseFilterKey((string) ($expense['status_label'] ?? '')),
        'expense_account' => strtolower(trim((string) (($expense['expense_account'] ?? '') !== '' ? $expense['expense_account'] : ($expense['category_name'] ?? '')))),
        'reference_number' => strtolower(trim((string) ($expense['reference_number'] ?? ''))),
        'customer_name' => strtolower(trim((string) ($expense['customer_name'] ?? ''))),
        'amount' => (float) ($expense['total_amount'] ?? 0),
        default => '',
    };
};

$visibleExpenses = array_values(array_filter($expenses, static function (array $expense) use ($selectedFilter, $matchesExpenseFilter): bool {
    return $matchesExpenseFilter($expense, $selectedFilter);
}));

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

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

        $actual = $expenseFieldValue($expense, $criteriaField);
        if ($criteriaField === 'amount') {
            $left = (float) $actual;
            $right = (float) $criteriaValue;
            return match ($criteriaComparator) {
                'is' => $left === $right,
                'is_not' => $left !== $right,
                'greater_than' => $left > $right,
                'less_than' => $left < $right,
                default => true,
            };
        }

        $left = (string) $actual;
        return match ($criteriaComparator) {
            'is' => $left === $criteriaValue,
            'is_not' => $left !== $criteriaValue,
            'contains' => $criteriaValue === '' ? true : strpos($left, $criteriaValue) !== false,
            'not_contains' => $criteriaValue === '' ? true : strpos($left, $criteriaValue) === false,
            default => true,
        };
    }));

    if ($criteriaField !== '' && $criteriaComparator !== '' && isset($criteriaFieldOptions[$criteriaField], $criteriaComparatorOptions[$criteriaComparator])) {
        $activeCustomViewCriteriaLabel = $criteriaFieldOptions[$criteriaField] . ' ' . $criteriaComparatorOptions[$criteriaComparator];
        if ($criteriaValue !== '') {
            $activeCustomViewCriteriaLabel .= ': ' . $criteriaValue;
        }
    }
}

$pageTitle = 'All Expenses';
if ($selectedFilter !== 'all' && isset($expenseStatusViews[$selectedFilter])) {
    $pageTitle = $expenseStatusViews[$selectedFilter];
}
if ($selectedView !== '' && isset($customViews[$selectedView]['name'])) {
    $pageTitle = (string) $customViews[$selectedView]['name'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="<?php echo billing_escape(billing_base_href()); ?>">
<title>Expenses</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;700;800&display=swap">
<link rel="stylesheet" href="Payslip_Project/assets/fontawesome/css/all.min.css">
<link rel="stylesheet" href="assets/billing.css?v=20260507-css-recovery-2">
<style>
.billing-expenses-page {
    background: #f6f8fc;
}

.billing-expenses-shell {
    position: relative;
    overflow: visible;
}

.billing-expenses-head {
    position: relative;
    z-index: 5;
    overflow: visible;
}

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

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

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

.billing-expenses-tabs {
    display: flex;
    align-items: center;
    gap: 18px;
}

.billing-expenses-tab-title {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    min-height: 44px;
    padding: 0 14px;
    border: 1px solid #dfe6f2;
    border-radius: 10px;
    background: #f4f6fb;
    color: #10203c;
    font-size: 19px;
    font-weight: 800;
}

.billing-expenses-dropdown {
    position: absolute;
    top: calc(100% + 8px);
    left: 0;
    z-index: 30;
    width: 318px;
    padding: 8px 0 0;
    border: 1px solid #dce6f2;
    border-radius: 12px;
    background: #fff;
    box-shadow: 0 12px 30px rgba(15, 23, 42, 0.12);
}

.billing-expenses-dropdown-search {
    padding: 0 10px 10px;
}

.billing-expenses-dropdown-search input {
    width: 100%;
    min-height: 44px;
    padding: 0 14px;
    border: 1px solid #8db6ff;
    border-radius: 10px;
    outline: 0;
    font: inherit;
}

.billing-expenses-dropdown-list {
    display: block;
    max-height: 430px;
    overflow-y: auto;
    padding: 0 10px 10px;
}

.billing-expenses-dropdown-item {
    display: flex;
    width: calc(100% - 20px);
    box-sizing: border-box;
    min-height: 48px;
    margin: 0 10px 4px;
    padding: 0 22px 0 18px;
    border-radius: 10px;
    color: #3a4556;
    text-decoration: none;
    font-size: 15px;
    font-weight: 500;
    align-items: center;
    justify-content: space-between;
}

.billing-expenses-dropdown-item:hover,
.billing-expenses-dropdown-item.is-active {
    background: #4b87eb;
    color: #fff;
}

.billing-expenses-dropdown-footer {
    border-top: 1px solid #edf2f7;
    padding: 10px 18px 14px;
}

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

.billing-expenses-upload-split {
    position: relative;
    display: inline-flex;
    align-items: stretch;
}

.billing-expenses-upload-main,
.billing-expenses-upload-caret {
    min-height: 40px;
    border: 1px solid #d6dfeb;
    background: #fff;
    color: #111827;
    font: inherit;
    cursor: pointer;
}

.billing-expenses-upload-main {
    padding: 0 16px;
    border-radius: 8px 0 0 8px;
}

.billing-expenses-upload-caret {
    min-width: 36px;
    border-left: 0;
    border-radius: 0 8px 8px 0;
}

.billing-expenses-upload-menu {
    position: absolute;
    top: calc(100% + 8px);
    right: 0;
    z-index: 25;
    min-width: 194px;
    padding: 6px;
    border: 1px solid #dce6f2;
    border-radius: 12px;
    background: #fff;
    box-shadow: 0 12px 30px rgba(15, 23, 42, 0.12);
}

.billing-expenses-upload-menu a {
    min-height: 44px;
    width: 100%;
    box-sizing: border-box;
    padding: 0 14px;
    border-radius: 10px;
    background: #4b87eb;
    color: #fff;
    text-decoration: none;
    font-size: 15px;
    font-weight: 500;
    display: flex;
    align-items: center;
}

.billing-expenses-filter-chip {
    display: inline-flex;
    align-items: center;
    min-height: 34px;
    padding: 0 12px;
    border-radius: 999px;
    border: 1px solid #d5dfef;
    background: #eef5ff;
    color: #2563eb;
    font-size: 13px;
    font-weight: 600;
    margin: 0 0 14px 0;
}

.billing-expenses-table-card {
    overflow: visible;
}

.billing-expenses-custom-view-page .customer-custom-view-card {
    max-width: none;
}

.billing-expenses-custom-view-page .customer-custom-view-head h1 {
    font-size: 22px;
}

.billing-expenses-custom-view-page .customer-custom-view-section--header {
    grid-template-columns: minmax(320px, 480px) auto;
}

.billing-expenses-custom-view-page .customer-columns-title--selected {
    color: #55647e;
}
</style>
</head>
<body class="billing-dashboard-page">
<div class="dashboard-shell">
    <?php include dirname(__DIR__) . '/includes/app_sidebar.php'; ?>
    <div class="dashboard-main">
        <?php include dirname(__DIR__) . '/includes/topbar.php'; ?>
        <main class="dashboard-content <?php echo $openModal === 'custom-view' ? 'billing-expenses-custom-view-page customer-custom-view-page' : 'billing-expenses-page'; ?>">
            <?php if ($openModal === 'custom-view'): ?>
                <section class="customer-custom-view-card">
                    <div class="customer-custom-view-head">
                        <h1>New Custom View</h1>
                        <a class="customer-close-link" href="<?php echo billing_escape($buildExpenseUrl(['modal' => null])); ?>"><i class="fa-solid fa-xmark"></i></a>
                    </div>

                    <form method="post">
                        <input type="hidden" name="expense_action" value="save_custom_view">

                        <div class="customer-custom-view-section customer-custom-view-section--header">
                            <label>
                                <span>Name*</span>
                                <input id="view_name" type="text" name="view_name" required autofocus>
                            </label>
                            <label class="customer-favorite-toggle">
                                <input type="checkbox" name="favorite" value="1">
                                <i class="fa-regular fa-star"></i>
                                <span>Mark as Favorite</span>
                            </label>
                        </div>

                        <div class="customer-custom-view-section">
                            <h2>Define the criteria ( if any )</h2>
                            <div class="customer-criteria-list">
                                <div class="customer-criterion-row">
                                    <div class="customer-criterion-number">1</div>
                                    <select name="criteria_field">
                                        <option value="">Select a field</option>
                                        <?php foreach ($criteriaFieldOptions as $fieldValue => $fieldLabel): ?>
                                            <option value="<?php echo billing_escape($fieldValue); ?>"><?php echo billing_escape($fieldLabel); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <select name="criteria_comparator">
                                        <option value="">Select a comparator</option>
                                        <?php foreach ($criteriaComparatorOptions as $comparatorValue => $comparatorLabel): ?>
                                            <option value="<?php echo billing_escape($comparatorValue); ?>"><?php echo billing_escape($comparatorLabel); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <input type="text" name="criteria_value">
                                    <button class="customer-criterion-add" type="button" onclick="return false;"><i class="fa-solid fa-plus"></i></button>
                                    <button class="customer-criterion-remove" type="button" onclick="return false;"><i class="fa-regular fa-trash-can"></i></button>
                                </div>
                            </div>
                            <button class="customer-add-criterion-link" type="button" onclick="return false;"><i class="fa-solid fa-circle-plus"></i> Add Criterion</button>
                        </div>

                        <div class="customer-custom-view-section">
                            <h2>Columns Preference:</h2>
                            <div class="customer-columns-grid">
                                <div class="customer-columns-box">
                                    <div class="customer-columns-title">AVAILABLE COLUMNS</div>
                                    <div class="customer-columns-search">
                                        <i class="fa-solid fa-magnifying-glass"></i>
                                        <input type="search" placeholder="Search">
                                    </div>
                                    <div class="customer-columns-list">
                                        <?php foreach ($availableColumns as $columnLabel): ?>
                                            <div class="customer-column-chip"><i class="fa-solid fa-grip-vertical"></i><span><?php echo billing_escape($columnLabel); ?></span></div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <div class="customer-columns-box">
                                    <div class="customer-columns-title customer-columns-title--selected">SELECTED COLUMNS</div>
                                    <div class="customer-columns-list customer-columns-list--selected">
                                        <?php foreach ($selectedColumns as $columnLabel): ?>
                                            <div class="customer-column-chip"><i class="fa-solid fa-grip-vertical"></i><span><?php echo billing_escape($columnLabel); ?></span></div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="customer-custom-view-section">
                            <h2>Visibility Preference</h2>
                            <div class="customer-visibility-card">
                                <div class="customer-visibility-title">Share With</div>
                                <label><input type="radio" name="visibility" value="only_me" checked> Only Me</label>
                                <label><input type="radio" name="visibility" value="selected_roles"> Only Selected Users &amp; Roles</label>
                                <label><input type="radio" name="visibility" value="everyone"> Everyone</label>
                            </div>
                        </div>

                        <div class="customer-form-footer">
                            <button class="customer-btn customer-btn--green" type="submit">Save</button>
                            <a class="customer-btn" href="<?php echo billing_escape($buildExpenseUrl(['modal' => null])); ?>">Cancel</a>
                        </div>
                    </form>
                </section>
            <?php else: ?>
            <section class="billing-expenses-shell">
                <?php if ($flashSuccess): ?><div class="customer-flash"><?php echo billing_escape($flashSuccess); ?></div><?php endif; ?>
                <?php if ($flashError): ?><div class="customer-flash" style="background:#fef2f2;color:#b91c1c;border-color:#fecaca;"><?php echo billing_escape($flashError); ?></div><?php endif; ?>

                <div class="billing-expenses-head">
                    <div class="billing-expenses-tabs">
                        <a href="#">Receipts Inbox</a>
                        <details class="billing-expenses-inline-details">
                            <summary class="billing-expenses-tab-title"><?php echo billing_escape($pageTitle); ?> <i class="fa-solid fa-angle-down"></i></summary>
                            <div class="billing-expenses-dropdown">
                                <div class="billing-expenses-dropdown-search">
                                    <input type="search" placeholder="Search" data-expense-filter-search>
                                </div>
                                <div class="billing-expenses-dropdown-list">
                                    <?php foreach ($expenseStatusViews as $filterKey => $filterLabel): ?>
                                        <a class="billing-expenses-dropdown-item <?php echo $selectedView === '' && $selectedFilter === $filterKey ? 'is-active' : ''; ?>" href="<?php echo billing_escape($buildExpenseUrl(['filter_by' => $filterKey, 'view' => null])); ?>" data-expense-filter-option>
                                            <span><?php echo billing_escape($filterLabel); ?></span>
                                            <i class="fa-regular fa-star"></i>
                                        </a>
                                    <?php endforeach; ?>
                                    <?php foreach ($customViews as $viewKey => $view): ?>
                                        <a class="billing-expenses-dropdown-item <?php echo $selectedView === (string) $viewKey ? 'is-active' : ''; ?>" href="<?php echo billing_escape($buildExpenseUrl(['view' => $viewKey, 'filter_by' => null])); ?>" data-expense-filter-option>
                                            <span><?php echo billing_escape((string) ($view['name'] ?? 'Custom View')); ?></span>
                                            <i class="fa-<?php echo !empty($view['favorite']) ? 'solid' : 'regular'; ?> fa-star"></i>
                                        </a>
                                    <?php endforeach; ?>
                                </div>
                                <div class="billing-expenses-dropdown-footer">
                                    <a class="billing-expenses-dropdown-create" href="<?php echo billing_escape($buildExpenseUrl(['modal' => 'custom-view'])); ?>"><i class="fa-solid fa-circle-plus"></i> New Custom View</a>
                                </div>
                            </div>
                        </details>
                    </div>
                    <div class="billing-expenses-actions">
                        <details class="billing-expenses-inline-details billing-expenses-upload-split">
                            <summary style="display:flex;list-style:none;">
                                <span class="billing-expenses-upload-main">Upload Expense</span>
                                <span class="billing-expenses-upload-caret" aria-label="Upload options"><i class="fa-solid fa-angle-down"></i></span>
                            </summary>
                            <div class="billing-expenses-upload-menu">
                                <a href="#" data-expense-desktop-trigger>Attach From Desktop</a>
                            </div>
                        </details>
                        <a class="billing-expenses-btn billing-expenses-btn--green" href="expense_new.php"><i class="fa-solid fa-plus"></i> New</a>
                        <button class="billing-expenses-icon-btn" type="button" aria-label="More actions">
                            <i class="fa-solid fa-ellipsis"></i>
                        </button>
                    </div>
                </div>

                <?php if ($activeCustomViewCriteriaLabel !== ''): ?>
                    <div class="billing-expenses-filter-chip">Custom View: <?php echo billing_escape($activeCustomViewCriteriaLabel); ?></div>
                <?php endif; ?>

                <section class="billing-expenses-table-card">
                    <table class="billing-expenses-table">
                        <thead>
                            <tr>
                                <th class="is-icon"><i class="fa-solid fa-sliders"></i></th>
                                <th class="is-check"><input type="checkbox" aria-label="Select all expenses"></th>
                                <th>DATE</th>
                                <th>EXPENSE ACCOUNT</th>
                                <th>REFERENCE#</th>
                                <th>CUSTOMER NAME</th>
                                <th>STATUS</th>
                                <th class="is-amount">AMOUNT</th>
                                <th class="is-icon"><i class="fa-solid fa-magnifying-glass"></i></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($visibleExpenses === []): ?>
                                <tr>
                                    <td class="billing-expenses-empty" colspan="9">No expenses found for this view.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($visibleExpenses as $expense): ?>
                                    <?php
                                    $expenseDate = (string) ($expense['expense_date'] ?? '');
                                    $expenseDateLabel = $expenseDate !== '' ? date('d/m/Y', strtotime($expenseDate)) : '-';
                                    $accountLabel = (string) (($expense['expense_account'] ?? '') !== '' ? $expense['expense_account'] : ($expense['category_name'] ?? ''));
                                    $referenceNumber = (string) (($expense['reference_number'] ?? '') !== '' ? $expense['reference_number'] : '-');
                                    $customerName = (string) (($expense['customer_name'] ?? '') !== '' ? $expense['customer_name'] : '-');
                                    $statusLabel = (string) ($expense['status_label'] ?? 'NON-BILLABLE');
                                    $amount = (float) ($expense['total_amount'] ?? 0);
                                    $hasAttachment = !empty($expense['attachments']);
                                    ?>
                                    <tr>
                                        <td></td>
                                        <td class="is-check"><input type="checkbox" aria-label="Select expense <?php echo (int) ($expense['id'] ?? 0); ?>"></td>
                                        <td><?php echo billing_escape($expenseDateLabel); ?></td>
                                        <td><a class="billing-expenses-name" href="expense_new.php?id=<?php echo (int) ($expense['id'] ?? 0); ?>"><?php echo billing_escape($accountLabel); ?></a></td>
                                        <td class="is-muted"><?php echo billing_escape($referenceNumber); ?></td>
                                        <td><?php echo billing_escape($customerName); ?></td>
                                        <td><?php echo billing_escape(strtoupper($statusLabel)); ?></td>
                                        <td class="is-amount"><?php echo billing_escape('₹' . number_format($amount, 2)); ?></td>
                                        <td class="is-icon"><?php if ($hasAttachment): ?><i class="fa-solid fa-paperclip"></i><?php endif; ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </section>
            </section>
            <?php endif; ?>
        </main>
    </div>
</div>

<form id="expenseDesktopUploadForm" action="expenses.php" method="post" enctype="multipart/form-data" style="display:none;">
    <input type="hidden" name="expense_action" value="upload_desktop">
    <input id="expenseDesktopUploadInput" type="file" name="expense_receipts[]" multiple accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.csv">
</form>

<script src="assets/billing.js"></script>
<script>
document.querySelectorAll('.billing-expenses-inline-details').forEach(function (details) {
    details.addEventListener('toggle', function () {
        if (!details.open) {
            return;
        }

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

        var searchInput = details.querySelector('[data-expense-filter-search]');
        if (searchInput) {
            searchInput.value = '';
        }

        var options = details.querySelectorAll('[data-expense-filter-option]');
        options.forEach(function (option) {
            option.style.display = '';
        });

        var list = details.querySelector('.billing-expenses-dropdown-list');
        if (list) {
            list.scrollTop = 0;
        }

        if (searchInput) {
            setTimeout(function () {
                searchInput.focus();
                searchInput.select();
            }, 0);
        }
    });
});

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

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

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

var expenseDesktopTrigger = document.querySelector('[data-expense-desktop-trigger]');
var expenseDesktopInput = document.getElementById('expenseDesktopUploadInput');
var expenseDesktopForm = document.getElementById('expenseDesktopUploadForm');

if (expenseDesktopTrigger && expenseDesktopInput && expenseDesktopForm) {
    expenseDesktopTrigger.addEventListener('click', function (event) {
        event.preventDefault();
        document.querySelectorAll('.billing-expenses-inline-details[open]').forEach(function (details) {
            details.open = false;
        });
        expenseDesktopInput.click();
    });

    expenseDesktopInput.addEventListener('change', function () {
        if (expenseDesktopInput.files && expenseDesktopInput.files.length > 0) {
            expenseDesktopForm.submit();
        }
    });
}
</script>
</body>
</html>
