<?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_categories.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();

function report_view_money(float $amount, string $currency = 'INR'): string
{
    $symbol = strtoupper(trim($currency)) === 'INR' ? html_entity_decode('&#8377;') : strtoupper(trim($currency)) . ' ';
    return $symbol . number_format($amount, 2);
}

function report_view_date(?string $value): string
{
    $value = trim((string) $value);
    if ($value === '') {
        return '-';
    }
    $ts = strtotime($value);
    return $ts ? date('d/m/Y', $ts) : $value;
}

function report_view_datetime(?string $value): string
{
    $value = trim((string) $value);
    if ($value === '') {
        return '-';
    }
    $ts = strtotime($value);
    return $ts ? date('d/m/Y h:i A', $ts) : $value;
}

function report_view_avatar(string $path): string
{
    $path = trim($path);
    if ($path === '') {
        return asset_url('images/img1.jpg');
    }

    if (preg_match('#^https?://#i', $path)) {
        return $path;
    }

    return asset_url(ltrim($path, '/'));
}

$reportId = (int) ($_GET['report_id'] ?? $_POST['report_id'] ?? 0);
if ($reportId <= 0) {
    redirect(page_url('reports'));
}

$error = null;
$tab = strtolower(trim((string) ($_GET['tab'] ?? 'expenses')));
if (!in_array($tab, ['expenses', 'advances', 'history'], true)) {
    $tab = 'expenses';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim((string) ($_POST['action'] ?? ''));
    if ($action === 'update_report') {
        $existingReport = expense_flow_fetch_report_summary($reportId, $userId);
        $reportTitle = trim((string) ($_POST['report_title'] ?? ''));
        $businessPurpose = trim((string) ($_POST['business_purpose'] ?? ''));
        $startDate = expense_flow_normalize_date((string) ($_POST['start_date'] ?? ''));
        $endDate = expense_flow_normalize_date((string) ($_POST['end_date'] ?? ''));
        $tripId = (int) ($_POST['trip_id'] ?? 0);

        if ($reportTitle === '') {
            $error = 'Please enter a report name.';
        } else {
            execute_query(
                'UPDATE expense_reports
                 SET report_title = ?, business_purpose = ?, start_date = NULLIF(?, ""), end_date = NULLIF(?, ""), trip_id = NULLIF(?, 0), updated_at = NOW()
                 WHERE id = ? AND user_id = ?',
                'ssssiii',
                [$reportTitle, $businessPurpose, $startDate, $endDate, $tripId, $reportId, $userId]
            );
            $previousTitle = trim((string) ($existingReport['report_title'] ?? ''));
            expense_flow_log_report_event(
                $reportId,
                $userId,
                'updated',
                'Report updated',
                $previousTitle !== '' && $previousTitle !== $reportTitle
                    ? 'Report renamed to ' . $reportTitle
                    : 'Report details were updated.'
            );
            flash('expense_success', 'Report updated.');
            redirect(route_url('reports/view/?report_id=' . $reportId));
        }
    }

    if ($action === 'submit_report') {
        $approverUserId = (int) ($_POST['approver_user_id'] ?? 0);
        if ($approverUserId <= 0) {
            $approverUserId = $userId;
        }

        $selectedApprover = fetch_one(
            'SELECT id, email
             FROM users
             WHERE id = ?
             LIMIT 1',
            'i',
            [$approverUserId]
        );
        $currentUserEmail = strtolower(trim((string) ($_SESSION['user_email'] ?? '')));
        if ($currentUserEmail === '') {
            $currentUserRow = fetch_one(
                'SELECT email
                 FROM users
                 WHERE id = ?
                 LIMIT 1',
                'i',
                [$userId]
            );
            $currentUserEmail = strtolower(trim((string) ($currentUserRow['email'] ?? '')));
        }
        $selectedApproverEmail = strtolower(trim((string) ($selectedApprover['email'] ?? '')));
        $isSelfApproval = $approverUserId === $userId
            || ($currentUserEmail !== '' && $selectedApproverEmail !== '' && $selectedApproverEmail === $currentUserEmail);

        $status = $isSelfApproval ? 'approved' : 'awaiting_approval';
        execute_query(
            'UPDATE expense_reports
             SET report_status = ?, submitted_at = NOW(), approved_at = CASE WHEN ? = "approved" THEN NOW() ELSE NULL END, approver_user_id = ?, updated_at = NOW()
             WHERE id = ? AND user_id = ?',
            'ssiii',
            [$status, $status, $approverUserId, $reportId, $userId]
        );
        expense_flow_log_report_event(
            $reportId,
            $userId,
            $status === 'approved' ? 'approved' : 'submitted',
            $status === 'approved' ? 'Report approved' : 'Report submitted',
            $status === 'approved'
                ? 'The report was approved immediately after submission.'
                : 'The report was submitted for approval.'
        );
        flash('expense_success', $status === 'approved' ? 'Report submitted and approved successfully.' : 'Report submitted for approval.');
        redirect(route_url('reports/view/?report_id=' . $reportId));
    }
}

