<?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_new_content.php';
require_once __DIR__ . '/../../includes/expense_flow.php';
require_once __DIR__ . '/../../includes/trips.php';

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

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

expense_flow_ensure_schema();

$expenseId = (int) ($_GET['expense_id'] ?? 0);
if ($expenseId <= 0) {
    redirect(page_url('expenses'));
}

$selectedItem = expense_flow_fetch_item($expenseId, $userId);
if (!$selectedItem) {
    flash('expense_error', 'We could not find that expense.');
    redirect(page_url('expenses'));
}

$recentItems = expense_flow_recent_items($userId, 10);
$reportOptions = expense_flow_report_options($userId);
$selectedTrip = null;
if ((int) ($selectedItem['trip_id'] ?? 0) > 0) {
    $selectedTrip = trip_fetch_by_id((int) ($selectedItem['trip_id'] ?? 0), $userId);
}

$prefill = [
    'expense_id' => (int) ($selectedItem['id'] ?? 0),
    'selected_item' => $selectedItem,
    'recent_items' => $recentItems,
    'report_id' => (int) ($selectedItem['report_id'] ?? 0),
    'report_title' => (string) ($selectedItem['report_title'] ?? ''),
    'trip_id' => (int) ($selectedItem['trip_id'] ?? 0),
    'trip_name' => (string) ($selectedTrip['trip_name'] ?? ''),
];

if ($prefill['report_title'] === '' && (int) $prefill['report_id'] > 0) {
    foreach ($reportOptions as $report) {
        if ((int) ($report['id'] ?? 0) === (int) $prefill['report_id']) {
            $prefill['report_title'] = (string) ($report['report_title'] ?? '');
            break;
        }
    }
}

$message = flash('expense_success');
$error = flash('expense_error');

render_expense_shell_start('Expense | Detail', 'dashboard-page expense-page expense-editor-page', 'expenses');
?>
<div class="page-surface page-surface--white expense-editor-surface">
    <?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; ?>
    <?php render_expense_detail_content($prefill); ?>
</div>
<?php render_expense_shell_end(); ?>
