<?php
declare(strict_types=1);

function open_bill_view_text(string $th, string $en): string
{
    return function_exists('current_language') && current_language() === 'th' ? $th : $en;
}

function open_bill_view_order_source_label(string $orderSource): string
{
    return $orderSource === 'quick_service'
        ? open_bill_view_text('ควิกเซอร์วิส', 'Quick Service')
        : open_bill_view_text('Booking', 'Booking');
}

function open_bill_view_icon_svg(string $icon): string
{
    switch ($icon) {
        case 'search':
            return '<svg class="open-bill-icon" viewBox="0 0 24 24" aria-hidden="true"><circle cx="11" cy="11" r="6"></circle><path d="M20 20l-4.2-4.2"></path></svg>';
        case 'plus':
            return '<svg class="open-bill-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5v14"></path><path d="M5 12h14"></path></svg>';
        case 'refresh':
            return '<svg class="open-bill-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M21 12a9 9 0 1 1-2.64-6.36"></path><path d="M21 3v6h-6"></path></svg>';
        case 'dashboard':
            return '<svg class="open-bill-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 5h7v6H4z"></path><path d="M13 5h7v4h-7z"></path><path d="M13 11h7v8h-7z"></path><path d="M4 13h7v6H4z"></path></svg>';
        case 'arrow-right':
            return '<svg class="open-bill-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M5 12h14"></path><path d="M13 5l7 7-7 7"></path></svg>';
        case 'booking':
            return '<svg class="open-bill-icon" viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="5" width="18" height="16" rx="3"></rect><path d="M8 3v4"></path><path d="M16 3v4"></path><path d="M3 10h18"></path></svg>';
        case 'quick_service':
            return '<svg class="open-bill-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M13 2L4 14h6l-1 8 9-12h-6l1-8z"></path></svg>';
        case 'member':
            return '<svg class="open-bill-icon" viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="5" width="18" height="14" rx="3"></rect><circle cx="9" cy="11" r="2.5"></circle><path d="M6.5 16c.9-1.6 2.4-2.4 4.5-2.4S14.6 14.4 15.5 16"></path><path d="M16 9h2.5"></path><path d="M16 13h2.5"></path></svg>';
        case 'camera':
            return '<svg class="open-bill-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 8h3l1.5-2h7L17 8h3a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2z"></path><circle cx="12" cy="14" r="4"></circle></svg>';
        case 'customer':
            return '<svg class="open-bill-icon" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="8" r="4"></circle><path d="M5 20c1.5-3.4 4-5 7-5s5.5 1.6 7 5"></path></svg>';
        case 'vehicle':
            return '<svg class="open-bill-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M5 16l1.5-5A3 3 0 0 1 9.4 9h5.2a3 3 0 0 1 2.9 2L19 16"></path><path d="M4 16h16v3a1 1 0 0 1-1 1h-1.5a1 1 0 0 1-1-1v-1h-9v1a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1z"></path><circle cx="7.5" cy="16.5" r="1"></circle><circle cx="16.5" cy="16.5" r="1"></circle></svg>';
        default:
            return '<svg class="open-bill-icon" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="9"></circle></svg>';
    }
}