$report = fetch_one(
    'SELECT
        r.*,
        t.trip_name,
        t.destination,
        u.business_name AS approver_name,
        u.email AS approver_email
     FROM expense_reports r
     LEFT JOIN expense_trips t ON t.id = r.trip_id
     LEFT JOIN users u ON u.id = r.approver_user_id
     WHERE r.id = ? AND r.user_id = ? AND r.is_deleted = 0 AND r.deleted_at IS NULL
     LIMIT 1',
    'ii',
    [$reportId, $userId]
);

if (!$report) {
    flash('expense_error', 'We could not find that report.');
    redirect(page_url('reports'));
}

$items = fetch_all(
    'SELECT id, category_name, merchant_name, amount, currency_code, expense_date, receipt_path, claim_reimbursement, description
     FROM expense_report_items
     WHERE report_id = ? AND user_id = ? AND is_deleted = 0 AND deleted_at IS NULL
     ORDER BY COALESCE(expense_date, created_at) DESC, id DESC',
    'ii',
    [$reportId, $userId]
);

$duplicates = fetch_all(
    'SELECT merchant_name, category_name, expense_date, amount, COUNT(*) AS duplicate_count
     FROM expense_report_items
     WHERE report_id = ? AND user_id = ? AND is_deleted = 0 AND deleted_at IS NULL
     GROUP BY merchant_name, category_name, expense_date, amount
     HAVING COUNT(*) > 1',
    'ii',
    [$reportId, $userId]
);

$advances = [];
if (expense_flow_column_exists('expense_advances', 'report_id')) {
    $advanceCurrencySelect = expense_flow_column_exists('expense_advances', 'currency_code') ? 'currency_code' : '"INR" AS currency_code';
    $advances = fetch_all(
        'SELECT id, advance_title, advance_status, amount, ' . $advanceCurrencySelect . ', advance_date, paid_through, notes, created_at
         FROM expense_advances
         WHERE report_id = ? AND user_id = ? AND is_deleted = 0 AND deleted_at IS NULL
         ORDER BY COALESCE(advance_date, created_at) DESC, id DESC',
        'ii',
        [$reportId, $userId]
    );
}

$historyItems = expense_flow_fetch_report_history($reportId, $userId);

$approvers = fetch_all(
    'SELECT id, business_name, email
     FROM users
     WHERE COALESCE(NULLIF(TRIM(email), ""), "") <> ""
     ORDER BY id DESC
     LIMIT 20'
);

$status = trim((string) ($report['report_status'] ?? 'draft'));
$isDraft = $status === 'draft';
$isApproved = $status === 'approved';
$expenseCount = count($items);
$newExpenseUrl = route_url('expenses/new/?report_id=' . $reportId . ((int) ($report['trip_id'] ?? 0) > 0 ? '&trip_id=' . (int) $report['trip_id'] : ''));
$recordAdvanceUrl = route_url('advances/new/?report_id=' . $reportId . ((int) ($report['trip_id'] ?? 0) > 0 ? '&trip_id=' . (int) $report['trip_id'] : ''));
$totalAmount = (float) ($report['total_amount'] ?? 0);
$reimbursableAmount = 0.0;
$nonReimbursableAmount = 0.0;
foreach ($items as $item) {
    if ((int) ($item['claim_reimbursement'] ?? 1) === 1) {
        $reimbursableAmount += (float) ($item['amount'] ?? 0);
    } else {
        $nonReimbursableAmount += (float) ($item['amount'] ?? 0);
    }
}
$appliedAdvanceAmount = 0.0;
foreach ($advances as $advance) {
    if (trim((string) ($advance['advance_status'] ?? 'pending')) !== 'cancelled') {
        $appliedAdvanceAmount += (float) ($advance['amount'] ?? 0);
    }
}

