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

$stats = billing_dashboard_stats((int) $user['id']);
$organizationName = (string) ($organization['organization_name'] ?? 'bala');
$userLabel = (string) ($user['email'] ?? 'billing-user');
$billingTopbarOrganizationName = $organizationName;
$billingTopbarUserLabel = $userLabel;
$billingActiveNav = 'expenses';

$expenseId = (int) ($_GET['id'] ?? 0);
$existing = $expenseId > 0 ? billing_get_expense((int) $user['id'], (int) $organization['id'], $expenseId) : null;
$expenseAccounts = billing_expense_accounts((int) $user['id'], (int) $organization['id']);
$customers = billing_expense_customer_options((int) $user['id'], (int) $organization['id']);

function billing_expense_form_date(?string $value): string
{
    if (!$value) {
        return date('d/m/Y');
    }
    $time = strtotime($value);
    return $time ? date('d/m/Y', $time) : (string) $value;
}

function billing_expense_parse_date(string $value): string
{
    $value = trim($value);
    if ($value === '') {
        return '';
    }
    $formats = ['d/m/Y', 'Y-m-d', 'm/d/Y'];
    foreach ($formats as $format) {
        $date = DateTime::createFromFormat($format, $value);
        if ($date instanceof DateTime) {
            return $date->format('Y-m-d');
        }
    }
    $time = strtotime($value);
    return $time ? date('Y-m-d', $time) : '';
}

$form = [
    'expense_date' => billing_expense_form_date((string) ($existing['expense_date'] ?? '')),
    'category_name' => (string) ($existing['category_name'] ?? ''),
    'expense_account' => (string) ($existing['expense_account'] ?? ''),
    'currency_code' => (string) ($existing['currency_code'] ?? 'INR'),
    'total_amount' => $existing ? number_format((float) ($existing['total_amount'] ?? 0), 2, '.', '') : '',
    'invoice_number' => (string) ($existing['invoice_number'] ?? ''),
    'notes_text' => (string) ($existing['notes_text'] ?? ''),
    'customer_name' => (string) ($existing['customer_name'] ?? ''),
    'status_label' => (string) ($existing['status_label'] ?? 'NON-BILLABLE'),
    'is_itemized' => !empty($existing['is_itemized']) ? '1' : '',
    'attachments' => is_array($existing['attachments'] ?? null) ? $existing['attachments'] : [],
];

if (!$existing && isset($_SESSION['billing_pending_expense_attachments']) && is_array($_SESSION['billing_pending_expense_attachments'])) {
    $form['attachments'] = array_values(array_filter($_SESSION['billing_pending_expense_attachments']));
    unset($_SESSION['billing_pending_expense_attachments']);
}

$itemRows = $existing && !empty($existing['items']) ? $existing['items'] : [
    ['expense_account' => '', 'notes_text' => '', 'amount' => ''],
];
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $form['expense_date'] = billing_clean((string) ($_POST['expense_date'] ?? ''));
    $form['category_name'] = billing_clean((string) ($_POST['category_name'] ?? ''));
    $form['expense_account'] = billing_clean((string) ($_POST['expense_account'] ?? $form['category_name']));
    $form['currency_code'] = billing_clean((string) ($_POST['currency_code'] ?? 'INR'));
    $form['total_amount'] = billing_clean((string) ($_POST['total_amount'] ?? ''));
    $form['invoice_number'] = billing_clean((string) ($_POST['invoice_number'] ?? ''));
    $form['notes_text'] = billing_clean((string) ($_POST['notes_text'] ?? ''));
    $form['customer_name'] = billing_clean((string) ($_POST['customer_name'] ?? ''));
    $form['status_label'] = 'NON-BILLABLE';
    $form['is_itemized'] = !empty($_POST['is_itemized']) ? '1' : '';
    $form['attachments'] = array_values(array_filter(array_merge(
        is_array($form['attachments']) ? $form['attachments'] : [],
        billing_store_uploaded_files('expense_receipts', 'expense_receipts')
    )));

    $rowAccounts = is_array($_POST['item_account'] ?? null) ? $_POST['item_account'] : [];
    $rowNotes = is_array($_POST['item_notes'] ?? null) ? $_POST['item_notes'] : [];
    $rowAmounts = is_array($_POST['item_amount'] ?? null) ? $_POST['item_amount'] : [];
    $itemRows = [];
    $rowCount = max(count($rowAccounts), count($rowNotes), count($rowAmounts), 1);
    for ($i = 0; $i < $rowCount; $i++) {
        $itemRows[] = [
            'expense_account' => billing_clean((string) ($rowAccounts[$i] ?? '')),
            'notes_text' => billing_clean((string) ($rowNotes[$i] ?? '')),
            'amount' => billing_clean((string) ($rowAmounts[$i] ?? '')),
        ];
    }

    if ($form['expense_date'] === '' || billing_expense_parse_date($form['expense_date']) === '') {
        $errors['expense_date'] = 'Enter a valid date.';
    }
    if ($form['category_name'] === '') {
        $errors['category_name'] = 'Select a category.';
    }
    if ($form['is_itemized'] === '') {
        if ($form['total_amount'] === '' || !is_numeric($form['total_amount'])) {
            $errors['total_amount'] = 'Enter a valid amount.';
        }
    }

    if ($errors === []) {
        $payload = $form;
        $payload['expense_date'] = billing_expense_parse_date($form['expense_date']);
        $payload['items'] = $itemRows;
        $savedId = billing_save_expense((int) $user['id'], (int) $organization['id'], $payload, $existing ? $expenseId : null);
        if ($savedId) {
            billing_flash('success', $existing ? 'Expense updated successfully.' : 'Expense saved successfully.');
            if (($_POST['save_action'] ?? '') === 'save_new') {
                billing_redirect('expense_new.php?reset=1');
            }
            billing_redirect('expenses.php?id=' . $savedId);
        }
        $errors['save'] = 'Unable to save the expense right now.';
    }
}