function open_bill_view_customer_summary(mysqli $conn, int $customerId): array
{
    if ($customerId <= 0) {
        return array(
            'customer_id' => 0,
            'name' => '',
            'phone' => '',
            'customer_group' => 'member',
            'loyalty_points' => 0,
            'visit_count' => 0,
            'vehicle_count' => 0,
            'lifetime_value' => 0.0,
            'latest_visit' => null,
        );
    }

    $types = '';
    $params = array();
    $orderJoin = "LEFT JOIN orders o ON o.customer_id = c.customer_id AND o.status <> 'cancelled'";
    $branchCondition = auth_branch_condition($conn, 'o', $types, $params);
    if ($branchCondition !== '') {
        $orderJoin .= " AND {$branchCondition}";
    }

    $types .= 'i';
    $params[] = $customerId;
    $stmt = db_prepare($conn, "
        SELECT
            c.customer_id,
            c.name,
            c.phone,
            c.customer_group,
            c.loyalty_points,
            COUNT(DISTINCT o.order_id) AS visit_count,
            COALESCE(SUM(o.total_price), 0) AS lifetime_value,
            MAX(o.order_date) AS latest_visit
        FROM customers c
        {$orderJoin}
        WHERE c.customer_id = ?
        GROUP BY
            c.customer_id,
            c.name,
            c.phone,
            c.customer_group,
            c.loyalty_points
        LIMIT 1
    ");
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $summary = $stmt->get_result()->fetch_assoc() ?: array();
    $stmt->close();

    $carSummary = customer_car_summary_map($conn, array($customerId))[$customerId] ?? array();
    $summary['vehicle_count'] = (int) ($carSummary['car_count'] ?? 0);
    $summary['plate_numbers'] = (string) ($carSummary['plate_numbers'] ?? '');

    return $summary;
}

function open_bill_view_recent_orders(mysqli $conn, int $customerId, int $limit = 5): array
{
    if ($customerId <= 0) {
        return array();
    }

    $types = 'i';
    $params = array($customerId);
    $where = array(
        'o.customer_id = ?',
        "o.status <> 'cancelled'",
    );
    $branchCondition = auth_branch_condition($conn, 'o', $types, $params);
    if ($branchCondition !== '') {
        $where[] = $branchCondition;
    }

    $limit = max(1, min(10, $limit));
    $stmt = db_prepare($conn, "
        SELECT
            o.order_id,
            o.bill_number,
            o.order_date,
            o.order_source,
            o.branch_name,
            o.status,
            o.payment_status,
            o.total_price,
            car.plate_number,
            car.province,
            car.brand,
            car.model,
            car.profile_image_path,
            car.profile_image_name
        FROM orders o
        INNER JOIN cars car ON car.car_id = o.car_id
        WHERE " . implode(' AND ', $where) . "
        ORDER BY o.order_date DESC, o.order_id DESC
        LIMIT {$limit}
    ");
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
    $rows = array();

    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }

    $stmt->close();

    $orderIds = array_column($rows, 'order_id');
    $serviceSummaryMap = order_service_summary_map($conn, $orderIds);
    $paymentSummaryMap = order_payment_summary_map($conn, $orderIds);

    foreach ($rows as &$row) {
        $orderId = (int) ($row['order_id'] ?? 0);
        $serviceSummary = $serviceSummaryMap[$orderId] ?? array();
        $paymentSummary = $paymentSummaryMap[$orderId] ?? order_payment_summary_defaults();
        $row['service_names'] = (string) ($serviceSummary['service_names'] ?? '');
        $row['item_count'] = (int) ($serviceSummary['item_count'] ?? 0);
        $row['paid_amount'] = (float) ($paymentSummary['total_amount'] ?? 0);
        $row['detail_href'] = notification_center_order_href($conn, $row);
    }
    unset($row);

    return $rows;
}

function open_bill_view_selected_context(mysqli $conn, int $customerId, int $carId): ?array
{
    $vehicle = find_customer_record_by_ids($conn, $customerId, $carId);
    if (!$vehicle) {
        return null;
    }

    return array(
        'vehicle' => $vehicle,
        'summary' => open_bill_view_customer_summary($conn, $customerId),
        'recent_orders' => open_bill_view_recent_orders($conn, $customerId),
    );
}

function open_bill_render_selected_context_html(mysqli $conn, array $selectedContext): string
{
    $selectedVehicle = $selectedContext['vehicle'] ?? null;
    $selectedSummary = $selectedContext['summary'] ?? null;
    $recentOrders = $selectedContext['recent_orders'] ?? array();

    if (!is_array($selectedVehicle) || !is_array($selectedSummary)) {
        return '';
    }

    $selectedVehicleName = trim((string) (($selectedVehicle['brand'] ?? '') . ' ' . ($selectedVehicle['model'] ?? '')));
    $selectedGroupLabel = customer_group_label((string) ($selectedSummary['customer_group'] ?? 'member'));
    $selectedLevelLabel = customer_group_key((string) ($selectedSummary['customer_group'] ?? 'member')) === 'guest'
        ? '-'
        : member_level((int) ($selectedSummary['loyalty_points'] ?? 0));
    $profileImageUrl = trim((string) ($selectedVehicle['profileImageUrl'] ?? ''));
    $profileImageName = trim((string) ($selectedVehicle['profileImageName'] ?? ''));

    $bookingUrl = 'booking.php?' . http_build_query(array(
        'open_bill_customer_id' => (int) ($selectedVehicle['customerId'] ?? 0),
        'open_bill_car_id' => (int) ($selectedVehicle['carId'] ?? 0),
    ));
    $quickServiceUrl = 'quick_service.php?' . http_build_query(array(
        'open_bill_customer_id' => (int) ($selectedVehicle['customerId'] ?? 0),
        'open_bill_car_id' => (int) ($selectedVehicle['carId'] ?? 0),
    ));

    $memberLookupValue = trim((string) ($selectedSummary['phone'] ?? ''));
    if ($memberLookupValue === '') {
        $memberLookupValue = trim((string) ($selectedVehicle['plateNumber'] ?? ''));
    }

    $memberUrl = 'member.php?' . http_build_query(array(
        'view' => 'profile',
        'customer_id' => (int) ($selectedVehicle['customerId'] ?? 0),
        'car_id' => (int) ($selectedVehicle['carId'] ?? 0),
        'q' => $memberLookupValue,
    ));

    $canOpenBooking = can_access($conn, 'booking');
    $canOpenQuickService = can_access($conn, 'quick_service');
    $canOpenMemberInfo = can_access_member_area($conn);
    $latestVisit = format_datetime($selectedSummary['latest_visit'] ? (string) $selectedSummary['latest_visit'] : null);
    $profilePhotoAlt = $profileImageName !== '' ? $profileImageName : open_bill_view_text('รูปรถ', 'Vehicle photo');
    $profilePhotoTitle = open_bill_view_text('รูปโปรไฟล์รถ', 'Vehicle profile photo');
    $profilePhotoZoomHint = open_bill_view_text('คลิกที่รูปเพื่อดูขนาดใหญ่', 'Click photo to view a larger image');

    ob_start();
    ?>
    <div data-open-bill-selected-section>
        <section class="grid grid-4 open-bill-stats-grid" style="margin-top: 18px;">
            <article class="stat-card open-bill-stat-card">
                <p class="stat-label"><?= e(open_bill_view_text('กลุ่มลูกค้า', 'Customer group')) ?></p>
                <p class="stat-value"><?= e($selectedGroupLabel) ?></p>
            </article>
            <article class="stat-card open-bill-stat-card">
                <p class="stat-label"><?= e(open_bill_view_text('ระดับสมาชิก', 'Member level')) ?></p>
                <p class="stat-value"><?= e($selectedLevelLabel) ?></p>
            </article>
            <article class="stat-card open-bill-stat-card">
                <p class="stat-label"><?= e(open_bill_view_text('จำนวนรถ', 'Vehicles')) ?></p>
                <p class="stat-value"><?= (int) ($selectedSummary['vehicle_count'] ?? 0) ?></p>
            </article>
            <article class="stat-card open-bill-stat-card">
                <p class="stat-label"><?= e(open_bill_view_text('จำนวนครั้งใช้บริการ', 'Visits')) ?></p>
                <p class="stat-value"><?= (int) ($selectedSummary['visit_count'] ?? 0) ?></p>
            </article>
        </section>

        <div class="content-grid open-bill-context-grid" style="margin-top: 18px;">
            <section class="card open-bill-summary-card">
                <div class="section-head open-bill-section-head">
                    <div>
                        <h2 class="section-title"><?= e(open_bill_view_text('สรุปลูกค้าและรถ', 'Customer and vehicle summary')) ?></h2>
                    </div>
                </div>
                <div class="open-bill-vehicle-hero">
                    <figure class="open-bill-vehicle-photo-card">
                        <?php if ($profileImageUrl !== ''): ?>
                            <button
                                type="button"
                                class="open-bill-photo-trigger"
                                data-open-bill-photo-expand
                                data-photo-src="<?= e($profileImageUrl) ?>"
                                data-photo-alt="<?= e($profilePhotoAlt) ?>"
                                data-photo-title="<?= e($profilePhotoTitle) ?>"
                                aria-label="<?= e($profilePhotoZoomHint) ?>"
                            >
                                <img
                                    class="open-bill-vehicle-photo"
                                    src="<?= e($profileImageUrl) ?>"
                                    alt="<?= e($profilePhotoAlt) ?>"
                                >
                            </button>
                            <figcaption class="open-bill-photo-caption"><?= e($profilePhotoZoomHint) ?></figcaption>
                        <?php else: ?>
                            <div class="open-bill-vehicle-photo-placeholder">
                                <span class="open-bill-photo-placeholder-icon"><?= open_bill_view_icon_svg('camera') ?></span>
                                <strong><?= e(open_bill_view_text('ยังไม่มีรูปรถ', 'No vehicle photo')) ?></strong>
                            </div>
                        <?php endif; ?>
                    </figure>
                    <div class="member-profile-grid open-bill-profile-grid">
                        <div class="stack">
                            <span class="muted"><?= e(open_bill_view_text('ชื่อลูกค้า', 'Customer')) ?></span>
                            <strong><?= e((string) ($selectedSummary['name'] ?? '-')) ?></strong>
                        </div>
                        <div class="stack">
                            <span class="muted"><?= e(open_bill_view_text('เบอร์โทร', 'Phone')) ?></span>
                            <strong><?= e((string) (($selectedSummary['phone'] ?? '') !== '' ? $selectedSummary['phone'] : '-')) ?></strong>
                        </div>
                        <div class="stack">
                            <span class="muted"><?= e(open_bill_view_text('ทะเบียนรถ', 'Plate number')) ?></span>
                            <strong><?= e((string) ($selectedVehicle['plateNumber'] ?? '-')) ?></strong>
                        </div>
                        <div class="stack">
                            <span class="muted"><?= e(open_bill_view_text('จังหวัด', 'Province')) ?></span>
                            <strong><?= e((string) (($selectedVehicle['province'] ?? '') !== '' ? $selectedVehicle['province'] : '-')) ?></strong>
                        </div>
                        <div class="stack">
                            <span class="muted"><?= e(open_bill_view_text('รายละเอียดรถ', 'Vehicle details')) ?></span>
                            <strong><?= e($selectedVehicleName !== '' ? $selectedVehicleName : open_bill_view_text('ยังไม่มีรายละเอียดรถ', 'Vehicle details pending')) ?></strong>
                        </div>
                        <div class="stack">
                            <span class="muted"><?= e(open_bill_view_text('สีรถ', 'Color')) ?></span>
                            <strong><?= e((string) (($selectedVehicle['color'] ?? '') !== '' ? $selectedVehicle['color'] : '-')) ?></strong>
                        </div>
                        <div class="stack">
                            <span class="muted"><?= e(open_bill_view_text('รูปโปรไฟล์รถ', 'Vehicle profile photo')) ?></span>
                            <strong><?= e($profileImageUrl !== '' ? open_bill_view_text('บันทึกแล้ว', 'Saved') : open_bill_view_text('ยังไม่เพิ่มรูป', 'Not uploaded yet')) ?></strong>
                        </div>
                        <div class="stack">
                            <span class="muted"><?= e(open_bill_view_text('ใช้บริการล่าสุด', 'Latest visit')) ?></span>
                            <strong><?= e($latestVisit) ?></strong>
                        </div>
                    </div>
                </div>
            </section>

            <aside class="card open-bill-path-card">
                <div class="section-head open-bill-section-head">
                    <div>
                        <h2 class="section-title"><?= e(open_bill_view_text('เลือกช่องทางทำรายการ', 'Choose transaction path')) ?></h2>
                    </div>
                </div>
                <div class="open-bill-action-grid">
                    <article class="open-bill-action-card">
                        <div class="open-bill-action-card-head">
                            <span class="open-bill-action-icon is-booking"><?= open_bill_view_icon_svg('booking') ?></span>
                            <div class="open-bill-action-copy">
                                <strong><?= e(open_bill_view_text('Booking', 'Booking')) ?></strong>
                            </div>
                        </div>
                        <div class="open-bill-chip-row">
                            <span class="open-bill-chip"><?= e(open_bill_view_text('สร้างคิวเมื่อบันทึก', 'Queue on save')) ?></span>
                        </div>
                        <?php if ($canOpenBooking): ?>
                            <a class="button button-accent open-bill-cta-button" href="<?= e($bookingUrl) ?>">
                                <span class="open-bill-cta-copy">
                                    <?= open_bill_view_icon_svg('booking') ?>
                                    <span><?= e(open_bill_view_text('ไปที่ Booking', 'Go to Booking')) ?></span>
                                </span>
                                <?= open_bill_view_icon_svg('arrow-right') ?>
                            </a>
                        <?php else: ?>
                            <button class="button button-secondary open-bill-cta-button" type="button" disabled>
                                <span class="open-bill-cta-copy">
                                    <?= open_bill_view_icon_svg('booking') ?>
                                    <span><?= e(open_bill_view_text('ไม่มีสิทธิ์ Booking', 'Booking unavailable')) ?></span>
                                </span>
                            </button>
                        <?php endif; ?>
                    </article>

                    <article class="open-bill-action-card">
                        <div class="open-bill-action-card-head">
                            <span class="open-bill-action-icon is-quick-service"><?= open_bill_view_icon_svg('quick_service') ?></span>
                            <div class="open-bill-action-copy">
                                <strong><?= e(open_bill_view_text('Quick Service', 'Quick Service')) ?></strong>
                            </div>
                        </div>
                        <div class="open-bill-chip-row">
                            <span class="open-bill-chip"><?= e(open_bill_view_text('ไม่เข้า Queue', 'No queue')) ?></span>
                        </div>
                        <?php if ($canOpenQuickService): ?>
                            <a class="button button-accent open-bill-cta-button" href="<?= e($quickServiceUrl) ?>">
                                <span class="open-bill-cta-copy">
                                    <?= open_bill_view_icon_svg('quick_service') ?>
                                    <span><?= e(open_bill_view_text('ไปที่ Quick Service', 'Go to Quick Service')) ?></span>
                                </span>
                                <?= open_bill_view_icon_svg('arrow-right') ?>
                            </a>
                        <?php else: ?>
                            <button class="button button-secondary open-bill-cta-button" type="button" disabled>
                                <span class="open-bill-cta-copy">
                                    <?= open_bill_view_icon_svg('quick_service') ?>
                                    <span><?= e(open_bill_view_text('ไม่มีสิทธิ์ Quick Service', 'Quick Service unavailable')) ?></span>
                                </span>
                            </button>
                        <?php endif; ?>
                    </article>

                    <article class="open-bill-action-card">
                        <div class="open-bill-action-card-head">
                            <span class="open-bill-action-icon is-member"><?= open_bill_view_icon_svg('member') ?></span>
                            <div class="open-bill-action-copy">
                                <strong><?= e(open_bill_view_text('ข้อมูลสมาชิก', 'Member info')) ?></strong>
                            </div>
                        </div>
                        <div class="open-bill-chip-row">
                            <span class="open-bill-chip"><?= e(open_bill_view_text('ดูข้อมูลย้อนหลัง', 'Review history')) ?></span>
                        </div>
                        <?php if ($canOpenMemberInfo): ?>
                            <a class="button button-accent open-bill-cta-button" href="<?= e($memberUrl) ?>">
                                <span class="open-bill-cta-copy">
                                    <?= open_bill_view_icon_svg('member') ?>
                                    <span><?= e(open_bill_view_text('ดูข้อมูลสมาชิก', 'Open member info')) ?></span>
                                </span>
                                <?= open_bill_view_icon_svg('arrow-right') ?>
                            </a>
                        <?php else: ?>
                            <button class="button button-secondary open-bill-cta-button" type="button" disabled>
                                <span class="open-bill-cta-copy">
                                    <?= open_bill_view_icon_svg('member') ?>
                                    <span><?= e(open_bill_view_text('ไม่มีสิทธิ์ข้อมูลสมาชิก', 'Member info unavailable')) ?></span>
                                </span>
                            </button>
                        <?php endif; ?>
                    </article>
                </div>
            </aside>
        </div>

        <section class="table-card open-bill-history-card" style="margin-top: 18px;">
            <div class="section-head open-bill-section-head" style="padding: 18px 18px 0;">
                <div>
                    <h2 class="section-title"><?= e(open_bill_view_text('ประวัติใช้บริการล่าสุด', 'Recent service history')) ?></h2>
                </div>
            </div>
            <?php if (empty($recentOrders)): ?>
                <div class="empty-state" style="margin: 18px;"><?= e(open_bill_view_text('ยังไม่มีประวัติใช้บริการสำหรับลูกค้ารายนี้', 'No service history is available for this customer yet.')) ?></div>
            <?php else: ?>
                <table style="min-width: 920px;">
                    <thead>
                    <tr>
                        <th><?= e(open_bill_view_text('วันที่', 'Date')) ?></th>
                        <th><?= e(open_bill_view_text('เลขบิล', 'Bill')) ?></th>
                        <th><?= e(open_bill_view_text('ประเภทรายการ', 'Source')) ?></th>
                        <th><?= e(open_bill_view_text('รถ', 'Vehicle')) ?></th>
                        <th><?= e(open_bill_view_text('บริการ', 'Services')) ?></th>
                        <th><?= e(open_bill_view_text('สถานะ', 'Status')) ?></th>
                        <th><?= e(open_bill_view_text('ชำระเงิน', 'Payment')) ?></th>
                        <th><?= e(open_bill_view_text('ยอดรวม', 'Total')) ?></th>
                        <th><?= e(open_bill_view_text('ชำระแล้ว', 'Paid')) ?></th>
                        <th><?= e(open_bill_view_text('เปิดดู', 'Open')) ?></th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($recentOrders as $order): ?>
                        <?php
                        $billLabel = trim((string) ($order['bill_number'] ?? '')) !== ''
                            ? (string) $order['bill_number']
                            : '#' . (int) ($order['order_id'] ?? 0);
                        $historyVehicleName = trim((string) (($order['brand'] ?? '') . ' ' . ($order['model'] ?? '')));
                        ?>
                        <tr>
                            <td><?= e(format_datetime((string) ($order['order_date'] ?? ''))) ?></td>
                            <td><strong><?= e($billLabel) ?></strong></td>
                            <td><?= e(open_bill_view_order_source_label((string) ($order['order_source'] ?? 'booking'))) ?></td>
                            <td>
                                <div class="vehicle-profile-inline">
                                    <?= car_profile_photo_html($order, 'vehicle-profile-photo vehicle-profile-photo--sm', 'vehicle-profile-photo-placeholder vehicle-profile-photo-placeholder--sm') ?>
                                    <div class="stack">
                                    <strong><?= e((string) ($order['plate_number'] ?? '-')) ?></strong>
                                    <span class="muted"><?= e($historyVehicleName !== '' ? $historyVehicleName : open_bill_view_text('ยังไม่มีรายละเอียดรถ', 'Vehicle details pending')) ?></span>
                                    </div>
                                </div>
                            </td>
                            <td><?= e((string) (($order['service_names'] ?? '') !== '' ? $order['service_names'] : '-')) ?></td>
                            <td><span class="<?= e(status_class((string) ($order['status'] ?? 'waiting'))) ?>"><?= e(status_label((string) ($order['status'] ?? 'waiting'))) ?></span></td>
                            <td><span class="<?= e(payment_status_class((string) ($order['payment_status'] ?? 'unpaid'))) ?>"><?= e(payment_status_label((string) ($order['payment_status'] ?? 'unpaid'))) ?></span></td>
                            <td><?= format_money((float) ($order['total_price'] ?? 0)) ?></td>
                            <td><?= format_money((float) ($order['paid_amount'] ?? 0)) ?></td>
                            <td>
                                <?php if (trim((string) ($order['detail_href'] ?? '')) !== ''): ?>
                                    <a class="button button-secondary open-bill-mini-button" href="<?= e((string) $order['detail_href']) ?>">
                                        <?= open_bill_view_icon_svg('arrow-right') ?>
                                        <span><?= e(open_bill_view_text('เปิดดู', 'Open')) ?></span>
                                    </a>
                                <?php else: ?>
                                    <span class="muted">-</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </section>
    </div>
    <?php

    return trim((string) ob_get_clean());
}