$reportCode = 'ER-' . str_pad((string) $reportId, 5, '0', STR_PAD_LEFT);
$tripCode = (int) ($report['trip_id'] ?? 0) > 0 ? 'TRIP-' . str_pad((string) ((int) $report['trip_id']), 5, '0', STR_PAD_LEFT) : '-';
$message = flash('expense_success');
$flashError = flash('expense_error');
if ($error === null) {
    $error = $flashError;
}
$userContext = current_user_context();
$reportApproverName = trim((string) ($report['approver_name'] ?? ''));
if ((int) ($report['approver_user_id'] ?? 0) === $userId) {
    $reportApproverName = trim((string) ($userContext['display_name'] ?? '')) ?: $reportApproverName;
}

render_expense_shell_start(($report['report_title'] ?? 'Report') . ' | Reports | Expense', 'dashboard-page report-detail-page', 'reports');
?>
<div class="page-surface page-surface--white report-detail-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; ?>

    <header class="report-detail-topbar">
        <div class="report-detail-top-left">
            <strong><?= e($reportCode) ?></strong>
            <span class="reports-status-pill <?= e($status === 'approved' ? 'is-approved' : ($status === 'draft' ? 'is-draft' : 'is-pending')) ?>"><?= e(strtoupper(str_replace('_', ' ', $status))) ?></span>
            <button type="button" class="report-detail-comment-btn" aria-label="Comments">
                <i class="fa-regular fa-comment-dots" aria-hidden="true"></i>
            </button>
        </div>
        <div class="report-detail-top-actions">
            <?php if ($isDraft): ?>
                <a class="report-detail-icon-btn" href="<?= e(route_url('reports/view/?report_id=' . $reportId . '&edit=1')) ?>" aria-label="Edit">
                    <i class="fa-regular fa-pen-to-square" aria-hidden="true"></i>
                </a>
                <button type="button" class="trip-primary report-detail-submit-btn" data-trip-submit-open>Submit</button>
                <button type="button" class="report-detail-icon-btn" aria-label="More actions">
                    <i class="fa-solid fa-ellipsis" aria-hidden="true"></i>
                </button>
            <?php endif; ?>
            <a class="report-detail-icon-btn" href="<?= e(page_url('reports')) ?>" aria-label="Close">
                <i class="fa-solid fa-xmark" aria-hidden="true"></i>
            </a>
        </div>
    </header>

    <div class="report-detail-hero">
        <div class="report-detail-hero-main">
            <h1><?= e((string) ($report['report_title'] ?? 'Report')) ?></h1>
            <p>Duration: <?= e(report_view_date((string) ($report['start_date'] ?? ''))) ?> - <?= e(report_view_date((string) ($report['end_date'] ?? ''))) ?></p>
        </div>
        <div class="report-detail-hero-metrics">
            <div>
                <span>Total</span>
                <strong><?= e(report_view_money($totalAmount, (string) ($report['currency_code'] ?? 'INR'))) ?></strong>
            </div>
            <div>
                <span>Amount to be Reimbursed</span>
                <strong><?= e(report_view_money($reimbursableAmount, (string) ($report['currency_code'] ?? 'INR'))) ?></strong>
                <?php if ($expenseCount > 0): ?>
                    <a class="report-detail-summary-link" href="#report-summary">View Summary</a>
                <?php endif; ?>
            </div>
        </div>
        <aside class="report-detail-sidebar">
            <div class="report-detail-side-block">
                <span>Approver:</span>
                <?php if ($reportApproverName !== ''): ?>
                    <div class="report-detail-approver-card">
                        <img src="<?= e(report_view_avatar('')) ?>" alt="" aria-hidden="true">
                        <div>
                            <strong><?= e($reportApproverName) ?></strong>
                            <small><?= e(trim((string) ($report['approver_email'] ?? '')) ?: 'View approval flow') ?></small>
                        </div>
                    </div>
                    <a class="report-detail-side-link" href="<?= e(route_url('reports/view/?report_id=' . $reportId . '&tab=history')) ?>">View approval flow</a>
                <?php else: ?>
                    <strong>-</strong>
                <?php endif; ?>
            </div>
            <div class="report-detail-side-block">
                <span>Policy</span>
                <strong>demo</strong>
            </div>
            <div class="report-detail-side-block">
                <span>Business Purpose</span>
                <strong><?= e(trim((string) ($report['business_purpose'] ?? '')) ?: '-') ?></strong>
            </div>
            <div class="report-detail-side-block">
                <span>Trip</span>
                <strong class="report-detail-trip-code"><?= e($tripCode) ?></strong>
            </div>
            <div class="report-detail-side-block">
                <span class="report-detail-documents-head">
                    <span>Documents</span>
                    <button type="button" class="report-detail-documents-add" aria-label="Add document">+</button>
                </span>
                <strong>-</strong>
            </div>
        </aside>
    </div>

    <?php if ($duplicates !== []): ?>
        <section class="report-detail-warning">
            <div class="report-detail-warning-head">Warning Violations <span><?= count($duplicates) ?></span></div>
            <div class="report-detail-warning-body">
                <strong>Expenses</strong>
                <p>Duplicate - <?= array_sum(array_map(static fn(array $row): int => (int) ($row['duplicate_count'] ?? 0), $duplicates)) ?> expenses - <a href="<?= e(route_url('reports/view/?report_id=' . $reportId . '&tab=expenses')) ?>">View</a></p>
            </div>
        </section>
    <?php endif; ?>

    <section class="report-detail-tabs">
        <a class="<?= $tab === 'expenses' ? 'is-active' : '' ?>" href="<?= e(route_url('reports/view/?report_id=' . $reportId . '&tab=expenses')) ?>">EXPENSES <span><?= $expenseCount ?></span></a>
        <a class="<?= $tab === 'advances' ? 'is-active' : '' ?>" href="<?= e(route_url('reports/view/?report_id=' . $reportId . '&tab=advances')) ?>">ADVANCES &amp; REFUNDS</a>
        <a class="<?= $tab === 'history' ? 'is-active' : '' ?>" href="<?= e(route_url('reports/view/?report_id=' . $reportId . '&tab=history')) ?>">HISTORY</a>
        <button type="button" class="report-detail-tab-tool" aria-label="Report tools">
            <i class="fa-solid fa-arrow-down-up-across-line" aria-hidden="true"></i>
        </button>
        <?php if ($isDraft): ?>
            <a class="report-detail-add-expense" href="<?= e($newExpenseUrl) ?>">+ New Expense</a>
        <?php endif; ?>
    </section>

    <?php if ($tab === 'expenses'): ?>
        <section class="report-detail-expenses">
            <?php if ($items === [] && $isDraft): ?>
                <div class="report-empty-dropzone">
                    <div class="report-empty-dropzone-icon">
                        <i class="fa-solid fa-arrow-up" aria-hidden="true"></i>
                    </div>
                    <div class="report-empty-dropzone-copy">
                        <strong>Drag &amp; Drop Receipts</strong>
                        <p>or <a href="<?= e($newExpenseUrl) ?>">click here to upload</a></p>
                    </div>
                    <div class="report-empty-dropzone-actions">
                        <a class="report-empty-primary" href="<?= e($newExpenseUrl) ?>">Autoscan Receipts <i class="fa-solid fa-caret-down" aria-hidden="true"></i></a>
                        <a class="report-empty-secondary" href="<?= e($newExpenseUrl) ?>">+ New Expense</a>
                    </div>
                </div>
            <?php endif; ?>
            <?php foreach ($items as $item): ?>
                <?php
                    $receiptPath = trim((string) ($item['receipt_path'] ?? ''));
                    $receiptUrl = $receiptPath !== '' ? asset_url(ltrim($receiptPath, '/')) : '';
                    $ext = strtolower(pathinfo($receiptPath, PATHINFO_EXTENSION));
                    $isImage = in_array($ext, ['jpg', 'jpeg', 'png', 'webp', 'gif'], true);
                    $title = trim((string) ($item['category_name'] ?? '')) ?: trim((string) ($item['merchant_name'] ?? '')) ?: 'Expense';
                    $merchant = trim((string) ($item['merchant_name'] ?? ''));
                    $isReimbursable = (int) ($item['claim_reimbursement'] ?? 1) === 1;
                    $hasWarning = false;
                    foreach ($duplicates as $duplicate) {
                        if (
                            trim((string) ($duplicate['merchant_name'] ?? '')) === $merchant
                            && trim((string) ($duplicate['category_name'] ?? '')) === trim((string) ($item['category_name'] ?? ''))
                            && trim((string) ($duplicate['expense_date'] ?? '')) === trim((string) ($item['expense_date'] ?? ''))
                            && (float) ($duplicate['amount'] ?? 0) === (float) ($item['amount'] ?? 0)
                        ) {
                            $hasWarning = true;
                            break;
                        }
                    }
                ?>
                <article class="report-expense-card">
                    <label class="report-expense-check">
                        <input type="checkbox" aria-label="Select expense <?= e($title) ?>">
                    </label>
                    <div class="report-expense-thumb">
                        <?php if ($receiptUrl !== '' && $isImage): ?>
                            <img src="<?= e($receiptUrl) ?>" alt="Receipt preview">
                        <?php else: ?>
                            <span>No Receipt</span>
                        <?php endif; ?>
                    </div>
                    <div class="report-expense-copy">
                        <span><?= e(report_view_date((string) ($item['expense_date'] ?? ''))) ?></span>
                        <strong><?= e($title) ?></strong>
                        <div class="report-expense-meta">
                            <a href="<?= e(route_url('expenses/view/?expense_id=' . (int) ($item['id'] ?? 0))) ?>"><?= e($merchant !== '' ? $merchant : $title) ?></a>
                            <?php if ($isReimbursable): ?>
                                <span class="report-expense-flag">R</span>
                            <?php endif; ?>
                        </div>
                        <?php if (trim((string) ($item['description'] ?? '')) !== ''): ?>
                            <p><?= e((string) ($item['description'] ?? '')) ?></p>
                        <?php endif; ?>
                    </div>
                    <div class="report-expense-side">
                        <div class="report-expense-amount"><?= e(report_view_money((float) ($item['amount'] ?? 0), (string) ($item['currency_code'] ?? 'INR'))) ?></div>
                        <div class="report-expense-tools">
                            <span class="report-expense-tool<?= $hasWarning ? ' is-warning' : '' ?>"><i class="fa-regular fa-triangle-exclamation" aria-hidden="true"></i></span>
                            <span class="report-expense-tool"><i class="fa-solid fa-magnifying-glass-plus" aria-hidden="true"></i></span>
                            <span class="report-expense-tool report-expense-tool--more"><i class="fa-solid fa-ellipsis" aria-hidden="true"></i></span>
                        </div>
                    </div>
                </article>
            <?php endforeach; ?>
            <?php if ($items === [] && !$isDraft): ?>
                <div class="reports-list-empty">No expenses linked to this report yet.</div>
            <?php endif; ?>
        </section>
        <?php if ($expenseCount > 0): ?>
            <section class="report-detail-summary" id="report-summary">
                <div class="report-detail-summary-grid">
                    <div><span>Total Expense Amount</span><strong><?= e(report_view_money($totalAmount, (string) ($report['currency_code'] ?? 'INR'))) ?></strong></div>
                    <div><span>Non-reimbursable Amount</span><strong>(-) <?= e(report_view_money($nonReimbursableAmount, (string) ($report['currency_code'] ?? 'INR'))) ?></strong></div>
                    <div><span>Applied Advance Amount</span><strong>(-) <?= e(report_view_money($appliedAdvanceAmount, (string) ($report['currency_code'] ?? 'INR'))) ?></strong></div>
                </div>
                <div class="report-detail-summary-total">
                    <span>Amount to be Reimbursed</span>
                    <strong><?= e(report_view_money($reimbursableAmount, (string) ($report['currency_code'] ?? 'INR'))) ?></strong>
                </div>
            </section>
        <?php endif; ?>
    <?php endif; ?>

    <?php if ($tab === 'advances'): ?>
        <section class="report-detail-panel report-detail-panel--emptyable">
            <?php if ($advances === []): ?>
                <div class="report-detail-empty">
                    <div class="report-detail-empty-illustration">
                        <i class="fa-solid fa-money-bill-wave" aria-hidden="true"></i>
                    </div>
                    <p><?= e($isDraft ? 'Record advance for this report' : 'You don\'t have any advances associated with this report.') ?></p>
                    <?php if ($isDraft): ?>
                        <a class="report-empty-secondary" href="<?= e($recordAdvanceUrl) ?>">Record Advance</a>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <div class="trip-related-list report-detail-related-list">
                    <?php foreach ($advances as $advance): ?>
                        <article class="trip-related-item">
                            <div class="trip-related-item-head">
                                <strong><?= e(trim((string) ($advance['advance_title'] ?? 'Advance')) ?: 'Advance') ?></strong>
                                <span class="trip-related-pill"><?= e(ucfirst((string) ($advance['advance_status'] ?? 'pending'))) ?></span>
                            </div>
                            <div class="trip-related-meta">
                                <span><?= e(report_view_date((string) ($advance['advance_date'] ?? $advance['created_at'] ?? ''))) ?></span>
                                <span><?= e(report_view_money((float) ($advance['amount'] ?? 0), (string) ($advance['currency_code'] ?? 'INR'))) ?></span>
                            </div>
                            <p class="trip-related-note"><?= e(trim((string) ($advance['paid_through'] ?? ''))) ?></p>
                            <?php if (trim((string) ($advance['notes'] ?? '')) !== ''): ?>
                                <p class="trip-related-description"><?= e((string) $advance['notes']) ?></p>
                            <?php endif; ?>
                        </article>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>
    <?php endif; ?>

    <?php if ($tab === 'history'): ?>
        <section class="report-detail-panel">
            <?php if ($historyItems === []): ?>
                <div class="report-history-empty">No history yet.</div>
            <?php else: ?>
                <div class="report-history-list">
                    <?php foreach ($historyItems as $historyItem): ?>
                        <article class="report-history-item">
                            <div class="report-history-avatar">
                                <img src="<?= e(report_view_avatar((string) ($historyItem['actor_avatar_path'] ?? ''))) ?>" alt="" aria-hidden="true">
                            </div>
                            <div class="report-history-content">
                                <div class="report-history-heading">
                                    <strong><?= e(trim((string) ($historyItem['actor_name'] ?? 'Expense user')) ?: 'Expense user') ?></strong>
                                    <span><?= e(report_view_datetime((string) ($historyItem['created_at'] ?? ''))) ?></span>
                                </div>
                                <p><?= e(trim((string) ($historyItem['event_title'] ?? 'Report updated')) ?: 'Report updated') ?><?php if (trim((string) ($historyItem['event_description'] ?? '')) !== ''): ?>. <?= e((string) ($historyItem['event_description'] ?? '')) ?><?php endif; ?></p>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>
    <?php endif; ?>