$receiptFiles = $form['attachments'];
?>
<!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><?php echo $existing ? 'Edit Expense' : 'Add New Expense'; ?> | Zoho Billing</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;600;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>
.expense-form-page {
    background: #fff;
    border: 1px solid #e7edf5;
    border-radius: 24px;
    overflow: hidden;
}
.expense-tabs {
    display: flex;
    gap: 6px;
    border-bottom: 1px solid #e8edf5;
    padding: 26px 26px 0;
}
.expense-tab {
    padding: 14px 18px;
    border: 1px solid transparent;
    border-bottom: 0;
    border-radius: 12px 12px 0 0;
    color: #2763d6;
    text-decoration: none;
    font-size: 16px;
}
.expense-tab.is-active {
    color: #22344a;
    background: #fff;
    border-color: #dfe7f1;
    box-shadow: 0 -3px 0 #2b79ff inset;
    font-weight: 700;
}
.expense-form {
    padding: 28px 26px 24px;
}
.expense-grid {
    display: grid;
    grid-template-columns: minmax(0, 1fr) 360px;
    gap: 34px;
}
.expense-fields {
    min-width: 0;
}
.expense-row {
    display: grid;
    grid-template-columns: 210px minmax(0, 1fr);
    align-items: start;
    gap: 16px;
    padding: 12px 0;
}
.expense-row + .expense-divider,
.expense-divider {
    border-top: 1px solid #edf2f8;
}
.expense-label {
    padding-top: 12px;
    font-size: 16px;
    color: #142235;
}
.expense-label.is-required {
    color: #ff2f2f;
}
.expense-control input[type="text"],
.expense-control input[type="number"],
.expense-control select,
.expense-control textarea {
    width: 100%;
    border: 1px solid #d6dfeb;
    border-radius: 10px;
    padding: 12px 14px;
    font: inherit;
    color: #22344a;
    background: #fff;
}
.expense-control textarea {
    min-height: 66px;
    resize: vertical;
}
.expense-inline {
    display: flex;
    align-items: stretch;
}
.expense-inline .currency-select {
    max-width: 102px;
    border-radius: 10px 0 0 10px;
}
.expense-inline .amount-input {
    border-left: 0;
    border-radius: 0 10px 10px 0;
}
.expense-itemize-trigger {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    margin-top: 8px;
    color: #2b72f0;
    cursor: pointer;
    font-weight: 600;
}
.expense-upload-card {
    align-self: start;
    border: 1px dashed #d6ddea;
    border-radius: 18px;
    padding: 40px 26px;
    text-align: center;
    background: #fff;
}
.expense-upload-art {
    width: 58px;
    height: 58px;
    margin: 0 auto 18px;
    border-radius: 16px;
    display: grid;
    place-items: center;
    background: linear-gradient(180deg, #23366d, #2b79ff);
    color: #fff;
    font-size: 24px;
}
.expense-upload-card h3 {
    margin: 0 0 6px;
    font-size: 16px;
}
.expense-upload-card p {
    margin: 0 0 18px;
    color: #75839a;
}
.expense-upload-btn {
    position: relative;
    display: inline-flex;
    align-items: stretch;
    border: 1px solid #d9e2ee;
    border-radius: 14px;
    background: #fff;
    overflow: visible;
}
.expense-upload-main,
.expense-upload-toggle {
    border: 0;
    background: transparent;
    color: #1b1f2a;
    font: inherit;
    cursor: pointer;
}
.expense-upload-main {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    padding: 0 18px;
    min-height: 54px;
}
.expense-upload-toggle {
    min-width: 48px;
    border-left: 1px solid #d9e2ee;
}
.expense-upload-menu {
    position: absolute;
    top: calc(100% + 8px);
    right: 0;
    min-width: 220px;
    padding: 8px;
    background: #fff;
    border: 1px solid #d9e2ee;
    border-radius: 12px;
    box-shadow: 0 12px 30px rgba(18, 35, 63, 0.14);
    display: none;
    z-index: 20;
}
.expense-upload-btn.is-open .expense-upload-menu {
    display: block;
}
.expense-upload-menu button {
    display: block;
    width: 100%;
    padding: 12px 14px;
    border: 0;
    border-radius: 8px;
    background: transparent;
    color: #1b1f2a;
    font: inherit;
    text-align: left;
    cursor: pointer;
}
.expense-upload-menu button:hover {
    background: #2b79ff;
    color: #fff;
}
.expense-file-list {
    margin-top: 14px;
    text-align: left;
    color: #5d6d84;
    font-size: 13px;
}
.expense-file-list div + div {
    margin-top: 6px;
}
.expense-customer-search {
    display: grid;
    grid-template-columns: minmax(0, 1fr) 44px;
}
.expense-customer-search button {
    border: 0;
    border-radius: 0 10px 10px 0;
    background: #20c667;
    color: #fff;
}
.expense-customer-search select {
    border-radius: 10px 0 0 10px;
}
.expense-itemized-panel {
    display: none;
    padding: 10px 0 0;
}
.expense-itemized-panel.is-open {
    display: block;
}
.expense-back-link {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    margin: 4px 0 18px;
    color: #2b72f0;
    text-decoration: none;
}
.expense-item-table {
    width: 100%;
    border-collapse: collapse;
}
.expense-item-table th {
    padding: 12px 14px;
    text-align: left;
    color: #ff3030;
    font-size: 13px;
    border-top: 1px solid #edf2f8;
    border-bottom: 1px solid #edf2f8;
}
.expense-item-table td {
    padding: 12px 10px 12px 0;
    vertical-align: top;
}
.expense-item-table td:last-child,
.expense-item-table th:last-child {
    padding-right: 0;
}
.expense-item-table textarea,
.expense-item-table select,
.expense-item-table input {
    width: 100%;
    border: 1px solid #d6dfeb;
    border-radius: 10px;
    padding: 12px 12px;
    font: inherit;
}
.expense-reporting-box {
    margin-top: 10px;
    padding: 20px;
    border: 1px solid #edf2f8;
    background: #f7f7f7;
}
.expense-row-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 18px 0 8px;
}
.expense-add-row {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    border: 0;
    border-radius: 10px;
    background: #f0f1fb;
    color: #2d64d9;
    padding: 10px 14px;
    font: inherit;
    font-weight: 600;
    cursor: pointer;
}
.expense-total {
    font-size: 18px;
    font-weight: 700;
}
.expense-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 22px;
    border-top: 1px solid #edf2f8;
    margin-top: 22px;
}
.expense-footer-actions {
    display: flex;
    gap: 12px;
}
.expense-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-height: 42px;
    padding: 0 18px;
    border-radius: 10px;
    border: 1px solid #d9e1ec;
    background: #fff;
    color: #1f2f46;
    text-decoration: none;
    font: inherit;
    cursor: pointer;
}
.expense-btn--green {
    border-color: #19bf60;
    background: #19bf60;
    color: #fff;
    font-weight: 700;
}
.expense-combobox {
    position: relative;
}
.expense-combobox-toggle {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    min-height: 44px;
    border: 1px solid #d6dfeb;
    border-radius: 10px;
    background: #fff;
    color: #6f7d95;
    padding: 0 12px;
    font: inherit;
    cursor: pointer;
}
.expense-combobox.is-open .expense-combobox-toggle,
.expense-control input:focus,
.expense-control select:focus,
.expense-control textarea:focus {
    outline: none;
    border-color: #3f86ff;
    box-shadow: 0 0 0 2px rgba(63, 134, 255, 0.08);
}
.expense-combobox-menu {
    position: absolute;
    top: calc(100% + 10px);
    left: 0;
    right: 0;
    z-index: 25;
    background: #fff;
    border: 1px solid #d6dfeb;
    border-radius: 12px;
    box-shadow: 0 16px 38px rgba(15, 34, 62, 0.16);
    padding: 6px;
    display: none;
}
.expense-combobox.is-open .expense-combobox-menu {
    display: block;
}
.expense-combobox-search {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 6px;
    padding: 0 12px;
    border: 1px solid #3f86ff;
    border-radius: 10px;
    min-height: 44px;
}
.expense-combobox-search input {
    width: 100%;
    border: 0;
    outline: 0;
    font: inherit;
}
.expense-combobox-options {
    max-height: 290px;
    overflow: auto;
}
.expense-combobox-option {
    display: block;
    width: 100%;
    text-align: left;
    border: 0;
    background: transparent;
    padding: 10px 12px;
    border-radius: 8px;
    font: inherit;
    color: #34465f;
    cursor: pointer;
}
.expense-combobox-option:hover,
.expense-combobox-option.is-active {
    background: #4788f3;
    color: #fff;
}
.field-error {
    margin-top: 6px;
    color: #d93025;
    font-size: 13px;
}
.expense-alert {
    margin-bottom: 18px;
    padding: 14px 16px;
    border-radius: 12px;
    border: 1px solid #ffd7d2;
    background: #fff2f1;
    color: #c4312b;
}
@media (max-width: 1120px) {
    .expense-grid {
        grid-template-columns: 1fr;
    }
}
</style>
</head>
<body>
<div class="dashboard-shell customer-shell">
    <?php include dirname(__DIR__) . '/includes/app_sidebar.php'; ?>
    <div class="dashboard-main customer-main">
        <?php include dirname(__DIR__) . '/includes/topbar.php'; ?>
        <main class="expense-form-page">
            <div class="expense-tabs">
                <a class="expense-tab is-active" href="expense_new.php<?php echo $existing ? '?id=' . (int) $expenseId : ''; ?>">Record Expense</a>
                <a class="expense-tab" href="#">Record Mileage</a>
                <a class="expense-tab" href="#">Bulk Add Expenses</a>
            </div>

            <form method="post" enctype="multipart/form-data" class="expense-form">
                <?php if (isset($errors['save'])): ?><div class="expense-alert"><?php echo billing_escape($errors['save']); ?></div><?php endif; ?>

                <div class="expense-grid">
                    <div class="expense-fields">
                        <div class="expense-row">
                            <label class="expense-label is-required" for="expense_date">Date*</label>
                            <div class="expense-control">
                                <input id="expense_date" type="text" name="expense_date" value="<?php echo billing_escape($form['expense_date']); ?>">
                                <?php if (isset($errors['expense_date'])): ?><div class="field-error"><?php echo billing_escape($errors['expense_date']); ?></div><?php endif; ?>
                            </div>
                        </div>

                        <div class="expense-row">
                            <label class="expense-label is-required">Category Name*</label>
                            <div class="expense-control">
                                <div class="expense-combobox" data-combobox>
                                    <input type="hidden" name="category_name" value="<?php echo billing_escape($form['category_name']); ?>">
                                    <input type="hidden" name="expense_account" value="<?php echo billing_escape($form['expense_account'] !== '' ? $form['expense_account'] : $form['category_name']); ?>">
                                    <button class="expense-combobox-toggle" type="button">
                                        <span><?php echo billing_escape($form['category_name'] !== '' ? $form['category_name'] : 'Select Category'); ?></span>
                                        <i class="fa-solid fa-angle-down"></i>
                                    </button>
                                    <div class="expense-combobox-menu">
                                        <div class="expense-combobox-search">
                                            <i class="fa-solid fa-magnifying-glass"></i>
                                            <input type="text" placeholder="Search">
                                        </div>
                                        <div class="expense-combobox-options">
                                            <?php foreach ($expenseAccounts as $account): ?>
                                                <button class="expense-combobox-option<?php echo $form['category_name'] === $account ? ' is-active' : ''; ?>" type="button" data-value="<?php echo billing_escape($account); ?>"><?php echo billing_escape($account); ?></button>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                </div>
                                <?php if (isset($errors['category_name'])): ?><div class="field-error"><?php echo billing_escape($errors['category_name']); ?></div><?php endif; ?>
                                <label class="expense-itemize-trigger">
                                    <input type="checkbox" name="is_itemized" value="1" <?php echo $form['is_itemized'] === '1' ? 'checked' : ''; ?> data-itemize-toggle hidden>
                                    <i class="fa-solid fa-list"></i> Itemize
                                </label>
                            </div>
                        </div>

                        <div class="expense-row">
                            <label class="expense-label is-required" for="total_amount">Amount*</label>
                            <div class="expense-control">
                                <div class="expense-inline">
                                    <select class="currency-select" name="currency_code">
                                        <option value="INR" <?php echo $form['currency_code'] === 'INR' ? 'selected' : ''; ?>>INR</option>
                                    </select>
                                    <input id="total_amount" class="amount-input" type="text" name="total_amount" value="<?php echo billing_escape($form['total_amount']); ?>" <?php echo $form['is_itemized'] === '1' ? 'readonly' : ''; ?>>
                                </div>
                                <?php if (isset($errors['total_amount'])): ?><div class="field-error"><?php echo billing_escape($errors['total_amount']); ?></div><?php endif; ?>
                            </div>
                        </div>

                        <div class="expense-itemized-panel<?php echo $form['is_itemized'] === '1' ? ' is-open' : ''; ?>" id="itemizedPanel">
                            <div class="expense-row">
                                <div></div>
                                <div>
                                    <div class="expense-row" style="padding: 0 0 14px;">
                                        <label class="expense-label" style="padding-top: 8px;">Currency</label>
                                        <div class="expense-control" style="max-width: 525px;">
                                            <select name="currency_code">
                                                <option value="INR" <?php echo $form['currency_code'] === 'INR' ? 'selected' : ''; ?>>INR- Indian Rupee</option>
                                            </select>
                                        </div>
                                    </div>

                                    <a class="expense-back-link" href="#" data-itemize-back><i class="fa-solid fa-arrow-left"></i> Back to single expense view</a>

                                    <table class="expense-item-table" id="expenseItemTable">
                                        <thead>
                                            <tr>
                                                <th style="width:38%;">EXPENSE ACCOUNT</th>
                                                <th>NOTES</th>
                                                <th style="width:26%;">AMOUNT</th>
                                                <th style="width:36px;"><i class="fa-solid fa-ellipsis-vertical"></i></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($itemRows as $row): ?>
                                                <tr>
                                                    <td>
                                                        <select name="item_account[]">
                                                            <option value="">Select</option>
                                                            <?php foreach ($expenseAccounts as $account): ?>
                                                                <option value="<?php echo billing_escape($account); ?>" <?php echo (string) ($row['expense_account'] ?? '') === $account ? 'selected' : ''; ?>><?php echo billing_escape($account); ?></option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                    </td>
                                                    <td><textarea name="item_notes[]" placeholder="Max. 500 characters"><?php echo billing_escape((string) ($row['notes_text'] ?? '')); ?></textarea></td>
                                                    <td><input type="text" name="item_amount[]" value="<?php echo billing_escape((string) ($row['amount'] ?? '')); ?>" data-item-amount></td>
                                                    <td><button class="expense-btn" type="button" data-remove-row><i class="fa-solid fa-trash"></i></button></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>

                                    <div class="expense-reporting-box">
                                        <i class="fa-solid fa-tag" style="color:#95a2b5;"></i> Reporting Tags
                                    </div>

                                    <div class="expense-row-actions">
                                        <button class="expense-add-row" type="button" id="addExpenseRow"><i class="fa-solid fa-circle-plus"></i> Add New Row</button>
                                        <div class="expense-total">Expense Total ( &#8377; ) <span id="expenseTotalValue">0.00</span></div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="expense-divider"></div>

                        <div class="expense-row">
                            <label class="expense-label" for="invoice_number">Invoice#</label>
                            <div class="expense-control"><input id="invoice_number" type="text" name="invoice_number" value="<?php echo billing_escape($form['invoice_number']); ?>"></div>
                        </div>

                        <div class="expense-row">
                            <label class="expense-label" for="notes_text">Notes</label>
                            <div class="expense-control"><textarea id="notes_text" name="notes_text" placeholder="Max. 500 characters"><?php echo billing_escape($form['notes_text']); ?></textarea></div>
                        </div>

                        <div class="expense-divider"></div>

                        <div class="expense-row">
                            <label class="expense-label" for="customer_name">Customer Name</label>
                            <div class="expense-control expense-customer-search">
                                <select id="customer_name" name="customer_name">
                                    <option value="">Select or add a customer</option>
                                    <?php foreach ($customers as $customer): ?>
                                        <?php $customerName = (string) ($customer['customer_name'] ?? ''); ?>
                                        <option value="<?php echo billing_escape($customerName); ?>" <?php echo $form['customer_name'] === $customerName ? 'selected' : ''; ?>><?php echo billing_escape($customerName); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <button type="button" aria-label="Search customer"><i class="fa-solid fa-magnifying-glass"></i></button>
                            </div>
                        </div>

                    </div>

                    <aside class="expense-upload-card">
                        <div class="expense-upload-art"><i class="fa-regular fa-image"></i></div>
                        <h3>Drag or Drop your Receipts</h3>
                        <p>Maximum file size allowed is 10MB</p>
                        <div class="expense-upload-btn" data-upload-split>
                            <button class="expense-upload-main" type="button">
                                <i class="fa-solid fa-upload"></i> Upload your Files
                            </button>
                            <button class="expense-upload-toggle" type="button" aria-label="More upload options">
                                <i class="fa-solid fa-circle-chevron-down"></i>
                            </button>
                            <div class="expense-upload-menu">
                                <button type="button" data-file-trigger>Attach From Desktop</button>
                            </div>
                            <input type="file" name="expense_receipts[]" multiple hidden data-file-input>
                        </div>
                        <?php if ($receiptFiles !== []): ?>
                            <div class="expense-file-list">
                                <?php foreach ($receiptFiles as $file): ?>
                                    <div><?php echo billing_escape(basename((string) $file)); ?></div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </aside>
                </div>

                <div class="expense-footer">
                    <div class="expense-footer-actions">
                        <button class="expense-btn expense-btn--green" type="submit" name="save_action" value="save">Save (Alt+S)</button>
                        <button class="expense-btn" type="submit" name="save_action" value="save_new">Save and New (Alt+N)</button>
                        <a class="expense-btn" href="expenses.php">Cancel</a>
                    </div>
                </div>
            </form>
        </main>
    </div>
</div>

<template id="expenseRowTemplate">
    <tr>
        <td>
            <select name="item_account[]">
                <option value="">Select</option>
                <?php foreach ($expenseAccounts as $account): ?>
                    <option value="<?php echo billing_escape($account); ?>"><?php echo billing_escape($account); ?></option>
                <?php endforeach; ?>
            </select>
        </td>
        <td><textarea name="item_notes[]" placeholder="Max. 500 characters"></textarea></td>
        <td><input type="text" name="item_amount[]" value="" data-item-amount></td>
        <td><button class="expense-btn" type="button" data-remove-row><i class="fa-solid fa-trash"></i></button></td>
    </tr>
</template>

<script>
(function () {
    var itemizeCheckbox = document.querySelector('[data-itemize-toggle]');
    var itemizePanel = document.getElementById('itemizedPanel');
    var amountInput = document.getElementById('total_amount');
    var totalDisplay = document.getElementById('expenseTotalValue');
    var tableBody = document.querySelector('#expenseItemTable tbody');
    var template = document.getElementById('expenseRowTemplate');

    function updateItemizeVisibility() {
        if (!itemizeCheckbox) return;
        itemizePanel.classList.toggle('is-open', itemizeCheckbox.checked);
        amountInput.readOnly = itemizeCheckbox.checked;
        if (itemizeCheckbox.checked) {
            recalcTotal();
        }
    }

    function recalcTotal() {
        if (!tableBody || !totalDisplay) return;
        var total = 0;
        tableBody.querySelectorAll('[data-item-amount]').forEach(function (input) {
            var value = parseFloat(input.value);
            if (!isNaN(value)) {
                total += value;
            }
        });
        totalDisplay.textContent = total.toFixed(2);
        if (amountInput.readOnly) {
            amountInput.value = total.toFixed(2);
        }
    }

    if (itemizeCheckbox) {
        itemizeCheckbox.addEventListener('change', updateItemizeVisibility);
        updateItemizeVisibility();
    }

    document.querySelectorAll('[data-itemize-back]').forEach(function (link) {
        link.addEventListener('click', function (event) {
            event.preventDefault();
            itemizeCheckbox.checked = false;
            updateItemizeVisibility();
        });
    });

    if (tableBody) {
        tableBody.addEventListener('input', function (event) {
            if (event.target.matches('[data-item-amount]')) {
                recalcTotal();
            }
        });

        tableBody.addEventListener('click', function (event) {
            var button = event.target.closest('[data-remove-row]');
            if (!button) return;
            event.preventDefault();
            var rows = tableBody.querySelectorAll('tr');
            if (rows.length > 1) {
                button.closest('tr').remove();
                recalcTotal();
            }
        });
    }

    var addRowButton = document.getElementById('addExpenseRow');
    if (addRowButton && template && tableBody) {
        addRowButton.addEventListener('click', function () {
            tableBody.appendChild(template.content.firstElementChild.cloneNode(true));
        });
    }

    recalcTotal();

    document.querySelectorAll('[data-combobox]').forEach(function (box) {
        var hidden = box.querySelector('input[type="hidden"]');
        var accountHidden = box.querySelectorAll('input[type="hidden"]')[1];
        var toggle = box.querySelector('.expense-combobox-toggle');
        var label = toggle.querySelector('span');
        var search = box.querySelector('.expense-combobox-search input');
        var options = Array.prototype.slice.call(box.querySelectorAll('.expense-combobox-option'));

        toggle.addEventListener('click', function (event) {
            event.stopPropagation();
            document.querySelectorAll('[data-combobox].is-open').forEach(function (openBox) {
                if (openBox !== box) openBox.classList.remove('is-open');
            });
            box.classList.toggle('is-open');
            if (box.classList.contains('is-open')) {
                search.focus();
            }
        });

        options.forEach(function (option) {
            option.addEventListener('click', function () {
                hidden.value = option.dataset.value;
                if (accountHidden) {
                    accountHidden.value = option.dataset.value;
                }
                label.textContent = option.dataset.value;
                options.forEach(function (item) { item.classList.remove('is-active'); });
                option.classList.add('is-active');
                box.classList.remove('is-open');
            });
        });

        search.addEventListener('input', function () {
            var query = search.value.toLowerCase();
            options.forEach(function (option) {
                var match = option.dataset.value.toLowerCase().indexOf(query) !== -1;
                option.style.display = match ? '' : 'none';
            });
        });
    });

    document.addEventListener('click', function () {
        document.querySelectorAll('[data-combobox].is-open').forEach(function (box) {
            box.classList.remove('is-open');
        });
    });

    document.querySelectorAll('[data-upload-split]').forEach(function (group) {
        var mainButton = group.querySelector('.expense-upload-main');
        var toggleButton = group.querySelector('.expense-upload-toggle');
        var triggerButton = group.querySelector('[data-file-trigger]');
        var fileInput = group.querySelector('[data-file-input]');

        function toggleMenu(event) {
            event.stopPropagation();
            document.querySelectorAll('[data-upload-split].is-open').forEach(function (openGroup) {
                if (openGroup !== group) {
                    openGroup.classList.remove('is-open');
                }
            });
            group.classList.toggle('is-open');
        }

        mainButton.addEventListener('click', toggleMenu);
        toggleButton.addEventListener('click', toggleMenu);

        triggerButton.addEventListener('click', function (event) {
            event.stopPropagation();
            group.classList.remove('is-open');
            fileInput.click();
        });

        if (window.location.search.indexOf('upload=1') !== -1) {
            setTimeout(function () {
                fileInput.click();
            }, 150);
        }
    });

    document.addEventListener('click', function () {
        document.querySelectorAll('[data-upload-split].is-open').forEach(function (group) {
            group.classList.remove('is-open');
        });
    });
}());
</script>
</body>
</html>



