<?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/trips.php';

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

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

trip_ensure_schema();

$tripId = (int) ($_POST['trip_id'] ?? $_GET['trip_id'] ?? 0);
if ($tripId <= 0) {
    redirect(page_url('trips'));
}

$trip = trip_fetch_by_id($tripId, $userId);
if (!$trip) {
    flash('trip_error', 'That trip could not be found.');
    redirect(page_url('trips'));
}

$approverOptions = fetch_all(
    'SELECT
        approver_record_id AS id,
        approver_name,
        employee_id,
        approver_email,
        profile_photo_path,
        start_date,
        end_date,
        is_primary,
        source_priority
     FROM vw_trip_submit_approvers
     WHERE approver_user_id = ?
     ORDER BY source_priority ASC, is_primary DESC, approver_name ASC, id DESC',
    'i',
    [$userId]
);
$activeApprover = $approverOptions[0] ?? null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim((string) ($_POST['action'] ?? ''));

    if ($action === 'document') {
        $documentTitle = trim((string) ($_POST['document_title'] ?? ''));
        $file = $_FILES['trip_document'] ?? [];
        if (!empty($file) && (($file['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_OK)) {
            $documentId = trip_store_document($tripId, $userId, $file, $documentTitle);
            if ($documentId > 0) {
                flash('trip_success', 'Document uploaded.');
            } else {
                flash('trip_error', 'We could not upload the document right now.');
            }
        }
        redirect(route_url('trips/view/?trip_id=' . $tripId . '&tab=itinerary'));
    }

    if ($action === 'comment') {
        $commentText = trim((string) ($_POST['comment_text'] ?? ''));
        if ($commentText !== '') {
            trip_store_comment($tripId, $userId, $commentText, 'comment');
            flash('trip_success', 'Comment added.');
        }
        redirect(route_url('trips/view/?trip_id=' . $tripId . '&tab=history'));
    }

    if ($action === 'archive') {
        trip_archive($tripId, $userId);
        flash('trip_success', 'Trip archived.');
        redirect(route_url('trips/view/?trip_id=' . $tripId));
    }

    if ($action === 'delete') {
        trip_soft_delete($tripId, $userId, 'Deleted from trip detail page');
        flash('trip_success', 'Trip deleted.');
        redirect(page_url('trips'));
    }

    if ($action === 'submit') {
        $approverId = (int) ($_POST['approver_id'] ?? 0);
        $selectedApprover = null;

        foreach ($approverOptions as $approver) {
            if ((int) ($approver['id'] ?? 0) === $approverId) {
                $selectedApprover = $approver;
                break;
            }
        }

        if ($selectedApprover === null && count($approverOptions) === 1) {
            $selectedApprover = $approverOptions[0];
            $approverId = (int) ($selectedApprover['id'] ?? 0);
        }

        if ($selectedApprover === null) {
            flash('trip_error', 'Please select an approver before submitting the trip.');
            redirect(route_url('trips/view/?trip_id=' . $tripId));
        }

        trip_update_status($tripId, $userId, 'active');
        trip_log_event(
            $tripId,
            $userId,
            'submitted',
            'Trip submitted',
            'Trip was submitted for approval.',
            [
                'approver_id' => $approverId,
                'approver_name' => (string) ($selectedApprover['approver_name'] ?? ''),
                'approver_email' => (string) ($selectedApprover['approver_email'] ?? ''),
            ]
        );
        flash('trip_success', 'Trip submitted for approval.');
        redirect(route_url('trips/view/?trip_id=' . $tripId));
    }
}

$tab = strtolower(trim((string) ($_GET['tab'] ?? (($trip['status'] ?? '') === 'active' ? 'reports' : 'itinerary'))));
$allowedTabs = ['itinerary', 'reports', 'advances', 'history'];
if (!in_array($tab, $allowedTabs, true)) {
    $tab = 'itinerary';
}

$tripNumber = trip_trip_number($tripId);
$itineraries = trip_fetch_itineraries($tripId);
$documents = trip_fetch_documents($tripId);
$events = trip_fetch_events($tripId);
$comments = trip_fetch_comments($tripId);
$associatedReports = fetch_all(
    'SELECT id, report_title, report_status, total_amount, currency_code, submitted_at, created_at
     FROM expense_reports
     WHERE trip_id = ? AND user_id = ? AND is_deleted = 0 AND deleted_at IS NULL
     ORDER BY COALESCE(submitted_at, created_at) DESC, id DESC',
    'ii',
    [$tripId, $userId]
);
$advanceDateColumn = 'created_at';
if (trip_column_exists('expense_advances', 'advance_date')) {
    $advanceDateColumn = 'advance_date';
} elseif (trip_column_exists('expense_advances', 'requested_on')) {
    $advanceDateColumn = 'requested_on';
}
$advanceCurrencySelect = trip_column_exists('expense_advances', 'currency_code') ? 'currency_code' : "'INR' AS currency_code";
$advancePaidThroughSelect = trip_column_exists('expense_advances', 'paid_through') ? 'paid_through' : "'' AS paid_through";
$tripAdvances = [];
if (trip_column_exists('expense_advances', 'trip_id')) {
    $tripAdvances = fetch_all(
        'SELECT id, advance_title, advance_status, amount, ' . $advanceCurrencySelect . ', ' . $advancePaidThroughSelect . ', notes, ' . $advanceDateColumn . ' AS advance_date
         FROM expense_advances
         WHERE trip_id = ? AND user_id = ? AND is_deleted = 0 AND deleted_at IS NULL
         ORDER BY ' . $advanceDateColumn . ' DESC, id DESC',
        'ii',
        [$tripId, $userId]
    );
}
$tripSuccess = flash('trip_success');
$tripError = flash('trip_error');

$duration = '-';
if (!empty($trip['start_date']) && !empty($trip['end_date'])) {
    $duration = date('d/m/Y', strtotime($trip['start_date'])) . ' - ' . date('d/m/Y', strtotime($trip['end_date']));
}

$itineraryLabels = [
    'flight' => 'Flight',
    'hotel' => 'Hotel',
    'car' => 'Car Rental',
    'bus' => 'Bus',
    'train' => 'Train',
];

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

    $timestamp = strtotime($value);
    return $timestamp ? date('d M Y', $timestamp) : $value;
}

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

function trip_detail_approver_label(array $approver): string
{
    $name = trim((string) ($approver['approver_name'] ?? ''));
    $employeeId = trim((string) ($approver['employee_id'] ?? ''));
    $email = trim((string) ($approver['approver_email'] ?? ''));

    $parts = [];
    if ($name !== '') {
        $parts[] = $name;
    }
    if ($employeeId !== '') {
        $parts[] = '(' . $employeeId . ')';
    }
    if ($email !== '') {
        $parts[] = $email;
    }

    return trim(implode(' ', $parts));
}

function trip_detail_approver_avatar(array $approver): string
{
    $path = trim((string) ($approver['avatar_url'] ?? $approver['profile_photo_path'] ?? ''));
    if ($path === '') {
        return asset_url('images/img1.jpg');
    }

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

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

function trip_detail_itinerary_title(array $row): string
{
    $payload = [];
    if (!empty($row['payload_json'])) {
        $decoded = json_decode((string) $row['payload_json'], true);
        if (is_array($decoded)) {
            $payload = $decoded;
        }
    }

    $mode = (string) ($row['mode'] ?? 'flight');
    $modeLabel = ucfirst($mode);

    if ($mode === 'flight') {
        $from = trim((string) ($payload['depart_from'] ?? $payload['from'] ?? ''));
        $to = trim((string) ($payload['arrive_at'] ?? $payload['to'] ?? ''));
        return $modeLabel . ': ' . ($from !== '' ? $from : 'Select City') . ' to ' . ($to !== '' ? $to : 'Select City');
    }

    if ($mode === 'hotel') {
        return 'Hotel: ' . trim((string) ($payload['location'] ?? $row['item_title'] ?? 'Select or type city'));
    }

    if ($mode === 'car') {
        $from = trim((string) ($payload['pickup_location'] ?? ''));
        $to = trim((string) ($payload['dropoff_location'] ?? ''));
        return 'Car Rental: ' . ($from !== '' ? $from : 'Pick-up location') . ' to ' . ($to !== '' ? $to : 'Drop-off location');
    }

    if ($mode === 'bus' || $mode === 'train') {
        $from = trim((string) ($payload['depart_from'] ?? ''));
        $to = trim((string) ($payload['arrive_at'] ?? ''));
        return $modeLabel . ': ' . ($from !== '' ? $from : 'Depart from') . ' to ' . ($to !== '' ? $to : 'Arrive at');
    }

    return trim((string) ($row['item_title'] ?? '')) !== '' ? (string) $row['item_title'] : $modeLabel . ' itinerary';
}

function trip_detail_itinerary_payload(array $row): array
{
    $payload = [];
    if (!empty($row['payload_json'])) {
        $decoded = json_decode((string) $row['payload_json'], true);
        if (is_array($decoded)) {
            $payload = $decoded;
        }
    }

    return $payload;
}

function trip_detail_itinerary_route(array $row): string
{
    $payload = trip_detail_itinerary_payload($row);
    $mode = (string) ($row['mode'] ?? 'flight');

    if ($mode === 'flight') {
        $from = trim((string) ($payload['depart_from'] ?? $payload['from'] ?? ''));
        $to = trim((string) ($payload['arrive_at'] ?? $payload['to'] ?? ''));

        return ($from !== '' ? $from : 'Select City') . ' → ' . ($to !== '' ? $to : 'Select City');
    }

    if ($mode === 'hotel') {
        $location = trim((string) ($payload['location'] ?? $row['item_title'] ?? ''));
        return $location !== '' ? $location : 'Select or type city';
    }

    if ($mode === 'car') {
        $from = trim((string) ($payload['pickup_location'] ?? ''));
        $to = trim((string) ($payload['dropoff_location'] ?? ''));

        return ($from !== '' ? $from : 'Pick-up location') . ' → ' . ($to !== '' ? $to : 'Drop-off location');
    }

    if ($mode === 'bus' || $mode === 'train') {
        $from = trim((string) ($payload['depart_from'] ?? ''));
        $to = trim((string) ($payload['arrive_at'] ?? ''));

        return ($from !== '' ? $from : 'Depart from') . ' → ' . ($to !== '' ? $to : 'Arrive at');
    }

    return trim((string) ($row['item_title'] ?? '')) !== '' ? (string) $row['item_title'] : 'Itinerary';
}

function trip_detail_itinerary_details(array $row): array
{
    $payload = trip_detail_itinerary_payload($row);
    $mode = (string) ($row['mode'] ?? 'flight');

    $text = static function ($value, string $fallback = '-'): string {
        $value = trim((string) $value);
        return $value !== '' ? $value : $fallback;
    };

    $details = [];

    if ($mode === 'flight') {
        $details = [
            ['Departure', $text($payload['departure_date'] ?? '')],
            ['Return', $text($payload['return_date'] ?? '')],
            ['Time', $text($payload['time_preference'] ?? '')],
            ['Class', $text($payload['class_preference'] ?? '')],
            ['Seat', $text($payload['seat_preference'] ?? '')],
            ['Meal', $text($payload['meal_preference'] ?? '')],
        ];
    } elseif ($mode === 'hotel') {
        $details = [
            ['Check-in', $text($payload['check_in_date'] ?? '')],
            ['Check-out', $text($payload['check_out_date'] ?? '')],
            ['Check-in time', $text($payload['check_in_time'] ?? '')],
            ['Check-out time', $text($payload['check_out_time'] ?? '')],
            ['Description', $text($payload['description'] ?? '')],
        ];
    } elseif ($mode === 'car') {
        $details = [
            ['Pick-up', $text($payload['pickup_date'] ?? '')],
            ['Drop-off', $text($payload['dropoff_date'] ?? '')],
            ['Pick-up time', $text($payload['pickup_time'] ?? '')],
            ['Drop-off time', $text($payload['dropoff_time'] ?? '')],
            ['Car type', $text($payload['car_type'] ?? '')],
            ['Driver required', $text($payload['driver_required'] ?? '')],
            ['Description', $text($payload['description'] ?? '')],
        ];
    } else {
        $details = [
            ['Departure date', $text($payload['departure_date'] ?? '')],
            ['Description', $text($payload['description'] ?? '')],
        ];
    }

    return array_values(array_filter($details, static fn (array $pair): bool => ($pair[1] ?? '-') !== '-' || ($pair[1] ?? '') === '0'));
}

$itineraryModes = ['flight', 'hotel', 'car', 'bus', 'train'];
$itineraryGroups = [];
foreach ($itineraryModes as $itemMode) {
    $itineraryGroups[$itemMode] = [];
}
foreach ($itineraries as $row) {
    $rowMode = (string) ($row['mode'] ?? 'flight');
    if (!isset($itineraryGroups[$rowMode])) {
        $itineraryGroups[$rowMode] = [];
    }
    $itineraryGroups[$rowMode][] = $row;
}

render_expense_shell_start('Trip | ' . $trip['trip_name'], 'dashboard-page trips-page trip-detail-page', 'trips');
?>
<div class="trip-detail-layout">
    <main class="trip-detail-main">
        <header class="trip-detail-header">
            <div class="trip-detail-title-block">
                <h1><?= e((string) $trip['trip_name']) ?></h1>
                <div class="trip-detail-subtitle">
                    <span class="trip-detail-number"><?= e($tripNumber) ?></span>
                    <span class="trip-detail-status"><?= e(strtoupper(trip_status_label((string) $trip['status']))) ?></span>
                </div>
            </div>

            <div class="trip-detail-actions">
                <button type="button" class="trip-action-icon" data-trip-comments-open aria-label="Open comments">
                    <i class="fa-regular fa-comment-dots" aria-hidden="true"></i>
                </button>
                <a class="trip-action-icon" href="<?= e(route_url('trips/edit/?trip_id=' . $tripId)) ?>" aria-label="Edit trip">
                    <i class="fa-regular fa-pen-to-square" aria-hidden="true"></i>
                </a>

                <?php if ((string) ($trip['status'] ?? '') === 'planned'): ?>
                    <button type="button" class="trip-submit-button" data-trip-submit-open>
                        Submit
                    </button>
                <?php endif; ?>

                <div class="trip-more-menu" data-topbar-popover>
                    <button type="button" class="trip-action-icon" data-topbar-toggle aria-expanded="false" aria-label="More actions">
                        <i class="fa-solid fa-ellipsis" aria-hidden="true"></i>
                    </button>
                    <div class="trip-more-popover" data-topbar-menu aria-hidden="true">
                        <a href="<?= e(route_url('trips/print/?trip_id=' . $tripId)) ?>"><i class="fa-regular fa-file-pdf"></i> PDF</a>
                        <a href="<?= e(route_url('trips/print/?trip_id=' . $tripId)) ?>" target="_blank" rel="noreferrer"><i class="fa-solid fa-print"></i> Print</a>
                        <form method="post">
                            <input type="hidden" name="trip_id" value="<?= (int) $tripId ?>">
                            <input type="hidden" name="action" value="archive">
                            <button type="submit"><i class="fa-solid fa-box-archive"></i> Archive</button>
                        </form>
                        <form method="post" onsubmit="return confirm('Delete this trip?');">
                            <input type="hidden" name="trip_id" value="<?= (int) $tripId ?>">
                            <input type="hidden" name="action" value="delete">
                            <button type="submit" class="is-danger"><i class="fa-regular fa-trash-can"></i> Delete</button>
                        </form>
                    </div>
                </div>

                <a class="trip-action-icon" href="<?= e(page_url('trips')) ?>" aria-label="Close trip">
                    <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                </a>
            </div>
        </header>

        <?php if ($tripSuccess !== null): ?>
            <div class="trip-banner trip-banner--success"><?= e($tripSuccess) ?></div>
        <?php endif; ?>
        <?php if ($tripError !== null): ?>
            <div class="trip-banner trip-banner--error"><?= e($tripError) ?></div>
        <?php endif; ?>

        <section class="trip-overview-card panel">
            <div class="trip-overview-grid">
                <div>
                    <span>Duration</span>
                    <strong><?= e($duration) ?></strong>
                </div>
                <div>
                    <span>Policy</span>
                    <strong>demo</strong>
                </div>
                <div>
                    <span>Destination</span>
                    <strong><?= e((string) $trip['destination']) ?></strong>
                </div>
                <div>
                    <span>Business Purpose</span>
                    <strong><?= e((string) $trip['business_purpose']) ?></strong>
                </div>
                <div>
                    <span>Is visa required?</span>
                    <strong><?= ((int) ($trip['is_visa_required'] ?? 0)) === 1 ? 'Yes' : 'No' ?></strong>
                </div>
                <div>
                    <span>Status</span>
                    <strong><?= e(trip_status_label((string) $trip['status'])) ?></strong>
                </div>
            </div>
        </section>

        <section class="trip-tabs panel">
            <div class="trip-tab-bar">
                <button type="button" class="trip-tab<?= $tab === 'itinerary' ? ' is-active' : '' ?>" data-trip-tab="itinerary">Itinerary</button>
                <button type="button" class="trip-tab<?= $tab === 'reports' ? ' is-active' : '' ?>" data-trip-tab="reports">Associated Reports</button>
                <button type="button" class="trip-tab<?= $tab === 'advances' ? ' is-active' : '' ?>" data-trip-tab="advances">Advances</button>
                <button type="button" class="trip-tab<?= $tab === 'history' ? ' is-active' : '' ?>" data-trip-tab="history">History</button>
            </div>

            <div class="trip-tab-panels">
                <div class="trip-tab-panel<?= $tab === 'itinerary' ? ' is-active' : '' ?>" data-trip-panel="itinerary">
                    <?php if ($itineraries === []): ?>
                        <div class="trip-itinerary-empty">
                            <div class="trip-itinerary-empty-illustration">
                                <i class="fa-solid fa-globe"></i>
                            </div>
                            <h2>Plan Your Trip Itineraries</h2>
                            <p>Add your preferred itineraries and submit the trip for approval. Once approved, itineraries can be booked externally.</p>
                            <div class="trip-itinerary-actions">
                                <a class="trip-itinerary-button is-primary" href="<?= e(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=flight')) ?>">+ Add Flight</a>
                                <a class="trip-itinerary-button" href="<?= e(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=hotel')) ?>">+ Add Hotel</a>
                                <a class="trip-itinerary-button" href="<?= e(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=car')) ?>">+ Add Car Rental</a>
                                <a class="trip-itinerary-button" href="<?= e(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=bus')) ?>">+ Add Bus</a>
                                <a class="trip-itinerary-button" href="<?= e(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=train')) ?>">+ Add Train</a>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="trip-itinerary-addbar">
                            <span class="trip-itinerary-addbar-label">Add Itineraries:</span>
                            <div class="trip-itinerary-addbar-actions">
                                <a class="trip-itinerary-addpill is-primary" href="<?= e(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=flight')) ?>">+ Flight</a>
                                <a class="trip-itinerary-addpill" href="<?= e(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=hotel')) ?>">+ Hotel</a>
                                <a class="trip-itinerary-addpill" href="<?= e(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=car')) ?>">+ Car Rental</a>
                                <a class="trip-itinerary-addpill" href="<?= e(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=bus')) ?>">+ Bus</a>
                                <a class="trip-itinerary-addpill" href="<?= e(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=train')) ?>">+ Train</a>
                            </div>
                        </div>

                        <div class="trip-itinerary-shell">
                            <div class="trip-itinerary-content">
                                <?php foreach ($itineraryModes as $itemMode): ?>
                                    <?php if ($itineraryGroups[$itemMode] !== []): ?>
                                        <section class="trip-itinerary-mode" data-trip-mode-section="<?= e($itemMode) ?>" id="trip-mode-<?= e($itemMode) ?>">
                                            <header class="trip-itinerary-mode-head">
                                                <div>
                                                    <span><?= e($itineraryLabels[$itemMode] ?? ucfirst($itemMode)) ?></span>
                                                    <strong><?= count($itineraryGroups[$itemMode]) ?> item<?= count($itineraryGroups[$itemMode]) === 1 ? '' : 's' ?></strong>
                                                </div>
                                            </header>

                                            <div class="trip-itinerary-list">
                                                <?php foreach ($itineraryGroups[$itemMode] as $row): ?>
                                                    <?php $payload = trip_detail_itinerary_payload($row); ?>
                                                    <article class="trip-itinerary-card">
                                                        <div class="trip-itinerary-card-head">
                                                            <div class="trip-itinerary-card-title">
                                                                <span class="trip-itinerary-badge"><?= e($itineraryLabels[$itemMode] ?? ucfirst($itemMode)) ?></span>
                                                                <strong><?= e(trip_detail_itinerary_route($row)) ?></strong>
                                                            </div>
                                                        </div>
                                                        <div class="trip-itinerary-card-actions">
                                                            <a class="trip-itinerary-mini-button" href="<?= e(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=' . $itemMode)) ?>">Edit</a>
                                                        </div>
                                                        <div class="trip-itinerary-card-body">
                                                            <dl class="trip-itinerary-detail-grid">
                                                                <?php foreach (trip_detail_itinerary_details($row) as $detail): ?>
                                                                    <div class="trip-itinerary-detail-item">
                                                                        <dt><?= e((string) $detail[0]) ?></dt>
                                                                        <dd><?= e((string) $detail[1]) ?></dd>
                                                                    </div>
                                                                <?php endforeach; ?>
                                                            </dl>
                                                            <?php if (($payload['description'] ?? '') !== ''): ?>
                                                                <div class="trip-itinerary-description">
                                                                    <strong>Description</strong>
                                                                    <p><?= e((string) $payload['description']) ?></p>
                                                                </div>
                                                            <?php endif; ?>
                                                        </div>
                                                    </article>
                                                <?php endforeach; ?>
                                            </div>
                                        </section>
                                    <?php endif; ?>
                                <?php endforeach; ?>

                                <div class="trip-itinerary-actions">
                                    <a class="trip-itinerary-button is-primary" href="<?= e(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=flight')) ?>">+ Add Flight</a>
                                    <a class="trip-itinerary-button" href="<?= e(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=hotel')) ?>">+ Add Hotel</a>
                                    <a class="trip-itinerary-button" href="<?= e(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=car')) ?>">+ Add Car Rental</a>
                                    <a class="trip-itinerary-button" href="<?= e(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=bus')) ?>">+ Add Bus</a>
                                    <a class="trip-itinerary-button" href="<?= e(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=train')) ?>">+ Add Train</a>
                                </div>
                            </div>

                            <aside class="trip-itinerary-rail" aria-label="Itinerary quick links">
                                <?php foreach ($itineraryModes as $itemMode): ?>
                                    <?php $count = count($itineraryGroups[$itemMode]); ?>
                                    <button type="button" class="trip-itinerary-rail-item<?= $count === 0 ? ' is-empty' : '' ?>" data-trip-mode-nav="<?= e($itemMode) ?>" title="<?= e($itineraryLabels[$itemMode] ?? ucfirst($itemMode)) ?>"<?= $count === 0 ? ' disabled aria-disabled="true"' : '' ?>>
                                        <i class="<?= e($modeIcons[$itemMode] ?? 'fa-solid fa-circle') ?>" aria-hidden="true"></i>
                                    </button>
                                <?php endforeach; ?>
                            </aside>
                        </div>
                    <?php endif; ?>
                </div>

                <div class="trip-tab-panel<?= $tab === 'reports' ? ' is-active' : '' ?>" data-trip-panel="reports">
                    <?php if ($associatedReports === []): ?>
                        <div class="trip-empty-state trip-empty-state--reports">
                            <div class="trip-empty-state-icon">
                                <i class="fa-solid fa-folder-open" aria-hidden="true"></i>
                            </div>
                            <h2>Create Report for this trip</h2>
                            <p>Add expenses to a report and connect it to this trip when you are ready to submit.</p>
                            <a class="trip-empty-state-button" href="<?= e(route_url('reports/new/?trip_id=' . $tripId)) ?>">+ New Report</a>
                        </div>
                    <?php else: ?>
                        <div class="trip-related-list">
                            <?php foreach ($associatedReports as $report): ?>
                                <article class="trip-related-item">
                                    <div class="trip-related-item-head">
                                        <strong><?= e((string) $report['report_title']) ?></strong>
                                        <span class="trip-related-pill"><?= e(ucfirst(str_replace('_', ' ', (string) $report['report_status']))) ?></span>
                                    </div>
                                    <div class="trip-related-meta">
                                        <span><?= e(trip_detail_format_date((string) ($report['created_at'] ?? ''))) ?></span>
                                        <span><?= e(trip_detail_format_money((float) ($report['total_amount'] ?? 0), (string) ($report['currency_code'] ?? 'INR'))) ?></span>
                                    </div>
                                    <a class="trip-related-link" href="<?= e(page_url('reports')) ?>">Open reports</a>
                                </article>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <div class="trip-tab-panel<?= $tab === 'advances' ? ' is-active' : '' ?>" data-trip-panel="advances">
                    <?php if ($tripAdvances === []): ?>
                        <div class="trip-empty-state trip-empty-state--advances">
                            <div class="trip-empty-state-icon trip-empty-state-icon--green">
                                <i class="fa-solid fa-money-bill-wave" aria-hidden="true"></i>
                            </div>
                            <h2>Record advance for this trip</h2>
                            <p>Record an advance payment and apply it against this trip so it can be tracked later.</p>
                            <a class="trip-empty-state-button" href="<?= e(route_url('advances/new/?trip_id=' . $tripId)) ?>">Record Advance</a>
                        </div>
                    <?php else: ?>
                        <div class="trip-related-list">
                            <?php foreach ($tripAdvances as $advance): ?>
                                <article class="trip-related-item">
                                    <div class="trip-related-item-head">
                                        <strong><?= e((string) $advance['advance_title']) ?></strong>
                                        <span class="trip-related-pill"><?= e(ucfirst((string) $advance['advance_status'])) ?></span>
                                    </div>
                                    <div class="trip-related-meta">
                                        <span><?= e(trip_detail_format_date((string) ($advance['advance_date'] ?? ''))) ?></span>
                                        <span><?= e(trip_detail_format_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; ?>
                </div>

                <div class="trip-tab-panel<?= $tab === 'history' ? ' is-active' : '' ?>" data-trip-panel="history">
                    <?php if ($events === [] && $comments === []): ?>
                        <div class="trip-history-empty">No history yet.</div>
                    <?php else: ?>
                        <div class="trip-history-list">
                            <?php foreach ($events as $event): ?>
                                <article class="trip-history-item">
                                    <strong><?= e((string) $event['event_title']) ?></strong>
                                    <p><?= e((string) $event['event_description']) ?></p>
                                    <span><?= e((string) $event['author_name']) ?> · <?= e((string) $event['created_at']) ?></span>
                                </article>
                            <?php endforeach; ?>
                            <?php foreach ($comments as $comment): ?>
                                <article class="trip-history-item trip-history-item--comment">
                                    <strong><?= e((string) $comment['author_name']) ?></strong>
                                    <p><?= e((string) $comment['comment_text']) ?></p>
                                    <span><?= e((string) $comment['created_at']) ?></span>
                                </article>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </section>
    </main>

    <aside class="trip-documents-panel panel">
        <section class="trip-sidebar-section trip-approver-card">
            <strong>Approver</strong>
            <?php if ($activeApprover): ?>
                <div class="trip-approver-person">
                    <div class="trip-approver-avatar">
                        <img src="<?= e(trip_detail_approver_avatar($activeApprover)) ?>" alt="" aria-hidden="true">
                    </div>
                    <div>
                        <strong><?= e(trim((string) ($activeApprover['approver_name'] ?? ''))) ?></strong>
                        <?php if (trim((string) ($activeApprover['employee_id'] ?? '')) !== ''): ?>
                            <span>ID: <?= e((string) $activeApprover['employee_id']) ?></span>
                        <?php endif; ?>
                        <?php if (trim((string) ($activeApprover['approver_email'] ?? '')) !== ''): ?>
                            <span><?= e((string) $activeApprover['approver_email']) ?></span>
                        <?php endif; ?>
                        <small><?= e(trip_detail_format_date((string) ($activeApprover['start_date'] ?? ''))) ?> - <?= e(trip_detail_format_date((string) ($activeApprover['end_date'] ?? ''))) ?></small>
                    </div>
                </div>
                <a class="trip-related-link" href="<?= e(page_url('approvals')) ?>">View approval flow</a>
            <?php else: ?>
                <p class="trip-related-empty-note">No active approver is assigned in your settings.</p>
                <a class="trip-related-link" href="<?= e(page_url('my_settings')) ?>">Set an approver</a>
            <?php endif; ?>
        </section>

        <div class="trip-documents-head">
            <strong>Documents</strong>
            <button type="button" class="trip-documents-add" data-trip-document-open>+</button>
        </div>
        <form method="post" enctype="multipart/form-data" class="trip-documents-form">
            <input type="hidden" name="trip_id" value="<?= (int) $tripId ?>">
            <input type="hidden" name="action" value="document">
            <input type="hidden" name="document_title" value="" data-trip-document-title>
            <input type="file" name="trip_document" accept="image/*,.pdf,.doc,.docx" hidden data-trip-document-input>
        </form>
        <?php if ($documents === []): ?>
            <div class="trip-documents-empty">-</div>
        <?php else: ?>
            <div class="trip-documents-list">
                <?php foreach ($documents as $document): ?>
                    <article class="trip-document-item">
                        <strong><?= e((string) $document['document_title']) ?></strong>
                        <span><?= e((string) $document['created_at']) ?></span>
                    </article>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
        <div class="trip-documents-actions">
            <a href="<?= e(route_url('trips/planner/?trip_id=' . $tripId . '&selectedTravelMode=flight')) ?>">Plan itinerary</a>
        </div>
    </aside>
</div>

<div class="trip-comments-drawer" data-trip-comments-drawer aria-hidden="true">
    <div class="trip-comments-backdrop" data-trip-comments-close></div>
    <aside class="trip-comments-panel">
        <header class="trip-comments-header">
            <strong>Comments</strong>
            <button type="button" class="trip-comments-close" data-trip-comments-close aria-label="Close comments">
                <i class="fa-solid fa-xmark"></i>
            </button>
        </header>

        <form method="post" class="trip-comments-form">
            <input type="hidden" name="trip_id" value="<?= (int) $tripId ?>">
            <input type="hidden" name="action" value="comment">
            <label>
                <textarea name="comment_text" placeholder="Add your comment here."></textarea>
            </label>
            <button type="submit" class="trip-primary">Add Comment</button>
        </form>
    </aside>
</div>

<div class="trip-submit-modal" data-trip-submit-modal 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="tripSubmitTitle">
        <header class="trip-submit-header">
            <strong id="tripSubmitTitle">Submit Trip</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="trip_id" value="<?= (int) $tripId ?>">
            <input type="hidden" name="action" value="submit">

            <label class="trip-submit-field">
                <span>Select an approver for the trip</span>
                <input type="hidden" name="approver_id" value="<?= $activeApprover ? (int) ($activeApprover['id'] ?? 0) : '' ?>" data-trip-submit-approver>
                <button
                    type="button"
                    class="trip-submit-picker"
                    data-trip-submit-picker-toggle
                    aria-expanded="false"
                    <?= $approverOptions === [] ? 'disabled aria-disabled="true"' : '' ?>
                >
                    <span class="trip-submit-picker-label" data-trip-submit-picker-label>
                        <?= $activeApprover ? e(trip_detail_approver_label($activeApprover)) : 'Please select an approver.' ?>
                    </span>
                    <i class="fa-solid fa-chevron-down" aria-hidden="true"></i>
                </button>

                <div class="trip-submit-picker-popover" data-trip-submit-picker-popover hidden>
                    <input type="search" class="trip-submit-picker-search" placeholder="Search" data-trip-submit-picker-search>
                    <div class="trip-submit-picker-list" role="listbox">
                        <?php foreach ($approverOptions as $approver): ?>
                            <?php
                                $approverName = trim((string) ($approver['approver_name'] ?? ''));
                                $approverEmail = trim((string) ($approver['approver_email'] ?? ''));
                                $approverEmployeeId = trim((string) ($approver['employee_id'] ?? ''));
                                $approverLabel = $approverName . ($approverEmail !== '' ? ' (' . $approverEmail . ')' : '');
                                $approverAvatar = trip_detail_approver_avatar($approver);
                            ?>
                            <button
                                type="button"
                                class="trip-submit-picker-option<?= $activeApprover && (int) ($activeApprover['id'] ?? 0) === (int) ($approver['id'] ?? 0) ? ' is-selected' : '' ?>"
                                data-trip-submit-picker-option
                                data-approver-id="<?= (int) ($approver['id'] ?? 0) ?>"
                                data-approver-label="<?= e($approverLabel) ?>"
                                data-approver-search="<?= e(strtolower($approverLabel)) ?>"
                            >
                                <span class="trip-submit-picker-avatar"><img src="<?= e($approverAvatar) ?>" alt="" aria-hidden="true"></span>
                                <span class="trip-submit-picker-copy">
                                    <strong><?= e($approverName) ?></strong>
                                    <?php if ($approverEmail !== ''): ?>
                                        <span><?= e($approverEmail) ?></span>
                                    <?php elseif ($approverEmployeeId !== ''): ?>
                                        <span>ID: <?= e($approverEmployeeId) ?></span>
                                    <?php endif; ?>
                                </span>
                            </button>
                        <?php endforeach; ?>
                    </div>
                </div>
            </label>

            <p class="trip-submit-help">Click here to copy another person in the notification email. (Cc)</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 render_expense_shell_end(); ?>