</div>

<?php if (isset($_GET['edit']) && $_GET['edit'] === '1'): ?>
    <div class="page-modal-overlay">
        <section class="trip-modal report-modal">
            <header class="trip-modal-header">
                <div class="trip-modal-title"><span>Edit Report</span></div>
                <a class="page-close-button" href="<?= e(route_url('reports/view/?report_id=' . $reportId)) ?>" aria-label="Close"><i class="fa-solid fa-xmark"></i></a>
            </header>
            <form method="post">
                <input type="hidden" name="action" value="update_report">
                <input type="hidden" name="report_id" value="<?= $reportId ?>">
                <div class="trip-modal-body report-modal-body">
                    <div class="trip-card">
                        <label class="report-field report-field--required">
                            <span>Report Name *</span>
                            <input type="text" name="report_title" value="<?= e((string) ($report['report_title'] ?? '')) ?>" required>
                        </label>
                    </div>
                    <div class="trip-card">
                        <label class="report-field">
                            <span>Business Purpose</span>
                            <textarea name="business_purpose" rows="4"><?= e((string) ($report['business_purpose'] ?? '')) ?></textarea>
                        </label>
                        <div class="report-duration-row">
                            <label class="report-field"><span>Start Date</span><input type="date" name="start_date" value="<?= e((string) ($report['start_date'] ?? '')) ?>"></label>
                            <label class="report-field"><span>End Date</span><input type="date" name="end_date" value="<?= e((string) ($report['end_date'] ?? '')) ?>"></label>
                        </div>
                        <label class="report-field">
                            <span>Trip</span>
                            <?php render_expense_picker('report-edit-trip-picker', 'trip', 'trip_id', '', (int) ($report['trip_id'] ?? 0) > 0 ? (string) ((int) $report['trip_id']) : ''); ?>
                        </label>
                    </div>
                </div>
                <footer class="trip-modal-footer report-modal-footer">
                    <button class="trip-primary" type="submit">Save</button>
                    <a class="trip-secondary" href="<?= e(route_url('reports/view/?report_id=' . $reportId)) ?>">Cancel</a>
                </footer>
            </form>
        </section>
    </div>
<?php endif; ?>

<?php if ($isDraft): ?>
    <div class="trip-submit-modal"
         data-trip-submit-modal
         data-trip-submit-search-url="<?= e(route_url('reports/view/search_approvers.php')) ?>"
         data-current-user-id="<?= (int) ($userContext['user_id'] ?? 0) ?>"
         data-current-user-name="<?= e((string) ($userContext['display_name'] ?? '')) ?>"
         data-current-user-email="<?= e((string) ($userContext['email'] ?? '')) ?>"
         aria-hidden="true">
        <div class="trip-submit-backdrop" data-trip-submit-close></div>
        <aside class="trip-submit-panel" role="dialog" aria-modal="true" aria-labelledby="reportSubmitTitle">
            <header class="trip-submit-header">
                <strong id="reportSubmitTitle">Submit Report</strong>
                <button type="button" class="trip-submit-close" data-trip-submit-close aria-label="Close submit dialog">
                    <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                </button>
            </header>

            <form method="post" class="trip-submit-dialog-form">
                <input type="hidden" name="action" value="submit_report">
                <input type="hidden" name="report_id" value="<?= $reportId ?>">

                <label class="trip-submit-field">
                    <span>Select an approver for the report</span>

                    <div class="trip-submit-picker-shell">
                        <input type="hidden" name="approver_user_id" value="" data-trip-submit-approver data-approver-id="">
                        <input type="hidden" name="approver_email" value="" data-trip-submit-approver-email>

                        <button
                            type="button"
                            class="trip-submit-picker"
                            data-trip-submit-picker-toggle
                            aria-expanded="false"
                            aria-haspopup="listbox"
                        >
                            <span class="trip-submit-picker-label" data-trip-submit-picker-label>
                                <strong data-trip-submit-picker-name>Please select an approver.</strong>
                                <span data-trip-submit-picker-email hidden></span>
                            </span>
                            <i class="fa-solid fa-chevron-down" aria-hidden="true"></i>
                        </button>

                        <button type="button" class="trip-submit-picker-clear" data-trip-submit-picker-clear hidden aria-label="Clear selected approver">
                            <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                        </button>

                        <div class="trip-submit-picker-popover" data-trip-submit-picker-popover hidden style="display:none;">
                            <input type="search" class="trip-submit-picker-search" placeholder="Search" data-trip-submit-picker-search autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false">
                            <div class="trip-submit-picker-list" role="listbox"></div>
                            <div class="trip-submit-picker-empty" data-trip-submit-picker-empty hidden>No approvers found.</div>
                        </div>
                    </div>
                </label>

                <p class="trip-submit-help">
                    <button type="button" class="trip-submit-help-link" data-trip-submit-cc-link>Click here</button>
                    to copy another person in the notification email. (Cc)
                </p>

                <p class="trip-submit-error" data-trip-submit-error hidden>Please select an approver.</p>

                <footer class="trip-submit-footer">
                    <button type="submit" class="trip-submit-confirm" data-trip-submit-confirm disabled>Submit</button>
                    <button type="button" class="trip-submit-cancel" data-trip-submit-close>Cancel</button>
                </footer>
            </form>
        </aside>
    </div>
<?php endif; ?>

<?php render_expense_shell_end(); ?>
