<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/layout.php';

require_permission($conn, 'queue');

ensure_order_branch_column($conn);
ensure_order_return_column($conn);
ensure_order_slide_send_column($conn);
ensure_order_service_at_column($conn);
ensure_order_bill_number_column($conn);
ensure_order_detail_options_column($conn);
ensure_order_detail_item_note_column($conn);
ensure_order_cancellation_columns($conn);
ensure_order_reopen_column($conn);
ensure_order_split_deposit_columns($conn);
ensure_payment_tender_columns($conn);
ensure_payment_slip_columns($conn);
ensure_car_profile_columns($conn);

$paymentOldInput = pull_old_input();

$orderId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$orderId) {
    redirect_with_flash('dashboard.php', 'error', localized_flash_message('ไม่พบคิวงาน', 'Job was not found.'));
}

$jobStmt = db_prepare($conn, "
    SELECT
        o.order_id,
        o.bill_number,
        o.car_id,
        o.order_date,
        o.branch_name,
        o.scheduled_at,
        o.slide_send_at,
        o.service_at,
        o.return_at,
        o.started_at,
        o.finished_at,
        o.status,
        o.payment_status,
        o.total_price,
        o.deposit_amount,
        o.deposit_method,
        o.admin_deposit_amount,
        o.admin_deposit_method,
        o.branch_deposit_amount,
        o.branch_deposit_method,
        o.reopened_from_order_id,
        o.notes,
        reopened.bill_number AS reopened_from_bill_number,
        c.customer_id,
        c.name AS customer_name,
        c.phone,
        c.loyalty_points,
        car.plate_number,
        car.province,
        car.vehicle_type,
        car.brand,
        car.model,
        car.color,
        car.profile_image_path,
        car.profile_image_name,
        car.profile_image_mime_type,
        car.profile_image_uploaded_at,
        q.queue_number,
        q.created_at AS queued_at,
        COALESCE(paid.paid_amount, 0) AS paid_amount
    FROM orders o
    LEFT JOIN orders reopened ON reopened.order_id = o.reopened_from_order_id
    INNER JOIN customers c ON c.customer_id = o.customer_id
    INNER JOIN cars car ON car.car_id = o.car_id
    LEFT JOIN queue q ON q.order_id = o.order_id
    LEFT JOIN (
        SELECT order_id, SUM(amount) AS paid_amount
        FROM payments
        GROUP BY order_id
    ) paid ON paid.order_id = o.order_id
    WHERE o.order_id = ?
    LIMIT 1
");
$jobStmt->bind_param('i', $orderId);
$jobStmt->execute();
$job = $jobStmt->get_result()->fetch_assoc();
$jobStmt->close();

if (!$job) {
    redirect_with_flash('dashboard.php', 'error', localized_flash_message('ไม่พบคิวงาน', 'Job was not found.'));
}

if (!auth_can_access_branch($conn, (string) ($job['branch_name'] ?? ''))) {
    redirect_with_flash('dashboard.php', 'error', localized_flash_message('คุณไม่มีสิทธิ์เข้าถึงสาขานี้', 'You do not have access to this branch.'));
}

$details = array();
$detailStmt = db_prepare($conn, "
    SELECT detail_id, service_id, service_name_snapshot, price, duration_minutes, service_options, item_note
    FROM order_details
    WHERE order_id = ?
    ORDER BY detail_id ASC
");
$detailStmt->bind_param('i', $orderId);
$detailStmt->execute();
$detailResult = $detailStmt->get_result();
while ($row = $detailResult->fetch_assoc()) {
    $details[] = $row;
}
$detailStmt->close();

$payments = array();
$paymentStmt = db_prepare($conn, "
    SELECT payment_id, payment_method, amount, received_amount, change_amount, note, payment_date, slip_file_path, slip_file_name
    FROM payments
    WHERE order_id = ?
    ORDER BY payment_date DESC, payment_id DESC
");
$paymentStmt->bind_param('i', $orderId);
$paymentStmt->execute();
$paymentResult = $paymentStmt->get_result();
while ($row = $paymentResult->fetch_assoc()) {
    $payments[] = $row;
}
$paymentStmt->close();

$adminDepositPayment = null;
$branchDepositPayment = null;
foreach ($payments as $paymentRow) {
    $paymentNote = trim((string) ($paymentRow['note'] ?? ''));
    if ($paymentNote === 'Admin deposit at booking' && $adminDepositPayment === null) {
        $adminDepositPayment = $paymentRow;
    }
    if ($paymentNote === 'Branch deposit at booking' && $branchDepositPayment === null) {
        $branchDepositPayment = $paymentRow;
    }
}

$openDepositRequested = (int) (filter_input(INPUT_GET, 'open_deposit', FILTER_VALIDATE_INT) ?: 0) === 1;

$balance = max(0.0, (float) $job['total_price'] - (float) $job['paid_amount']);
$brandModel = trim((string) (($job['brand'] ?? '') . ' ' . ($job['model'] ?? '')));
$queueNumber = (int) ($job['queue_number'] ?? 0);
$billNumber = (string) ($job['bill_number'] ?? '');
$billLabel = $billNumber !== '' ? $billNumber : '#' . (int) $job['order_id'];
$reopenedFromOrderId = (int) ($job['reopened_from_order_id'] ?? 0);
$reopenedFromBillNumber = (string) ($job['reopened_from_bill_number'] ?? '');
$reopenedFromLabel = $reopenedFromOrderId > 0 ? ($reopenedFromBillNumber !== '' ? $reopenedFromBillNumber : '#' . $reopenedFromOrderId) : '';
$jobStatus = (string) $job['status'];
$isFullyPaid = (string) $job['payment_status'] === 'paid' || ((float) $job['total_price'] > 0.0 && $balance <= 0.0);
$isJobDone = $jobStatus === 'done';
$isJobCancelled = $jobStatus === 'cancelled';
$isBillClosed = $isJobDone || $isFullyPaid;
$canReceiveQueuePayment = can_access($conn, 'queue_payment');
$canStartWaiting = can_access($conn, 'queue_start_waiting');
$canControlBill = can_access($conn, 'queue_bill_control');
$canCancelWaiting = can_access($conn, 'queue_cancel_waiting');
$canCancelClosedBill = can_access($conn, 'queue_cancel_closed');
$canCancelOpenBill = can_access($conn, 'queue_cancel_open');
$canEditOpenQueue = can_access($conn, 'queue_edit_open');
$canEditAdminDeposit = can_access($conn, 'booking_deposit_admin_edit');
$canEditBranchDeposit = can_access($conn, 'booking_deposit_branch_edit');
$canEditJob = $canEditOpenQueue && !$isBillClosed && !$isJobCancelled;
$canCancelBill = !$isJobCancelled && (
    ($jobStatus === 'waiting' && $canCancelWaiting)
    || ($jobStatus !== 'waiting' && $isBillClosed && $canCancelClosedBill)
    || ($jobStatus !== 'waiting' && !$isBillClosed && $canCancelOpenBill)
);
$depositEditPaymentId = (int) ($paymentOldInput['edit_deposit_payment_id'] ?? (filter_input(INPUT_GET, 'edit_deposit', FILTER_VALIDATE_INT) ?: 0));
$depositEditScopeValue = trim((string) ($paymentOldInput['edit_deposit_scope'] ?? ''));
$depositEditAmountValue = trim((string) ($paymentOldInput['deposit_edit_amount'] ?? ''));
$paymentMethods = quick_service_payment_methods();
$depositEditMethodValue = trim((string) ($paymentOldInput['deposit_edit_method'] ?? ''));
$hasDepositPermissions = !$isJobCancelled && ($canEditAdminDeposit || $canEditBranchDeposit);
$hasDepositPaymentRows = $adminDepositPayment !== null || $branchDepositPayment !== null;
$hasAnyDepositRecord = $hasDepositPaymentRows
    || (float) ($job['admin_deposit_amount'] ?? 0) > 0
    || (float) ($job['branch_deposit_amount'] ?? 0) > 0;
$showDepositManagement = $hasDepositPermissions
    && ($openDepositRequested || $depositEditPaymentId > 0 || $depositEditScopeValue !== '');
$depositPanelBasePath = 'job_details.php?id=' . (int) $job['order_id'] . '&open_deposit=1';
$depositPanelPath = $depositPanelBasePath . '#deposit-management';
$adminDepositPanelPath = $depositPanelBasePath . '#deposit-admin-form';
$branchDepositPanelPath = $depositPanelBasePath . '#deposit-branch-form';
$canAddPayment = $canReceiveQueuePayment && $isJobDone && !$isFullyPaid && !$isJobCancelled;
$lastPaymentMethod = trim((string) ($_SESSION['booking_payment_method'] ?? 'cash'));
if (!empty($payments)) {
    $lastPaymentMethod = trim((string) ($payments[0]['payment_method'] ?? $lastPaymentMethod));
}
if (!array_key_exists($lastPaymentMethod, $paymentMethods)) {
    $lastPaymentMethod = 'cash';
}
$selectedPaymentMethod = old_value($paymentOldInput, 'payment_method', $lastPaymentMethod);
if (!array_key_exists($selectedPaymentMethod, $paymentMethods)) {
    $selectedPaymentMethod = $lastPaymentMethod;
}
$receivedAmountValue = old_value($paymentOldInput, 'received_amount', $balance > 0 ? number_format($balance, 2, '.', '') : '');
$paymentNoteValue = old_value($paymentOldInput, 'note');
$qrAvailable = quick_service_qr_available((string) ($job['branch_name'] ?? ''), 'queue_payment')
    || quick_service_qr_available('', 'queue_payment')
    || quick_service_qr_available((string) ($job['branch_name'] ?? ''), 'quick_service')
    || quick_service_qr_available('', 'quick_service');

$scheduledAtParts = datetime_form_parts($job['scheduled_at'] ?? null);
$slideSendAtParts = datetime_form_parts($job['slide_send_at'] ?? null);
$serviceAtParts = datetime_form_parts($job['service_at'] ?? null);
$returnAtParts = datetime_form_parts($job['return_at'] ?? null);

$currentProvince = trim((string) ($job['province'] ?? ''));
$provinceOptions = vehicle_province_options($currentProvince);
$currentBrand = trim((string) ($job['brand'] ?? ''));
$vehicleBrands = vehicle_brand_options($conn, array($currentBrand));

$branchNames = authorized_order_branch_options($conn);
$currentBranchName = trim((string) ($job['branch_name'] ?? ''));
if ($currentBranchName !== '' && !in_array($currentBranchName, $branchNames, true)) {
    $branchNames[] = $currentBranchName;
}

$selectedServiceIds = array();
$selectedFilmOptions = array();
$selectedPackageUsage = array();
$selectedServiceNotes = array();
foreach ($details as $detail) {
    $detailServiceId = (int) $detail['service_id'];
    $selectedServiceIds[] = $detailServiceId;

    $detailItemNote = trim((string) ($detail['item_note'] ?? ''));
    if ($detailServiceId > 0 && $detailItemNote !== '') {
        $selectedServiceNotes[$detailServiceId] = $detailItemNote;
    }

    $decodedOptions = json_decode((string) ($detail['service_options'] ?? ''), true);

    if (is_array($decodedOptions)) {
        if (empty($selectedFilmOptions) && ((string) ($decodedOptions['type'] ?? '') === 'window_tint' || order_option_is_film_service_name((string) $detail['service_name_snapshot']))) {
            $selectedFilmOptions = $decodedOptions;
        }

        if (isset($decodedOptions['package_usage']) && is_array($decodedOptions['package_usage'])) {
            $selectedPackageUsage[(int) $detail['service_id']] = (int) ($decodedOptions['package_usage']['customer_package_item_id'] ?? 0);
        }
    }
}

$selectedServiceIds = array_values(array_unique(array_filter($selectedServiceIds)));
$serviceOptions = service_catalog_rows($conn, array(
    'service_types' => array('main_service', 'sub_service', 'package'),
    'active_only' => true,
    'include_inactive_ids' => $selectedServiceIds,
));
$serviceSelectionCatalog = service_selection_catalog($conn, array(
    'active_only' => true,
    'include_inactive_ids' => $selectedServiceIds,
));
$packageServiceOptions = service_catalog_rows($conn, array(
    'service_type' => 'package',
    'active_only' => true,
    'include_inactive_ids' => $selectedServiceIds,
));
$availablePackageBalanceMap = service_customer_package_balance_map($conn, (int) ($job['customer_id'] ?? 0), (int) ($job['car_id'] ?? 0));
$currentPackageUsageRows = service_order_package_usage_rows($conn, $orderId, false);

foreach ($currentPackageUsageRows as $packageUsageRow) {
    $serviceId = (int) ($packageUsageRow['service_id'] ?? 0);
    $customerPackageItemId = (int) ($packageUsageRow['customer_package_item_id'] ?? 0);

    if ($serviceId <= 0 || $customerPackageItemId <= 0) {
        continue;
    }

    if (!isset($availablePackageBalanceMap[$serviceId])) {
        $availablePackageBalanceMap[$serviceId] = array();
    }

    $exists = false;
    foreach ($availablePackageBalanceMap[$serviceId] as $balanceRow) {
        if ((int) ($balanceRow['customer_package_item_id'] ?? 0) === $customerPackageItemId) {
            $exists = true;
            break;
        }
    }

    if (!$exists) {
        $availablePackageBalanceMap[$serviceId][] = array(
            'customer_package_item_id' => $customerPackageItemId,
            'customer_package_id' => 0,
            'sub_service_id' => $serviceId,
            'service_name_snapshot' => (string) ($packageUsageRow['service_name_snapshot'] ?? ''),
            'remaining_uses' => 1,
            'package_name_snapshot' => (string) ($packageUsageRow['package_name_snapshot'] ?? ''),
            'vehicle_scope' => normalize_package_vehicle_scope((string) ($packageUsageRow['vehicle_scope'] ?? 'member')),
            'car_id' => (int) ($packageUsageRow['car_id'] ?? 0),
            'plate_number' => (string) ($packageUsageRow['plate_number'] ?? ''),
            'order_id' => (int) ($packageUsageRow['package_order_id'] ?? 0),
            'created_at' => '',
        );
    }
}

$filmFrontServiceId = (int) ($selectedFilmOptions['front_service_id'] ?? 0);
$filmSunroofServiceId = (int) ($selectedFilmOptions['sunroof_service_id'] ?? 0);
$filmFrontSideServiceId = (int) ($selectedFilmOptions['front_side_service_id'] ?? 0);
$filmRearSideServiceId = (int) ($selectedFilmOptions['rear_side_service_id'] ?? 0);
$filmRearServiceId = (int) ($selectedFilmOptions['rear_service_id'] ?? 0);
$filmNotes = trim((string) ($selectedFilmOptions['notes'] ?? ''));
$hasFilmServices = false;
$selectedGroupChoices = array();
$windowFilmGroups = array();

foreach ($serviceOptions as $serviceOption) {
    $isFilmService = service_row_is_film($serviceOption);
    $serviceId = (int) $serviceOption['service_id'];

    if ($isFilmService) {
        $hasFilmServices = true;
    }

    if ((string) ($serviceOption['service_type'] ?? '') === 'sub_service' && (int) ($serviceOption['group_id'] ?? 0) > 0) {
        $selectedGroupChoices[(int) ($serviceOption['main_service_id'] ?? 0)] = (int) ($serviceOption['group_id'] ?? 0);
    }
}

foreach ($serviceSelectionCatalog as $categoryRow) {
    foreach ((array) ($categoryRow['main_services'] ?? array()) as $mainServiceRow) {
        foreach ((array) ($mainServiceRow['groups'] ?? array()) as $groupRow) {
            if ((int) ($groupRow['show_window_film_details'] ?? 0) !== 1) {
                continue;
            }

            $windowFilmGroups[(int) ($groupRow['group_id'] ?? 0)] = $groupRow;
        }
    }
}

if ((int) ($selectedFilmOptions['main_service_id'] ?? 0) > 0 && (int) ($selectedFilmOptions['group_id'] ?? 0) > 0) {
    $selectedGroupChoices[(int) $selectedFilmOptions['main_service_id']] = (int) $selectedFilmOptions['group_id'];
}

$selectedWindowFilmGroupId = 0;
foreach ($selectedGroupChoices as $mainServiceId => $groupId) {
    if (isset($windowFilmGroups[$groupId])) {
        $selectedWindowFilmGroupId = $groupId;
        break;
    }
}

$selectedWindowFilmGroup = $selectedWindowFilmGroupId > 0 ? ($windowFilmGroups[$selectedWindowFilmGroupId] ?? null) : null;

$serviceItemNoteLabel = ui_text('หมายเหตุรายการ', 'Item note');
$serviceItemNotePlaceholder = ui_text('เช่น รายละเอียดเฉพาะของบริการนี้', 'Specific note for this item');

$renderSelectableService = static function (array $service) use ($selectedServiceIds, $selectedPackageUsage, $selectedServiceNotes, $availablePackageBalanceMap, $serviceItemNoteLabel, $serviceItemNotePlaceholder): void {
    $serviceId = (int) ($service['service_id'] ?? 0);
    $serviceType = (string) ($service['service_type'] ?? 'sub_service');
    $checked = in_array($serviceId, $selectedServiceIds, true) ? 'checked' : '';
    $isFilmService = service_row_is_film($service);
    $groupName = trim((string) ($service['group_name'] ?? ''));
    $packageBalances = $serviceType === 'sub_service' ? ($availablePackageBalanceMap[$serviceId] ?? array()) : array();
    $selectedPackageItemId = (int) ($selectedPackageUsage[$serviceId] ?? 0);
    $serviceNote = trim((string) ($selectedServiceNotes[$serviceId] ?? ''));
    $serviceMeta = array();

    if ($serviceType === 'main_service') {
        $serviceMeta[] = ui_text('บริการหลัก', 'Main Service');
    } elseif ($serviceType === 'sub_service') {
        $serviceMeta[] = ui_text('บริการย่อย', 'Sub Service');
    }

    if ($groupName !== '') {
        $serviceMeta[] = $groupName;
    }

    $serviceMeta[] = format_money($service['price']) . ' THB';

    if ((int) ($service['is_active'] ?? 0) !== 1) {
        $serviceMeta[] = ui_text('ปิดใช้งาน', 'Inactive');
    }
    ?>
    <label class="service-option">
        <input
            type="checkbox"
            name="service_ids[]"
            value="<?= $serviceId ?>"
            data-service-option
            data-price="<?= e((string) $service['price']) ?>"
            <?= $isFilmService ? 'data-film-service="1"' : '' ?>
            <?= $checked ?>
        >
        <span>
            <strong><?= e((string) ($service['service_name'] ?? '')) ?></strong>
            <?php if ($description = trim((string) ($service['description'] ?? ''))): ?>
                <span class="muted"><?= e($description) ?></span>
            <?php endif; ?>
            <span class="service-meta">
                <?php foreach ($serviceMeta as $metaItem): ?>
                    <span><?= e($metaItem) ?></span>
                <?php endforeach; ?>
            </span>
            <?php if ($serviceType === 'sub_service'): ?>
                <span
                    class="package-usage-picker"
                    data-package-usage-container
                    data-service-id="<?= $serviceId ?>"
                    <?= empty($packageBalances) ? 'hidden' : '' ?>
                >
                    <span class="muted"><?= e(ui_text('ใช้สิทธิ์แพ็กเกจ', 'Package usage')) ?></span>
                    <select
                        name="package_usage[<?= $serviceId ?>]"
                        data-package-usage
                        data-service-price="<?= e((string) $service['price']) ?>"
                        <?= $checked && !empty($packageBalances) ? '' : 'disabled' ?>
                    >
                        <option value=""><?= e(ui_text('คิดราคาปกติ', 'Charge normal price')) ?></option>
                        <?php foreach ($packageBalances as $packageBalance): ?>
                            <?php $customerPackageItemId = (int) ($packageBalance['customer_package_item_id'] ?? 0); ?>
                            <option value="<?= $customerPackageItemId ?>" <?= $selectedPackageItemId === $customerPackageItemId ? 'selected' : '' ?>>
                                <?= e((string) $packageBalance['package_name_snapshot']) ?> / <?= e(package_vehicle_scope_note($packageBalance)) ?> / <?= e(strtr(ui_text('คงเหลือ {count} ครั้ง', '{count} left'), array('{count}' => (string) ((int) ($packageBalance['remaining_uses'] ?? 0))))) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </span>
            <?php endif; ?>
            <span class="service-item-note">
                <span class="muted"><?= e($serviceItemNoteLabel) ?></span>
                <input
                    type="text"
                    name="service_notes[<?= $serviceId ?>]"
                    value="<?= e($serviceNote) ?>"
                    placeholder="<?= e($serviceItemNotePlaceholder) ?>"
                    data-service-note
                    <?= $checked ? '' : 'disabled' ?>
                >
            </span>
        </span>
    </label>
    <?php
};

$jobStatusReturnTo = 'job_details.php?id=' . (int) $job['order_id'];
$renderJobStatusAction = static function (
    int $orderId,
    string $nextStatus,
    string $label,
    string $buttonClass,
    string $returnTo
): string {
    $submissionScope = 'queue_status_' . $orderId . '_' . $nextStatus;

    return '<form class="inline-form" method="POST" action="../process/update_job_status.php">'
        . csrf_input('queue_status')
        . submission_input($submissionScope)
        . '<input type="hidden" name="order_id" value="' . $orderId . '">'
        . '<input type="hidden" name="status" value="' . e($nextStatus) . '">'
        . '<input type="hidden" name="return_to" value="' . e($returnTo) . '">'
        . '<button class="' . e($buttonClass) . '" type="submit">' . e($label) . '</button>'
        . '</form>';
};

$pageTitle = ui_text('คิวงาน', 'Job details');
$billHeadingLabel = ui_text('บิล', 'Bill');
$jobPrefixLabel = ui_text('งาน', 'Job');
$queueLabel = ui_text('คิว', 'Queue');
$backToQueueLabel = ui_text('กลับไปหน้าคิว', 'Back to queue');
$startJobLabel = ui_text('เริ่มงาน', 'Start job');
$backToWaitingLabel = ui_text('ย้อนกลับไปรอคิว', 'Back to waiting');
$completeJobLabel = ui_text('ปิดงาน', 'Complete job');
$backToServiceLabel = ui_text('กลับไปกำลังให้บริการ', 'Back to service');
$reopenBillLabel = ui_text('เปิดบิลใหม่', 'Reopen bill');
$cancelBillLabel = ui_text('ยกเลิกบิล', 'Cancel bill');
$statusShortLabel = ui_text('สถานะ', 'Status');
$paymentShortLabel = ui_text('การชำระเงิน', 'Payment');
$totalShortLabel = ui_text('ยอดรวม', 'Total');
$paidShortLabel = ui_text('ชำระแล้ว', 'Paid');
$balanceShortLabel = ui_text('คงค้าง', 'Balance');
$customerVehicleLabel = ui_text('ข้อมูลลูกค้าและรถ', 'Customer and vehicle');
$memberLevelLabel = ui_text('ระดับสมาชิก', 'Member level');
$pointsLabel = ui_text('คะแนน', 'points');
$customerLabel = ui_text('ลูกค้า', 'Customer');
$vehicleLabel = ui_text('รถ', 'Vehicle');
$vehicleDetailsPendingLabel = ui_text('ยังไม่มีรายละเอียดรถ', 'Vehicle details pending');
$billNoLabel = ui_text('เลขที่บิล', 'Bill no.');
$referenceLabel = ui_text('อ้างอิง', 'Ref.');
$branchLabel = ui_text('สาขา', 'Branch');
$createdLabel = ui_text('สร้างเมื่อ', 'Created');
$phoneLabel = ui_text('เบอร์โทร', 'Phone');
$plateNumberLabel = ui_text('ทะเบียนรถ', 'Plate number');
$provinceLabel = ui_text('จังหวัด', 'Province');
$selectProvinceLabel = ui_text('เลือกจังหวัด', 'Select province');
$brandLabel = ui_text('ยี่ห้อ', 'Brand');
$selectBrandLabel = ui_text('เลือกยี่ห้อ', 'Select brand');
$modelLabel = ui_text('รุ่น', 'Model');
$colorLabel = ui_text('สี', 'Color');
$selectBranchLabel = ui_text('เลือกสาขา', 'Select branch');
$saveCustomerVehicleLabel = ui_text('บันทึกข้อมูลลูกค้าและรถ', 'Save customer and vehicle');
$billDataLockedLabel = ui_text('ข้อมูลบิลถูกล็อกแล้ว', 'Bill data is locked.');
$selectedServicesLabel = ui_text('บริการที่เลือก', 'Selected services');
$serviceItemCountLabel = ui_text('{count} รายการบริการ', '{count} service item(s)');
$serviceLabel = ui_text('บริการ', 'Service');
$priceLabel = ui_text('ราคา', 'Price');
$serviceSelectionEmptyLabel = ui_text('ยังไม่มีบริการที่เปิดใช้งานอยู่', 'No active services are available.');
$categoryLabel = ui_text('หมวดหมู่', 'Category');
$serviceGroupLabel = ui_text('กลุ่มบริการ', 'Group');
$serviceGroupStepLabel = ui_text('ขั้นตอนที่ 2: เลือกกลุ่มบริการ', 'Step 2: Choose service group');
$subServiceStepLabel = ui_text('ขั้นตอนที่ 3: เลือกบริการย่อย', 'Step 3: Choose sub service');
$windowFilmDetailsLabel = ui_text('รายละเอียดฟิล์ม', 'Window film details');
$windowFilmHelperLabel = ui_text('เลือกบริการย่อยของกระจกแต่ละตำแหน่งจากกลุ่มบริการที่เลือก', 'Choose the sub service for each glass position from the selected service group.');
$frontGlassLabel = ui_text('กระจกหน้า', 'Front glass');
$sunroofLabel = ui_text('ซันรูฟ', 'Sunroof');
$frontSideGlassLabel = ui_text('กระจกข้างคู่หน้า', 'Front side glass');
$rearSideGlassLabel = ui_text('กระจกข้างคู่หลัง', 'Rear side glass');
$rearGlassLabel = ui_text('กระจกหลัง', 'Rear glass');
$frontSideShortLabel = ui_text('ข้างหน้า', 'Front side');
$rearSideShortLabel = ui_text('ข้างหลัง', 'Rear side');
$selectLabel = ui_text('เลือก', 'Select');
$filmNotesLabel = ui_text('หมายเหตุฟิล์ม', 'Film notes');
$selectedServicesLockedLabel = ui_text('รายการบริการที่เลือกถูกล็อกแล้ว', 'Selected services are locked.');
$notesLabel = ui_text('หมายเหตุบิล', 'Bill note');
$availablePackagesLabel = ui_text('แพ็กเกจที่ใช้ได้', 'Available packages');
$paymentSummaryLabel = ui_text('สรุปการชำระเงิน', 'Payment summary');
$billTotalLabel = ui_text('ยอดรวมบิล', 'Bill total');
$paymentMethodLabel = ui_text('วิธีชำระเงิน', 'Payment method');
$receivedNowLabel = ui_text('รับเงินครั้งนี้', 'Received now');
$paymentValidationLabel = ui_text('สามารถบันทึกรับชำระได้มากกว่าหนึ่งครั้ง และบิลจะปิดอัตโนมัติเมื่อยอดชำระรวมครบตามจำนวนที่ต้องชำระ', 'Payment can be recorded more than once. The bill will close automatically only when the total paid reaches the amount due.');
$qrPaymentLabel = ui_text('ชำระด้วย QR', 'QR payment');
$qrPaymentHintLabel = ui_text('สแกนเพื่อรับชำระเงิน', 'Scan to receive payment.');
$queuePaymentQrLabel = ui_text('คิวอาร์ชำระเงินคิวงาน', 'Queue payment QR');
$receiptNoteLabel = ui_text('หมายเหตุในใบเสร็จ', 'Receipt note');
$paymentActionLabel = ui_text('ชำระเงิน', 'Payment');
$paymentAfterDoneLabel = ui_text('บันทึกรับชำระได้หลังจากงานเสร็จแล้ว', 'Payment can be saved after the job is completed.');
$noPaymentPermissionLabel = ui_text('คุณไม่มีสิทธิ์รับชำระเงินในบิลนี้', 'You do not have permission to receive payment on this bill.');
$bookingDepositsLabel = ui_text('มัดจำการจอง', 'Booking deposits');
$bookingDepositsHelperLabel = ui_text('เพิ่ม แก้ไข หรือลบมัดจำการจองได้ที่นี่ หากพลาดตอนเปิดบิลครั้งแรก', 'Add, edit or delete booking deposits here when they were missed during the original booking.');
$depositAmountLabel = ui_text('จำนวนเงินมัดจำ', 'Deposit amount');
$bookingAdminDepositQrLabel = ui_text('คิวอาร์มัดจำ Booking @Admin', 'Booking admin deposit QR');
$bookingBranchDepositQrLabel = ui_text('คิวอาร์มัดจำ Booking @Branch', 'Booking branch deposit QR');
$saveDepositAdminLabel = ui_text('บันทึกมัดจำ @Admin', 'Save Deposit @Admin');
$addDepositAdminLabel = ui_text('เพิ่มมัดจำ @Admin', 'Add Deposit @Admin');
$deleteDepositAdminLabel = ui_text('ลบมัดจำ @Admin', 'Delete Deposit @Admin');
$deleteDepositAdminConfirmLabel = ui_text('ลบรายการมัดจำ @Admin นี้หรือไม่', 'Delete this Admin deposit record?');
$saveDepositBranchLabel = ui_text('บันทึกมัดจำ @Branch', 'Save Deposit @Branch');
$addDepositBranchLabel = ui_text('เพิ่มมัดจำ @Branch', 'Add Deposit @Branch');
$deleteDepositBranchLabel = ui_text('ลบมัดจำ @Branch', 'Delete Deposit @Branch');
$deleteDepositBranchConfirmLabel = ui_text('ลบรายการมัดจำ @Branch นี้หรือไม่', 'Delete this Branch deposit record?');
$paymentHistoryLabel = ui_text('ประวัติการชำระเงิน', 'Payment history');
$paymentRecordCountLabel = ui_text('{count} รายการ', '{count} record(s)');

$vehiclePhotoLabel = ui_text('รูปโปรไฟล์รถ', 'Vehicle profile photo');
$vehiclePhotoHelper = ui_text('อัปโหลดเมื่ออยากเปลี่ยนรูปประจำรถ ระบบจะไม่วิเคราะห์ข้อมูลจากรูป', 'Upload only when you want to replace the vehicle profile photo. The system will not analyze this image.');

$filmSearchPlaceholderLabel = ui_text('พิมพ์ชื่อบริการหรือ keyword', 'Type service name or keyword');
$filmSearchInvalidLabel = ui_text('กรุณาเลือกบริการจากรายการที่แนะนำ', 'Choose a service from the suggestions.');
$renderWindowFilmServiceSearch = static function (
    int $groupId,
    string $zoneKey,
    string $inputName,
    string $label,
    int $selectedServiceId,
    array $filmSearchOptions,
    string $listId,
    bool $enabled,
    string $placeholderLabel,
    string $invalidLabel
): void {
    $fieldId = 'film_' . $zoneKey . '_service_' . $groupId;
    $valueId = $fieldId . '_value';
    $selectedValue = (string) ($filmSearchOptions[$selectedServiceId] ?? '');
    $hiddenValue = $selectedValue !== '' ? (string) $selectedServiceId : '';
    ?>
    <div class="field film-service-search-field">
        <label for="<?= e($fieldId) ?>"><?= e($label) ?></label>
        <div class="film-service-search-control">
            <input
                id="<?= e($fieldId) ?>"
                type="search"
                value="<?= e($selectedValue) ?>"
                list="<?= e($listId) ?>"
                placeholder="<?= e($placeholderLabel) ?>"
                autocomplete="off"
                data-film-input
                data-film-search
                data-film-target="<?= e($valueId) ?>"
                data-film-invalid-message="<?= e($invalidLabel) ?>"
                <?= $enabled ? '' : 'disabled' ?>
            >
            <input
                id="<?= e($valueId) ?>"
                name="<?= e($inputName) ?>"
                type="hidden"
                value="<?= e($hiddenValue) ?>"
                data-film-input
                data-film-service-value
                <?= $enabled ? '' : 'disabled' ?>
            >
        </div>
    </div>
    <?php
};

render_page_start($pageTitle, 'queue', array('translation_buffer' => false));
?>

<section class="page-hero">
    <div>
        <h1><?= e($billHeadingLabel) ?> <?= e($billLabel) ?></h1>
        <p><?= e($jobPrefixLabel) ?> #<?= (int) $job['order_id'] ?> / <?= e((string) $job['customer_name']) ?> / <?= e((string) ($job['plate_number'] ?? '-')) ?> / <?= e($queueLabel) ?> <?= $queueNumber > 0 ? '#' . $queueNumber : '-' ?></p>
    </div>
    <div class="hero-actions">
        <a class="button button-secondary" href="queue.php?status=<?= e((string) $job['status']) ?>"><?= e($backToQueueLabel) ?></a>
        <?php if ($jobStatus === 'waiting' && $canStartWaiting): ?>
            <?= $renderJobStatusAction((int) $job['order_id'], 'washing', $startJobLabel, 'button', $jobStatusReturnTo) ?>
        <?php elseif ($jobStatus === 'washing'): ?>
            <?php if ($canControlBill): ?>
                <?= $renderJobStatusAction((int) $job['order_id'], 'waiting', $backToWaitingLabel, 'button button-secondary', $jobStatusReturnTo) ?>
            <?php endif; ?>
            <?= $renderJobStatusAction((int) $job['order_id'], 'done', $completeJobLabel, 'button button-accent', $jobStatusReturnTo) ?>
        <?php elseif ($jobStatus === 'done' && $canControlBill): ?>
            <?= $renderJobStatusAction((int) $job['order_id'], 'washing', $backToServiceLabel, 'button button-secondary', $jobStatusReturnTo) ?>
        <?php elseif ($jobStatus === 'cancelled' && $canControlBill): ?>
            <?= $renderJobStatusAction((int) $job['order_id'], 'waiting', $reopenBillLabel, 'button button-secondary', $jobStatusReturnTo) ?>
        <?php endif; ?>
        <?php if ($canCancelBill): ?>
            <a class="button button-secondary" href="cancel_bill.php?id=<?= (int) $job['order_id'] ?>&return_to=<?= e(urlencode($jobStatusReturnTo)) ?>"><?= e($cancelBillLabel) ?></a>
        <?php endif; ?>
    </div>
</section>

<section class="grid job-summary-stats">
    <article class="stat-card">
        <p class="stat-label"><?= e($statusShortLabel) ?></p>
        <p><span class="<?= e(status_class((string) $job['status'])) ?>"><?= e(status_label((string) $job['status'])) ?></span></p>
    </article>
    <article class="stat-card">
        <p class="stat-label"><?= e($paymentShortLabel) ?></p>
        <p><span class="<?= e(payment_status_class((string) $job['payment_status'])) ?>"><?= e(payment_status_label((string) $job['payment_status'])) ?></span></p>
    </article>
    <article class="stat-card">
        <p class="stat-label"><?= e(ui_text('ยอดรวมบิล', 'Total')) ?></p>
        <p class="stat-value"><?= format_money((float) ($job['total_price'] ?? 0)) ?></p>
    </article>
    <article class="stat-card">
        <p class="stat-label"><?= e($paidShortLabel) ?></p>
        <p class="stat-value"><?= format_money($job['paid_amount']) ?></p>
    </article>
    <article class="stat-card">
        <p class="stat-label"><?= e($balanceShortLabel) ?></p>
        <p class="stat-value"><?= format_money($balance) ?></p>
    </article>
</section>

<div class="content-grid" style="margin-top: 18px;">
    <div class="grid">
        <section class="card">
            <div class="section-head">
                <div>
                    <h2 class="section-title"><?= e($customerVehicleLabel) ?></h2>
                    <p class="helper"><?= e($memberLevelLabel) ?>: <?= e(member_level((int) $job['loyalty_points'])) ?> / <?= (int) $job['loyalty_points'] ?> <?= e($pointsLabel) ?></p>
                </div>
                <div class="job-edit-actions">
                    <span class="plate"><?= e((string) $job['plate_number']) ?></span>
                    <?php if ($canEditJob): ?>
                        <button
                            class="button button-secondary"
                            type="button"
                            data-edit-toggle
                            data-closed-label="แก้ไข"
                            data-open-label="ซ่อน"
                            aria-controls="customer-vehicle-edit-form"
                            aria-expanded="false"
                        >แก้ไข</button>
                    <?php endif; ?>
                </div>
            </div>

            <div class="grid grid-2 job-meta-grid">
                <div class="stack">
                    <span class="muted"><?= e($customerLabel) ?></span>
                    <strong><?= e((string) $job['customer_name']) ?></strong>
                    <span><?= e((string) ($job['phone'] ?? '-')) ?></span>
                </div>
                <div class="stack">
                    <span class="muted"><?= e($vehicleLabel) ?></span>
                    <div class="vehicle-profile-inline">
                        <?= car_profile_photo_html($job, 'vehicle-profile-photo vehicle-profile-photo--sm', 'vehicle-profile-photo-placeholder vehicle-profile-photo-placeholder--sm') ?>
                        <div class="stack stack-tight">
                            <strong><?= e($brandModel !== '' ? $brandModel : $vehicleDetailsPendingLabel) ?></strong>
                            <span><?= e((string) ($job['color'] ?? '')) ?></span>
                        </div>
                    </div>
                </div>
                <div class="stack">
                    <span class="muted"><?= e($billNoLabel) ?></span>
                    <strong><?= e($billLabel) ?></strong>
                    <?php if ($reopenedFromLabel !== ''): ?>
                        <span class="muted"><?= e($referenceLabel) ?> <?= e($reopenedFromLabel) ?></span>
                    <?php endif; ?>
                </div>
                <div class="stack">
                    <span class="muted"><?= e($branchLabel) ?></span>
                    <strong><?= e((string) ($job['branch_name'] ?? '-')) ?></strong>
                </div>
                <div class="stack">
                    <span class="muted"><?= e($createdLabel) ?></span>
                    <strong><?= e(format_datetime((string) $job['order_date'])) ?></strong>
                </div>
                <div class="stack">
                    <span class="muted">วันสไลด์รับ</span>
                    <strong><?= e(format_datetime($job['scheduled_at'] ? (string) $job['scheduled_at'] : null)) ?></strong>
                </div>
                <div class="stack">
                    <span class="muted">วันสไลด์ส่ง</span>
                    <strong><?= e(format_datetime($job['slide_send_at'] ? (string) $job['slide_send_at'] : null)) ?></strong>
                </div>
                <div class="stack">
                    <span class="muted">วันเข้าใช้บริการ</span>
                    <strong><?= e(format_datetime($job['service_at'] ? (string) $job['service_at'] : null)) ?></strong>
                </div>
                <div class="stack">
                    <span class="muted">วันรับรถ</span>
                    <strong><?= e(format_datetime($job['return_at'] ? (string) $job['return_at'] : null)) ?></strong>
                </div>
            </div>

            <?php if ($canEditJob): ?>
                <form id="customer-vehicle-edit-form" method="POST" action="../process/update_job_info.php" enctype="multipart/form-data" style="margin-top: 18px;" hidden>
                    <?= csrf_input('job_info_update') ?>
                    <input type="hidden" name="order_id" value="<?= (int) $job['order_id'] ?>">
                    <div class="form-grid">
                        <div class="field">
                            <label for="phone"><?= e($phoneLabel) ?></label>
                            <input id="phone" name="phone" type="text" value="<?= e((string) ($job['phone'] ?? '')) ?>">
                        </div>

                        <div class="field">
                            <label for="plate_number"><?= e($plateNumberLabel) ?></label>
                            <input id="plate_number" name="plate_number" type="text" value="<?= e((string) $job['plate_number']) ?>" required>
                        </div>

                        <div class="field">
                            <label for="province"><?= e($provinceLabel) ?></label>
                            <select id="province" name="province">
                                <option value=""><?= e($selectProvinceLabel) ?></option>
                                <?php foreach ($provinceOptions as $provinceOption): ?>
                                    <option value="<?= e($provinceOption) ?>" <?= $currentProvince === $provinceOption ? 'selected' : '' ?>>
                                        <?= e(translate_text($provinceOption)) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="field">
                            <label for="brand"><?= e($brandLabel) ?></label>
                            <select id="brand" name="brand">
                                <option value=""><?= e($selectBrandLabel) ?></option>
                                <?php foreach ($vehicleBrands as $vehicleBrand): ?>
                                    <option value="<?= e($vehicleBrand) ?>" <?= $currentBrand === $vehicleBrand ? 'selected' : '' ?>>
                                        <?= e($vehicleBrand) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="field">
                            <label for="model"><?= e($modelLabel) ?></label>
                            <input id="model" name="model" type="text" value="<?= e((string) ($job['model'] ?? '')) ?>">
                        </div>

                        <div class="field">
                            <label for="color"><?= e($colorLabel) ?></label>
                            <input id="color" name="color" type="text" value="<?= e((string) ($job['color'] ?? '')) ?>">
                        </div>

                        <div class="field">
                            <label for="car_profile_photo"><?= e($vehiclePhotoLabel) ?></label>
                            <div class="vehicle-profile-inline" style="margin-bottom: 8px;">
                                <?= car_profile_photo_html($job, 'vehicle-profile-photo vehicle-profile-photo--sm', 'vehicle-profile-photo-placeholder vehicle-profile-photo-placeholder--sm') ?>
                                <span class="helper"><?= e($vehiclePhotoHelper) ?></span>
                            </div>
                            <div class="vehicle-photo-picker" data-photo-picker>
                                <input class="vehicle-photo-picker-input" id="car_profile_photo" name="car_profile_photo" type="file" accept="<?= e(car_profile_upload_accept_attribute()) ?>" data-photo-picker-input>
                                <div class="vehicle-photo-picker-surface">
                                    <span class="vehicle-photo-picker-icon"><?= app_button_icon_svg('camera') ?></span>
                                    <div class="vehicle-photo-picker-copy">
                                        <strong data-photo-picker-file-name><?= e(ui_text('ยังไม่ได้เลือกรูป', 'No image selected')) ?></strong>
                                        <span><?= e(ui_text('ถ่ายรูปจากกล้อง หรือเลือกรูปจากเครื่องในช่องเดียวกัน', 'Take a photo or choose an image from this single field.')) ?></span>
                                    </div>
                                    <div class="vehicle-photo-picker-actions">
                                        <button class="button button-secondary vehicle-photo-picker-button" type="button" data-photo-picker-camera><?= e(ui_text('ถ่ายรูป', 'Take photo')) ?></button>
                                        <button class="button button-ghost vehicle-photo-picker-button" type="button" data-photo-picker-select><?= e(ui_text('เลือกรูป', 'Choose image')) ?></button>
                                        <button class="button button-ghost vehicle-photo-picker-button" type="button" data-photo-picker-clear hidden><?= e(ui_text('ล้างรูป', 'Clear')) ?></button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="field">
                            <label for="branch_name"><?= e($branchLabel) ?></label>
                            <select id="branch_name" name="branch_name" required>
                                <option value=""><?= e($selectBranchLabel) ?></option>
                                <?php foreach ($branchNames as $branchName): ?>
                                    <option value="<?= e($branchName) ?>" <?= (($currentBranchName ?? '') === $branchName) ? 'selected' : '' ?>>
                                        <?= e($branchName) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="field datetime-split-field">
                            <label>วันสไลด์รับ</label>
                            <div class="datetime-split-grid">
                                <input id="scheduled_at_date" name="scheduled_at_date" type="date" value="<?= e($scheduledAtParts['date']) ?>">
                                <input id="scheduled_at_time" name="scheduled_at_time" type="time" value="<?= e($scheduledAtParts['time']) ?>" step="60">
                            </div>
                        </div>

                        <div class="field datetime-split-field">
                            <label>วันสไลด์ส่ง</label>
                            <div class="datetime-split-grid">
                                <input id="slide_send_at_date" name="slide_send_at_date" type="date" value="<?= e($slideSendAtParts['date']) ?>">
                                <input id="slide_send_at_time" name="slide_send_at_time" type="time" value="<?= e($slideSendAtParts['time']) ?>" step="60">
                            </div>
                        </div>

                        <div class="field datetime-split-field">
                            <label>วันเข้าใช้บริการ</label>
                            <div class="datetime-split-grid">
                                <input id="service_at_date" name="service_at_date" type="date" value="<?= e($serviceAtParts['date']) ?>">
                                <input id="service_at_time" name="service_at_time" type="time" value="<?= e($serviceAtParts['time']) ?>" step="60">
                            </div>
                        </div>

                        <div class="field datetime-split-field">
                            <label>วันรับรถ</label>
                            <div class="datetime-split-grid">
                                <input id="return_at_date" name="return_at_date" type="date" value="<?= e($returnAtParts['date']) ?>">
                                <input id="return_at_time" name="return_at_time" type="time" value="<?= e($returnAtParts['time']) ?>" step="60">
                            </div>
                        </div>
                    </div>

                    <div class="actions" style="margin-top: 14px;">
                        <button class="button" type="submit"><?= e($saveCustomerVehicleLabel) ?></button>
                    </div>
                </form>
            <?php else: ?>
                <div class="empty-state" style="margin-top: 18px;"><?= e($billDataLockedLabel) ?></div>
            <?php endif; ?>
        </section>

        <section class="table-card">
            <div class="section-head" style="padding: 18px 18px 0;">
                <div>
                    <h2 class="section-title"><?= e($selectedServicesLabel) ?></h2>
                    <p class="helper"><?= e(strtr($serviceItemCountLabel, array('{count}' => (string) count($details)))) ?></p>
                </div>
                <?php if ($canEditJob): ?>
                    <button
                        class="button button-secondary"
                        type="button"
                        data-edit-toggle
                        data-closed-label="แก้ไข"
                        data-open-label="ซ่อน"
                        aria-controls="selected-services-edit-form"
                        aria-expanded="false"
                    >แก้ไข</button>
                <?php endif; ?>
            </div>
            <table>
                <thead>
                <tr>
                    <th><?= e($serviceLabel) ?></th>
                    <th><?= e($priceLabel) ?></th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($details as $detail): ?>
                    <tr>
                        <td>
                            <div class="stack">
                                <strong><?= e((string) $detail['service_name_snapshot']) ?></strong>
                                <?php foreach (order_option_detail_lines((string) ($detail['service_options'] ?? '')) as $optionLine): ?>
                                    <span class="muted"><?= e($optionLine) ?></span>
                                <?php endforeach; ?>
                                <?php if (trim((string) ($detail['item_note'] ?? '')) !== ''): ?>
                                    <span class="muted"><?= e($serviceItemNoteLabel) ?>: <?= e(trim((string) $detail['item_note'])) ?></span>
                                <?php endif; ?>
                            </div>
                        </td>
                        <td><?= format_money($detail['price']) ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>

            <?php if ($canEditJob): ?>
                <form id="selected-services-edit-form" method="POST" action="../process/update_job_services.php" data-service-edit-form style="padding: 18px;" hidden>
                    <?= csrf_input('job_services_update') ?>
                    <input type="hidden" name="order_id" value="<?= (int) $job['order_id'] ?>">
                    <div class="service-options">
                        <?php if (empty($serviceSelectionCatalog)): ?>
                            <div class="empty-state"><?= e($serviceSelectionEmptyLabel) ?></div>
                        <?php else: ?>
                            <?php foreach ($serviceSelectionCatalog as $category): ?>
                                <div class="service-group-head">
                                    <h3><?= e((string) ($category['category_name'] ?? $categoryLabel)) ?></h3>
                                </div>

                                <?php foreach ((array) ($category['direct_services'] ?? array()) as $service): ?>
                                    <?php $renderSelectableService($service); ?>
                                <?php endforeach; ?>

                                <?php foreach ((array) ($category['main_services'] ?? array()) as $mainService): ?>
                                    <?php
                                    $mainServiceId = (int) ($mainService['service_id'] ?? 0);
                                    $mainServiceChecked = in_array($mainServiceId, $selectedServiceIds, true);
                                    $selectedGroupId = (int) ($selectedGroupChoices[$mainServiceId] ?? 0);
                                    $hasSelectedChild = false;

                                    foreach ((array) ($mainService['direct_sub_services'] ?? array()) as $directSubService) {
                                        if (in_array((int) ($directSubService['service_id'] ?? 0), $selectedServiceIds, true)) {
                                            $hasSelectedChild = true;
                                            break;
                                        }
                                    }

                                    if (!$hasSelectedChild) {
                                        foreach ((array) ($mainService['groups'] ?? array()) as $groupRow) {
                                            foreach ((array) ($groupRow['sub_services'] ?? array()) as $subService) {
                                                if (in_array((int) ($subService['service_id'] ?? 0), $selectedServiceIds, true)) {
                                                    $hasSelectedChild = true;
                                                    $selectedGroupId = $selectedGroupId > 0 ? $selectedGroupId : (int) ($groupRow['group_id'] ?? 0);
                                                    break 2;
                                                }
                                            }
                                        }
                                    }
                                    ?>
                                    <details class="service-flow-card" data-main-service-flow data-main-service-id="<?= $mainServiceId ?>" <?= ($mainServiceChecked || $selectedGroupId > 0 || $hasSelectedChild) ? 'open' : '' ?>>
                                        <summary>
                                            <label class="service-option compact-option">
                                                <input
                                                    type="checkbox"
                                                    name="service_ids[]"
                                                    value="<?= $mainServiceId ?>"
                                                    data-service-option
                                                    data-price="<?= e((string) ($mainService['price'] ?? 0)) ?>"
                                                    <?= service_row_is_film($mainService) ? 'data-film-service="1"' : '' ?>
                                                    <?= $mainServiceChecked ? 'checked' : '' ?>
                                                >
                                                <span>
                                                    <strong><?= e((string) ($mainService['service_name'] ?? ui_text('บริการหลัก', 'Main Service'))) ?></strong>
                                                    <?php if ($description = trim((string) ($mainService['description'] ?? ''))): ?>
                                                        <span class="muted"><?= e($description) ?></span>
                                                    <?php endif; ?>
                                                    <span class="service-meta">
                                                        <span><?= e(ui_text('บริการหลัก', 'Main Service')) ?></span>
                                                        <span><?= format_money($mainService['price'] ?? 0) ?> THB</span>
                                                    </span>
                                                    <?php $mainServiceNote = trim((string) ($selectedServiceNotes[$mainServiceId] ?? '')); ?>
                                                    <span class="service-item-note">
                                                        <span class="muted"><?= e($serviceItemNoteLabel) ?></span>
                                                        <input
                                                            type="text"
                                                            name="service_notes[<?= $mainServiceId ?>]"
                                                            value="<?= e($mainServiceNote) ?>"
                                                            placeholder="<?= e($serviceItemNotePlaceholder) ?>"
                                                            data-service-note
                                                            <?= $mainServiceChecked ? '' : 'disabled' ?>
                                                        >
                                                    </span>
                                                </span>
                                            </label>
                                        </summary>

                                        <div class="service-flow-body">
                                            <?php if (!empty($mainService['groups'])): ?>
                                                <div class="service-flow-step">
                                                    <p class="helper"><?= e($serviceGroupStepLabel) ?></p>
                                                    <div class="service-flow-chip-list">
                                                        <?php foreach ($mainService['groups'] as $groupRow): ?>
                                                            <?php $groupId = (int) ($groupRow['group_id'] ?? 0); ?>
                                                            <label class="service-chip">
                                                                <input
                                                                    type="radio"
                                                                    name="service_group_choice[<?= $mainServiceId ?>]"
                                                                    value="<?= $groupId ?>"
                                                                    data-main-service-group
                                                                    data-main-service-id="<?= $mainServiceId ?>"
                                                                    data-show-window-film-details="<?= (int) ($groupRow['show_window_film_details'] ?? 0) ?>"
                                                                    <?= $selectedGroupId === $groupId ? 'checked' : '' ?>
                                                                >
                                                                <span><?= e((string) ($groupRow['group_name'] ?? $serviceGroupLabel)) ?></span>
                                                            </label>
                                                        <?php endforeach; ?>
                                                    </div>
                                                </div>
                                            <?php endif; ?>

                                            <?php if (!empty($mainService['direct_sub_services'])): ?>
                                                <div class="service-flow-step">
                                                    <p class="helper"><?= e($subServiceStepLabel) ?></p>
                                                    <div class="service-options compact-service-options">
                                                        <?php foreach ($mainService['direct_sub_services'] as $directSubService): ?>
                                                            <?php $renderSelectableService($directSubService); ?>
                                                        <?php endforeach; ?>
                                                    </div>
                                                </div>
                                            <?php endif; ?>

                                            <?php foreach ((array) ($mainService['groups'] ?? array()) as $groupRow): ?>
                                                <?php $groupId = (int) ($groupRow['group_id'] ?? 0); ?>
                                                <div
                                                    class="service-flow-step"
                                                    data-group-sub-services
                                                    data-main-service-id="<?= $mainServiceId ?>"
                                                    data-group-id="<?= $groupId ?>"
                                                    <?= $selectedGroupId === $groupId ? '' : 'hidden' ?>
                                                >
                                                    <p class="helper"><?= e((int) ($groupRow['show_window_film_details'] ?? 0) === 1 ? $windowFilmDetailsLabel : $subServiceStepLabel) ?></p>
                                                    <?php if ((int) ($groupRow['show_window_film_details'] ?? 0) === 1): ?>
                                                        <div
                                                            class="film-options-panel"
                                                            data-film-options-panel
                                                            data-group-id="<?= $groupId ?>"
                                                            <?= ($selectedGroupId === $groupId && $mainServiceChecked) ? '' : 'hidden' ?>
                                                        >
                                                            <p class="helper"><?= e($windowFilmHelperLabel) ?></p>

                                                            <div class="film-layout">
                                                                <div class="film-car-preview" aria-hidden="true">
                                                                    <span class="film-car-body"></span>
                                                                    <span class="film-glass film-glass-front"></span>
                                                                    <span class="film-glass film-glass-sunroof"></span>
                                                                    <span class="film-glass film-glass-front-left"></span>
                                                                    <span class="film-glass film-glass-front-right"></span>
                                                                    <span class="film-glass film-glass-rear-left"></span>
                                                                    <span class="film-glass film-glass-rear-right"></span>
                                                                    <span class="film-glass film-glass-rear"></span>
                                                                    <span class="film-zone film-zone-front"><?= e($frontGlassLabel) ?></span>
                                                                    <span class="film-zone film-zone-sunroof"><?= e($sunroofLabel) ?></span>
                                                                    <span class="film-zone film-zone-side-front"><?= e($frontSideShortLabel) ?></span>
                                                                    <span class="film-zone film-zone-side-rear"><?= e($rearSideShortLabel) ?></span>
                                                                    <span class="film-zone film-zone-rear"><?= e($rearGlassLabel) ?></span>
                                                                </div>

                                                                <?php
                                                                $filmSearchOptions = array();
                                                                foreach ((array) ($groupRow['sub_services'] ?? array()) as $subService) {
                                                                    $subServiceId = (int) ($subService['service_id'] ?? 0);
                                                                    $subServiceName = trim((string) ($subService['service_name'] ?? ''));

                                                                    if ($subServiceId <= 0 || $subServiceName === '') {
                                                                        continue;
                                                                    }

                                                                    $filmSearchOptions[$subServiceId] = $subServiceName . ' - ' . format_money($subService['price'] ?? 0) . ' THB';
                                                                }

                                                                $filmSearchListId = 'film_service_options_' . $groupId;
                                                                $filmSearchEnabled = $selectedGroupId === $groupId && $mainServiceChecked;
                                                                ?>
                                                                <datalist id="<?= e($filmSearchListId) ?>">
                                                                    <?php foreach ($filmSearchOptions as $subServiceId => $filmSearchOptionLabel): ?>
                                                                        <option value="<?= e($filmSearchOptionLabel) ?>" data-service-id="<?= (int) $subServiceId ?>"></option>
                                                                    <?php endforeach; ?>
                                                                </datalist>

                                                                <div class="form-grid film-service-search-grid">
                                                                    <?php $renderWindowFilmServiceSearch($groupId, 'front', 'film_front_service_id', $frontGlassLabel, $filmFrontServiceId, $filmSearchOptions, $filmSearchListId, $filmSearchEnabled, $filmSearchPlaceholderLabel, $filmSearchInvalidLabel); ?>
                                                                    <?php $renderWindowFilmServiceSearch($groupId, 'sunroof', 'film_sunroof_service_id', $sunroofLabel, $filmSunroofServiceId, $filmSearchOptions, $filmSearchListId, $filmSearchEnabled, $filmSearchPlaceholderLabel, $filmSearchInvalidLabel); ?>
                                                                    <?php $renderWindowFilmServiceSearch($groupId, 'front_side', 'film_front_side_service_id', $frontSideGlassLabel, $filmFrontSideServiceId, $filmSearchOptions, $filmSearchListId, $filmSearchEnabled, $filmSearchPlaceholderLabel, $filmSearchInvalidLabel); ?>
                                                                    <?php $renderWindowFilmServiceSearch($groupId, 'rear_side', 'film_rear_side_service_id', $rearSideGlassLabel, $filmRearSideServiceId, $filmSearchOptions, $filmSearchListId, $filmSearchEnabled, $filmSearchPlaceholderLabel, $filmSearchInvalidLabel); ?>
                                                                    <?php $renderWindowFilmServiceSearch($groupId, 'rear', 'film_rear_service_id', $rearGlassLabel, $filmRearServiceId, $filmSearchOptions, $filmSearchListId, $filmSearchEnabled, $filmSearchPlaceholderLabel, $filmSearchInvalidLabel); ?>
                                                                </div>
                                                            </div>

                                                            <div class="field">
                                                                <label for="film_notes_<?= $groupId ?>"><?= e($filmNotesLabel) ?></label>
                                                                <input id="film_notes_<?= $groupId ?>" name="film_notes" type="text" value="<?= e($filmNotes) ?>" data-film-input <?= ($selectedGroupId === $groupId && $mainServiceChecked) ? '' : 'disabled' ?>>
                                                            </div>
                                                        </div>
                                                    <?php elseif (empty($groupRow['sub_services'])): ?>
                                                        <div class="empty-state"><?= e(ui_text('ยังไม่มีบริการย่อยในกลุ่มนี้', 'No sub services linked to this group yet.')) ?></div>
                                                    <?php else: ?>
                                                        <div class="service-options compact-service-options">
                                                            <?php foreach ($groupRow['sub_services'] as $subService): ?>
                                                                <?php $renderSelectableService($subService); ?>
                                                            <?php endforeach; ?>
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </details>
                                <?php endforeach; ?>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>

                    <?php if (!empty($packageServiceOptions)): ?>
                        <div class="section-head" style="margin-top: 18px;">
                            <div>
                                <h3 class="section-title"><?= e(ui_text('ข้อเสนอแพ็กเกจ', 'Package offers')) ?></h3>
                                <p class="helper"><?= e(ui_text('เมื่อขายแพ็กเกจ ระบบจะเพิ่มสิทธิ์ใช้งานกลับเข้าให้ลูกค้าคนนี้', 'Selling a package adds reusable balances to this customer.')) ?></p>
                            </div>
                        </div>
                        <div class="service-options">
                            <?php foreach ($packageServiceOptions as $service): ?>
                                <?php
                                $serviceId = (int) $service['service_id'];
                                $checked = in_array($serviceId, $selectedServiceIds, true) ? 'checked' : '';
                                $packageItems = service_package_purchase_snapshot($conn, $serviceId);
                                ?>
                                <label class="service-option">
                                    <input
                                        type="checkbox"
                                        name="service_ids[]"
                                        value="<?= $serviceId ?>"
                                        data-service-option
                                        data-price="<?= e((string) $service['price']) ?>"
                                        <?= $checked ?>
                                    >
                                    <span>
                                        <strong><?= e((string) $service['service_name']) ?></strong>
                                        <span class="muted"><?= e((string) ($service['description'] ?? '')) ?></span>
                                        <span class="service-meta">
                                            <span><?= e(ui_text('แพ็กเกจ', 'Package')) ?></span>
                                            <span><?= format_money($service['price']) ?> THB</span>
                                        </span>
                                        <?php foreach ($packageItems as $packageItem): ?>
                                            <span class="muted"><?= e((string) $packageItem['service_name']) ?> x<?= (int) ($packageItem['included_uses'] ?? 0) ?></span>
                                        <?php endforeach; ?>
                                        <?php $packageServiceNote = trim((string) ($selectedServiceNotes[$serviceId] ?? '')); ?>
                                        <span class="service-item-note">
                                            <span class="muted"><?= e($serviceItemNoteLabel) ?></span>
                                            <input
                                                type="text"
                                                name="service_notes[<?= $serviceId ?>]"
                                                value="<?= e($packageServiceNote) ?>"
                                                placeholder="<?= e($serviceItemNotePlaceholder) ?>"
                                                data-service-note
                                                <?= $checked ? '' : 'disabled' ?>
                                            >
                                        </span>
                                    </span>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>

                    <?php if (false && $hasFilmServices && !empty($windowFilmGroups)): ?>
                        <div class="film-options-panel" data-film-options-panel data-film-group-id="<?= (int) $selectedWindowFilmGroupId ?>" <?= $selectedWindowFilmGroup ? '' : 'hidden' ?>>
                            <div class="form-grid">
                                <div class="field">
                                    <label for="film_front_percent">Front glass</label>
                                    <select id="film_front_percent" name="film_front_service_id" data-film-input data-film-service-select <?= $selectedWindowFilmGroup ? '' : 'disabled' ?>>
                                        <option value="">Select</option>
                                        <?php foreach ($windowFilmGroups as $groupRow): ?>
                                            <?php foreach ((array) ($groupRow['sub_services'] ?? array()) as $subService): ?>
                                                <?php $subServiceId = (int) ($subService['service_id'] ?? 0); ?>
                                                <option value="<?= $subServiceId ?>" data-group-id="<?= (int) ($groupRow['group_id'] ?? 0) ?>" <?= $filmFrontServiceId === $subServiceId ? 'selected' : '' ?>>
                                                    <?= e((string) ($subService['service_name'] ?? '')) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div class="field">
                                    <label for="film_front_side_percent">Front side glass</label>
                                    <select id="film_front_side_percent" name="film_front_side_service_id" data-film-input data-film-service-select <?= $selectedWindowFilmGroup ? '' : 'disabled' ?>>
                                        <option value="">Select</option>
                                        <?php foreach ($windowFilmGroups as $groupRow): ?>
                                            <?php foreach ((array) ($groupRow['sub_services'] ?? array()) as $subService): ?>
                                                <?php $subServiceId = (int) ($subService['service_id'] ?? 0); ?>
                                                <option value="<?= $subServiceId ?>" data-group-id="<?= (int) ($groupRow['group_id'] ?? 0) ?>" <?= $filmFrontSideServiceId === $subServiceId ? 'selected' : '' ?>>
                                                    <?= e((string) ($subService['service_name'] ?? '')) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div class="field">
                                    <label for="film_rear_side_percent">Rear side glass</label>
                                    <select id="film_rear_side_percent" name="film_rear_side_service_id" data-film-input data-film-service-select <?= $selectedWindowFilmGroup ? '' : 'disabled' ?>>
                                        <option value="">Select</option>
                                        <?php foreach ($windowFilmGroups as $groupRow): ?>
                                            <?php foreach ((array) ($groupRow['sub_services'] ?? array()) as $subService): ?>
                                                <?php $subServiceId = (int) ($subService['service_id'] ?? 0); ?>
                                                <option value="<?= $subServiceId ?>" data-group-id="<?= (int) ($groupRow['group_id'] ?? 0) ?>" <?= $filmRearSideServiceId === $subServiceId ? 'selected' : '' ?>>
                                                    <?= e((string) ($subService['service_name'] ?? '')) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div class="field">
                                    <label for="film_rear_percent">Rear glass</label>
                                    <select id="film_rear_percent" name="film_rear_service_id" data-film-input data-film-service-select <?= $selectedWindowFilmGroup ? '' : 'disabled' ?>>
                                        <option value="">Select</option>
                                        <?php foreach ($windowFilmGroups as $groupRow): ?>
                                            <?php foreach ((array) ($groupRow['sub_services'] ?? array()) as $subService): ?>
                                                <?php $subServiceId = (int) ($subService['service_id'] ?? 0); ?>
                                                <option value="<?= $subServiceId ?>" data-group-id="<?= (int) ($groupRow['group_id'] ?? 0) ?>" <?= $filmRearServiceId === $subServiceId ? 'selected' : '' ?>>
                                                    <?= e((string) ($subService['service_name'] ?? '')) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>

                            <div class="field">
                                <label for="film_notes">Film notes</label>
                                <input id="film_notes" name="film_notes" type="text" value="<?= e($filmNotes) ?>" data-film-input <?= $selectedWindowFilmGroup ? '' : 'disabled' ?>>
                            </div>
                        </div>
                    <?php endif; ?>

                    <div class="service-meta" style="margin-top: 14px;">
                        <span><?= e(ui_text('เลือกแล้ว', 'Selected')) ?>: <strong data-selected-count>0</strong></span>
                        <span><?= e(ui_text('ใช้สิทธิ์แพ็กเกจไป', 'Covered by package')) ?>: <strong data-selected-package-discount>0.00</strong> THB</span>
                        <span><?= e(ui_text('ยอดค่าบริการ', 'Service total')) ?>: <strong data-selected-total>0.00</strong> THB</span>
                    </div>

                    <div class="form-grid" style="margin-top: 14px;">
                        <div class="field">
                            <label for="total_price"><?= e(ui_text('ราคารวม', 'Total price')) ?></label>
                            <input id="total_price" name="total_price" type="number" step="0.01" min="0" value="<?= e((string) $job['total_price']) ?>" data-total-price-input>
                        </div>
                    </div>

                    <div class="actions" style="margin-top: 14px;">
                        <button class="button" type="submit"><?= e(ui_text('บันทึกบริการ', 'Save services')) ?></button>
                    </div>
                </form>
            <?php else: ?>
                <div class="empty-state" style="margin: 18px;"><?= e($selectedServicesLockedLabel) ?></div>
            <?php endif; ?>
        </section>

        <?php if (trim((string) ($job['notes'] ?? '')) !== ''): ?>
            <section class="card">
                <h2 class="section-title"><?= e($notesLabel) ?></h2>
                <p><?= nl2br(e((string) $job['notes'])) ?></p>
            </section>
        <?php endif; ?>
    </div>

    <aside class="grid summary-panel">
        <?php if (!empty($availablePackageBalanceMap)): ?>
            <section class="card">
                <h2 class="section-title"><?= e($availablePackagesLabel) ?></h2>
                <div class="member-summary-list">
                    <?php foreach ($availablePackageBalanceMap as $packageBalanceRows): ?>
                        <?php foreach ($packageBalanceRows as $packageBalance): ?>
                            <div>
                                <span>
                                    <?= e((string) $packageBalance['service_name_snapshot']) ?><br>
                                    <small class="muted"><?= e((string) $packageBalance['package_name_snapshot']) ?> / <?= e(package_vehicle_scope_note($packageBalance)) ?></small>
                                </span>
                                <strong><?= e(strtr(ui_text('คงเหลือ {count} ครั้ง', '{count} left'), array('{count}' => (string) ((int) ($packageBalance['remaining_uses'] ?? 0))))) ?></strong>
                            </div>
                        <?php endforeach; ?>
                    <?php endforeach; ?>
                </div>
            </section>
        <?php endif; ?>

        <?php if (!$isFullyPaid && !$isJobCancelled): ?>
            <section class="card booking-summary-card" id="payment-section">
                <h2 class="section-title"><?= e($paymentSummaryLabel) ?></h2>
                <?php if ($canAddPayment): ?>
                    <form
                        method="POST"
                        action="../process/save_payment.php"
                        enctype="multipart/form-data"
                        data-booking-form
                        data-quick-service-form="1"
                        data-paid-before="<?= e(number_format((float) ($job['paid_amount'] ?? 0), 2, '.', '')) ?>"
                        data-qr-available="<?= $qrAvailable ? '1' : '0' ?>"
                        data-qr-endpoint="../process/quick_service_qr.php"
                        data-qr-scope="queue_payment"
                        data-qr-branch="<?= e((string) ($job['branch_name'] ?? '')) ?>"
                    >
                        <?= csrf_input('queue_payment_save') ?>
                        <?= submission_input('queue_payment_save_' . (int) $job['order_id']) ?>
                        <input type="hidden" name="order_id" value="<?= (int) $job['order_id'] ?>">

                        <div class="field summary-price-field">
                            <label for="total_price"><?= e($billTotalLabel) ?></label>
                            <input
                                id="total_price"
                                type="number"
                                step="0.01"
                                min="0"
                                value="<?= e(number_format((float) ($job['total_price'] ?? 0), 2, '.', '')) ?>"
                                data-total-price-input
                                data-manual="1"
                                readonly
                            >
                        </div>

                        <div class="quick-service-summary-grid">
                            <div>
                                <span><?= e(ui_text('ชำระแล้ว', 'Paid already')) ?></span>
                                <strong data-paid-before><?= format_money($job['paid_amount'] ?? 0) ?></strong>
                            </div>
                            <div data-balance-due-card>
                                <span><?= e(ui_text('ยอดค้างชำระ', 'Balance due')) ?></span>
                                <strong data-balance-due><?= format_money($balance) ?></strong>
                            </div>
                            <div>
                                <span><?= e(ui_text('รับรู้ครั้งนี้', 'Recognized now')) ?></span>
                                <strong data-recognized-payment>0.00</strong>
                            </div>
                            <div data-change-field hidden>
                                <span><?= e(ui_text('เงินทอน', 'Cash change')) ?></span>
                                <strong data-change-due>0.00</strong>
                            </div>
                        </div>

                        <div class="field">
                            <label for="payment_method"><?= e($paymentMethodLabel) ?></label>
                            <select id="payment_method" name="payment_method" required>
                                <?php foreach ($paymentMethods as $paymentMethodValue => $paymentMethodLabel): ?>
                                    <option value="<?= e($paymentMethodValue) ?>" <?= $selectedPaymentMethod === $paymentMethodValue ? 'selected' : '' ?>>
                                        <?= e($paymentMethodLabel) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <?php if (!$qrAvailable): ?>
                                <p class="helper"><?= e(ui_text('ตั้งค่า QR สำหรับสาขานี้ หรือใช้โปรไฟล์เริ่มต้นทุกสาขาเพื่อแสดงตัวอย่าง QR', 'Set QR configuration for this branch or use the all-branch default profile to display a QR preview.')) ?></p>
                            <?php endif; ?>
                        </div>

                        <div class="field">
                            <label for="received_amount"><?= e($receivedNowLabel) ?></label>
                            <input
                                id="received_amount"
                                name="received_amount"
                                type="number"
                                step="0.01"
                                min="0"
                                value="<?= e($receivedAmountValue) ?>"
                                data-received-amount-input
                            >
                            <p class="helper" data-payment-validation-message><?= e($paymentValidationLabel) ?></p>
                        </div>

                        <div class="field payment-slip-field" data-payment-slip-field hidden>
                            <label for="slip_file"><?= ui_text('แนบสลิป / หลักฐานการชำระ', 'Payment slip / proof') ?></label>
                            <input
                                id="slip_file"
                                name="slip_file"
                                type="file"
                                accept="<?= e(payment_slip_accept_attribute()) ?>"
                                data-payment-slip-input
                            >
                            <p class="helper"><?= ui_text('ใช้ได้กับการโอน, QR และบัตรเครดิต', 'Available for Transfer, QR and Card payments.') ?></p>
                        </div>

                        <section class="card quick-service-qr-panel" data-quick-qr-panel hidden>
                            <h3 class="section-title"><?= e($qrPaymentLabel) ?></h3>
                            <p class="helper" data-quick-qr-hint><?= e($qrPaymentHintLabel) ?></p>
                            <div class="quick-service-qr-preview">
                                <img src="" alt="<?= e($queuePaymentQrLabel) ?>" data-quick-qr-image>
                            </div>
                            <div class="actions quick-service-qr-actions">
                                <a
                                    class="button button-secondary app-action-button"
                                    href="#"
                                    target="_blank"
                                    rel="noopener"
                                    hidden
                                    data-quick-qr-download
                                ><?= app_button_content('download', ui_text('บันทึก QR', 'Save QR')) ?></a>
                            </div>
                        </section>

                        <div class="field">
                            <label for="note"><?= e($receiptNoteLabel) ?></label>
                            <textarea id="note" name="note"><?= e($paymentNoteValue) ?></textarea>
                        </div>

                        <div class="actions quick-service-actions is-single">
                            <button class="button button-accent button-full" type="submit" name="submit_action" value="pay" data-pay-submit><?= e($paymentActionLabel) ?></button>
                        </div>
                    </form>
                <?php elseif (!$isJobDone): ?>
                    <div class="empty-state"><?= e($paymentAfterDoneLabel) ?></div>
                <?php else: ?>
                    <div class="empty-state"><?= e($noPaymentPermissionLabel) ?></div>
                <?php endif; ?>
            </section>
        <?php endif; ?>

        <?php if ($showDepositManagement): ?>
            <section class="card booking-summary-card" id="deposit-management">
                <h2 class="section-title"><?= e($bookingDepositsLabel) ?></h2>
                <p class="helper"><?= e($bookingDepositsHelperLabel) ?></p>

                <?php if ($canEditAdminDeposit): ?>
                    <?php
                    $adminDepositCurrentAmount = number_format((float) ($job['admin_deposit_amount'] ?? 0), 2, '.', '');
                    $adminDepositCurrentMethod = trim((string) (($adminDepositPayment['payment_method'] ?? '') ?: ($job['admin_deposit_method'] ?? 'cash')));
                    if (!array_key_exists($adminDepositCurrentMethod, $paymentMethods)) {
                        $adminDepositCurrentMethod = 'cash';
                    }
                    $adminDepositFormAmount = $depositEditScopeValue === 'admin' && $depositEditAmountValue !== ''
                        ? $depositEditAmountValue
                        : $adminDepositCurrentAmount;
                    $adminDepositFormMethod = $depositEditScopeValue === 'admin' && $depositEditMethodValue !== ''
                        ? $depositEditMethodValue
                        : $adminDepositCurrentMethod;
                    if (!array_key_exists($adminDepositFormMethod, $paymentMethods)) {
                        $adminDepositFormMethod = 'cash';
                    }
                    $adminDepositPaymentId = (int) ($adminDepositPayment['payment_id'] ?? 0);
                    $adminDepositSlipViewUrl = $adminDepositPaymentId > 0 ? payment_slip_access_url($adminDepositPaymentId) : '';
                    $adminDepositSlipDownloadUrl = $adminDepositPaymentId > 0 ? payment_slip_access_url($adminDepositPaymentId, true) : '';
                    $adminDepositSlipPath = trim((string) ($adminDepositPayment['slip_file_path'] ?? ''));
                    $adminDepositSlipPath = $adminDepositSlipPath !== '' ? $adminDepositSlipViewUrl : '';
                    $adminDepositSlipName = trim((string) ($adminDepositPayment['slip_file_name'] ?? ''));
                    $adminDepositSlipVisible = payment_method_supports_slip($adminDepositFormMethod) && (float) $adminDepositFormAmount > 0;
                    $adminDepositQrVisible = $adminDepositFormMethod === 'qr' && (float) $adminDepositFormAmount > 0;
                    $hasAdminDepositRecord = $adminDepositPayment !== null || (float) ($job['admin_deposit_amount'] ?? 0) > 0;
                    ?>
                    <form
                        id="deposit-admin-form"
                        class="quick-service-payment-edit-form deposit-manage-form"
                        method="post"
                        action="../process/update_booking_deposit.php"
                        enctype="multipart/form-data"
                        data-deposit-manage-form
                        data-qr-endpoint="../process/quick_service_qr.php"
                        data-qr-scope="booking_deposit_admin"
                        data-qr-branch="<?= e((string) ($job['branch_name'] ?? '')) ?>"
                    >
                        <?= csrf_input('booking_deposit_manage') ?>
                        <input type="hidden" name="order_id" value="<?= (int) $job['order_id'] ?>">
                        <input type="hidden" name="payment_id" value="<?= (int) ($adminDepositPayment['payment_id'] ?? 0) ?>">
                        <input type="hidden" name="deposit_scope" value="admin">
                        <input type="hidden" name="return_to" value="<?= e($adminDepositPanelPath) ?>">

                        <div class="stack">
                            <h3 class="section-title"><?= e(ui_text('มัดจำ @Admin', 'Deposit @Admin')) ?></h3>
                            <div class="form-grid">
                                <div class="field">
                                    <label for="admin_deposit_amount_edit"><?= e($depositAmountLabel) ?></label>
                                    <input
                                        id="admin_deposit_amount_edit"
                                        name="deposit_edit_amount"
                                        type="number"
                                        step="0.01"
                                        min="0.01"
                                        value="<?= e($adminDepositFormAmount) ?>"
                                        required
                                        data-deposit-amount-input
                                    >
                                </div>

                                <div class="field">
                                    <label for="admin_deposit_method_edit"><?= e($paymentMethodLabel) ?></label>
                                    <select
                                        id="admin_deposit_method_edit"
                                        name="deposit_edit_method"
                                        required
                                        data-deposit-method-select
                                    >
                                        <?php foreach ($paymentMethods as $paymentMethodValue => $paymentMethodLabel): ?>
                                            <option value="<?= e($paymentMethodValue) ?>" <?= $adminDepositFormMethod === $paymentMethodValue ? 'selected' : '' ?>>
                                                <?= e($paymentMethodLabel) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>

                            <div class="field payment-slip-field" data-deposit-slip-group <?= $adminDepositSlipVisible ? '' : 'hidden' ?>>
                                <label for="admin_deposit_slip_file_edit"><?= ui_text('แนบสลิป / หลักฐานการชำระ', 'Payment slip / proof') ?></label>
                                <input
                                    id="admin_deposit_slip_file_edit"
                                    name="deposit_slip_file"
                                    type="file"
                                    accept="<?= e(payment_slip_accept_attribute()) ?>"
                                    data-deposit-slip-input
                                >
                                <p class="helper"><?= ui_text('ใช้ได้กับการโอน, QR และบัตรเครดิต', 'Available for Transfer, QR and Card payments.') ?></p>
                                <?php if ($adminDepositSlipPath !== ''): ?>
                                    <div class="quick-service-payment-links">
                                        <a class="button button-secondary" href="<?= e($adminDepositSlipPath) ?>" target="_blank" rel="noopener"><?= ui_text('ดูสลิป', 'View slip') ?></a>
                                        <a class="button button-ghost" href="<?= e($adminDepositSlipPath) ?>" download="<?= e($adminDepositSlipName !== '' ? $adminDepositSlipName : 'payment-slip') ?>"><?= ui_text('ดาวน์โหลด', 'Download') ?></a>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <section class="card quick-service-qr-panel" data-deposit-qr-panel <?= $adminDepositQrVisible ? '' : 'hidden' ?>>
                                <h3 class="section-title"><?= e($qrPaymentLabel) ?></h3>
                                <p class="helper" data-deposit-qr-hint><?= e($qrPaymentHintLabel) ?></p>
                                <div class="quick-service-qr-preview">
                                    <img src="" alt="<?= e($bookingAdminDepositQrLabel) ?>" data-deposit-qr-image>
                                </div>
                                <div class="actions quick-service-qr-actions">
                                    <a class="button button-secondary app-action-button" href="#" target="_blank" rel="noopener" hidden data-deposit-qr-download><?= app_button_content('download', ui_text('บันทึก QR', 'Save QR')) ?></a>
                                </div>
                            </section>

                            <div class="actions-inline quick-service-payment-edit-actions">
                                <button class="button button-accent" type="submit"><?= e($hasAdminDepositRecord ? $saveDepositAdminLabel : $addDepositAdminLabel) ?></button>
                                <?php if ($hasAdminDepositRecord): ?>
                                    <button
                                        class="button button-danger"
                                        type="submit"
                                        formaction="../process/delete_booking_deposit.php"
                                        formnovalidate
                                        onclick="return confirm('<?= e($deleteDepositAdminConfirmLabel) ?>');"
                                    ><?= e($deleteDepositAdminLabel) ?></button>
                                <?php endif; ?>
                            </div>
                        </div>
                    </form>
                <?php endif; ?>

                <?php if ($canEditBranchDeposit): ?>
                    <?php
                    $branchDepositCurrentAmount = number_format((float) ($job['branch_deposit_amount'] ?? 0), 2, '.', '');
                    $branchDepositCurrentMethod = trim((string) (($branchDepositPayment['payment_method'] ?? '') ?: ($job['branch_deposit_method'] ?? 'cash')));
                    if (!array_key_exists($branchDepositCurrentMethod, $paymentMethods)) {
                        $branchDepositCurrentMethod = 'cash';
                    }
                    $branchDepositFormAmount = $depositEditScopeValue === 'branch' && $depositEditAmountValue !== ''
                        ? $depositEditAmountValue
                        : $branchDepositCurrentAmount;
                    $branchDepositFormMethod = $depositEditScopeValue === 'branch' && $depositEditMethodValue !== ''
                        ? $depositEditMethodValue
                        : $branchDepositCurrentMethod;
                    if (!array_key_exists($branchDepositFormMethod, $paymentMethods)) {
                        $branchDepositFormMethod = 'cash';
                    }
                    $branchDepositPaymentId = (int) ($branchDepositPayment['payment_id'] ?? 0);
                    $branchDepositSlipViewUrl = $branchDepositPaymentId > 0 ? payment_slip_access_url($branchDepositPaymentId) : '';
                    $branchDepositSlipDownloadUrl = $branchDepositPaymentId > 0 ? payment_slip_access_url($branchDepositPaymentId, true) : '';
                    $branchDepositSlipPath = trim((string) ($branchDepositPayment['slip_file_path'] ?? ''));
                    $branchDepositSlipPath = $branchDepositSlipPath !== '' ? $branchDepositSlipViewUrl : '';
                    $branchDepositSlipName = trim((string) ($branchDepositPayment['slip_file_name'] ?? ''));
                    $branchDepositSlipVisible = payment_method_supports_slip($branchDepositFormMethod) && (float) $branchDepositFormAmount > 0;
                    $branchDepositQrVisible = $branchDepositFormMethod === 'qr' && (float) $branchDepositFormAmount > 0;
                    $hasBranchDepositRecord = $branchDepositPayment !== null || (float) ($job['branch_deposit_amount'] ?? 0) > 0;
                    ?>
                    <form
                        id="deposit-branch-form"
                        class="quick-service-payment-edit-form deposit-manage-form"
                        method="post"
                        action="../process/update_booking_deposit.php"
                        enctype="multipart/form-data"
                        data-deposit-manage-form
                        data-qr-endpoint="../process/quick_service_qr.php"
                        data-qr-scope="booking_deposit_branch"
                        data-qr-branch="<?= e((string) ($job['branch_name'] ?? '')) ?>"
                    >
                        <?= csrf_input('booking_deposit_manage') ?>
                        <input type="hidden" name="order_id" value="<?= (int) $job['order_id'] ?>">
                        <input type="hidden" name="payment_id" value="<?= (int) ($branchDepositPayment['payment_id'] ?? 0) ?>">
                        <input type="hidden" name="deposit_scope" value="branch">
                        <input type="hidden" name="return_to" value="<?= e($branchDepositPanelPath) ?>">

                        <div class="stack">
                            <h3 class="section-title"><?= e(ui_text('มัดจำ @Branch', 'Deposit @Branch')) ?></h3>
                            <div class="form-grid">
                                <div class="field">
                                    <label for="branch_deposit_amount_edit"><?= e($depositAmountLabel) ?></label>
                                    <input
                                        id="branch_deposit_amount_edit"
                                        name="deposit_edit_amount"
                                        type="number"
                                        step="0.01"
                                        min="0.01"
                                        value="<?= e($branchDepositFormAmount) ?>"
                                        required
                                        data-deposit-amount-input
                                    >
                                </div>

                                <div class="field">
                                    <label for="branch_deposit_method_edit"><?= e($paymentMethodLabel) ?></label>
                                    <select
                                        id="branch_deposit_method_edit"
                                        name="deposit_edit_method"
                                        required
                                        data-deposit-method-select
                                    >
                                        <?php foreach ($paymentMethods as $paymentMethodValue => $paymentMethodLabel): ?>
                                            <option value="<?= e($paymentMethodValue) ?>" <?= $branchDepositFormMethod === $paymentMethodValue ? 'selected' : '' ?>>
                                                <?= e($paymentMethodLabel) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>

                            <div class="field payment-slip-field" data-deposit-slip-group <?= $branchDepositSlipVisible ? '' : 'hidden' ?>>
                                <label for="branch_deposit_slip_file_edit"><?= ui_text('แนบสลิป / หลักฐานการชำระ', 'Payment slip / proof') ?></label>
                                <input
                                    id="branch_deposit_slip_file_edit"
                                    name="deposit_slip_file"
                                    type="file"
                                    accept="<?= e(payment_slip_accept_attribute()) ?>"
                                    data-deposit-slip-input
                                >
                                <p class="helper"><?= ui_text('ใช้ได้กับการโอน, QR และบัตรเครดิต', 'Available for Transfer, QR and Card payments.') ?></p>
                                <?php if ($branchDepositSlipPath !== ''): ?>
                                    <div class="quick-service-payment-links">
                                        <a class="button button-secondary" href="<?= e($branchDepositSlipPath) ?>" target="_blank" rel="noopener"><?= ui_text('ดูสลิป', 'View slip') ?></a>
                                        <a class="button button-ghost" href="<?= e($branchDepositSlipPath) ?>" download="<?= e($branchDepositSlipName !== '' ? $branchDepositSlipName : 'payment-slip') ?>"><?= ui_text('ดาวน์โหลด', 'Download') ?></a>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <section class="card quick-service-qr-panel" data-deposit-qr-panel <?= $branchDepositQrVisible ? '' : 'hidden' ?>>
                                <h3 class="section-title"><?= e($qrPaymentLabel) ?></h3>
                                <p class="helper" data-deposit-qr-hint><?= e($qrPaymentHintLabel) ?></p>
                                <div class="quick-service-qr-preview">
                                    <img src="" alt="<?= e($bookingBranchDepositQrLabel) ?>" data-deposit-qr-image>
                                </div>
                                <div class="actions quick-service-qr-actions">
                                    <a class="button button-secondary app-action-button" href="#" target="_blank" rel="noopener" hidden data-deposit-qr-download><?= app_button_content('download', ui_text('บันทึก QR', 'Save QR')) ?></a>
                                </div>
                            </section>

                            <div class="actions-inline quick-service-payment-edit-actions">
                                <button class="button button-accent" type="submit"><?= e($hasBranchDepositRecord ? $saveDepositBranchLabel : $addDepositBranchLabel) ?></button>
                                <?php if ($hasBranchDepositRecord): ?>
                                    <button
                                        class="button button-danger"
                                        type="submit"
                                        formaction="../process/delete_booking_deposit.php"
                                        formnovalidate
                                        onclick="return confirm('<?= e($deleteDepositBranchConfirmLabel) ?>');"
                                    ><?= e($deleteDepositBranchLabel) ?></button>
                                <?php endif; ?>
                            </div>
                        </div>
                    </form>
                <?php endif; ?>
            </section>
        <?php endif; ?>

        <section class="card quick-service-payment-history-card" id="payment-history">
            <div class="section-head">
                <div>
                    <h2 class="section-title"><?= e($paymentHistoryLabel) ?></h2>
                    <p class="helper"><?= e(strtr($paymentRecordCountLabel, array('{count}' => (string) count($payments)))) ?></p>
                </div>
                <?php if ($hasDepositPermissions && !$showDepositManagement): ?>
                    <?php if (!$hasAnyDepositRecord): ?>
                        <a class="button button-accent" href="<?= e($depositPanelPath) ?>"><?= e(ui_text('มัดจำ', 'Deposit')) ?></a>
                    <?php elseif (!$hasDepositPaymentRows): ?>
                        <a class="button button-secondary" href="<?= e($depositPanelPath) ?>"><?= e(ui_text('แก้ไขมัดจำ', 'Edit deposit')) ?></a>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
            <?php if (empty($payments)): ?>
                <div class="empty-state quick-service-payment-empty"><?= e(ui_text('ยังไม่มีประวัติการชำระเงิน', 'No payments recorded.')) ?></div>
            <?php else: ?>
                <div class="quick-service-payment-history">
                    <?php foreach ($payments as $payment): ?>
                        <?php
                        $paymentMethodLabel = quick_service_payment_method_label((string) ($payment['payment_method'] ?? 'cash'));
                        $paymentAmount = (float) ($payment['amount'] ?? 0);
                        $paymentReceived = (float) ($payment['received_amount'] ?? 0);
                        $paymentChange = (float) ($payment['change_amount'] ?? 0);
                        $paymentDate = format_datetime((string) ($payment['payment_date'] ?? ''));
                        $paymentNote = trim((string) ($payment['note'] ?? ''));
                        $paymentNoteDisplay = $paymentNote;
                        if ($paymentNote === 'Admin deposit at booking') {
                            $paymentNoteDisplay = ui_text('มัดจำ @Admin ตอนเปิดบิล', 'Admin deposit at booking');
                        } elseif ($paymentNote === 'Branch deposit at booking') {
                            $paymentNoteDisplay = ui_text('มัดจำ @Branch ตอนเปิดบิล', 'Branch deposit at booking');
                        }
                        $paymentId = (int) ($payment['payment_id'] ?? 0);
                        $paymentSlipViewUrl = $paymentId > 0 ? payment_slip_access_url($paymentId) : '';
                        $paymentSlipDownloadUrl = $paymentId > 0 ? payment_slip_access_url($paymentId, true) : '';
                        $paymentSlipPath = trim((string) ($payment['slip_file_path'] ?? ''));
                        $paymentSlipPath = $paymentSlipPath !== '' ? $paymentSlipViewUrl : '';
                        $paymentSlipName = trim((string) ($payment['slip_file_name'] ?? ''));
                        $isAdminDepositPayment = $paymentNote === 'Admin deposit at booking';
                        $isBranchDepositPayment = $paymentNote === 'Branch deposit at booking';
                        $canEditDeposit = ($isAdminDepositPayment && $canEditAdminDeposit) || ($isBranchDepositPayment && $canEditBranchDeposit);
                        $editDepositPath = $isAdminDepositPayment ? $adminDepositPanelPath : $branchDepositPanelPath;
                        $deleteDepositReturnPath = 'job_details.php?id=' . (int) $job['order_id'] . '#payment-history';
                        ?>
                        <article class="quick-service-payment-row">
                            <div class="quick-service-payment-main">
                                <div class="quick-service-payment-topline">
                                    <strong><?= e($paymentMethodLabel) ?></strong>
                                    <span><?= e($paymentDate) ?></span>
                                </div>
                                <div class="quick-service-payment-meta">
                                    <span><?= e($paidShortLabel) ?> <?= format_money($paymentAmount) ?> THB</span>
                                    <span><?= e($receivedNowLabel) ?> <?= format_money($paymentReceived > 0 ? $paymentReceived : $paymentAmount) ?> THB</span>
                                    <?php if ($paymentChange > 0): ?>
                                        <span><?= e(ui_text('เงินทอน', 'Change')) ?> <?= format_money($paymentChange) ?> THB</span>
                                    <?php endif; ?>
                                </div>
                                <?php if ($paymentNoteDisplay !== ''): ?>
                                    <p class="helper"><?= e($paymentNoteDisplay) ?></p>
                                <?php endif; ?>
                                <?php if ($canEditDeposit): ?>
                                    <div class="quick-service-payment-links quick-service-payment-actions">
                                        <a class="button button-secondary" href="<?= e($editDepositPath) ?>"><?= e(ui_text('แก้ไขมัดจำ', 'Edit deposit')) ?></a>
                                        <form
                                            method="POST"
                                            action="../process/delete_booking_deposit.php"
                                            class="quick-service-payment-delete"
                                            onsubmit="return confirm('<?= e(ui_text('ลบรายการมัดจำการจองนี้หรือไม่', 'Delete this recorded booking deposit?')) ?>');"
                                        >
                                            <?= csrf_input('booking_deposit_manage') ?>
                                            <input type="hidden" name="order_id" value="<?= (int) $job['order_id'] ?>">
                                            <input type="hidden" name="payment_id" value="<?= $paymentId ?>">
                                            <input type="hidden" name="return_to" value="<?= e($deleteDepositReturnPath) ?>">
                                            <button class="button button-danger" type="submit"><?= e(ui_text('ลบมัดจำ', 'Delete deposit')) ?></button>
                                        </form>
                                    </div>
                                <?php endif; ?>
                                <?php if ($paymentSlipPath !== ''): ?>
                                    <div class="quick-service-payment-links">
                                        <a class="button button-secondary" href="<?= e($paymentSlipPath) ?>" target="_blank" rel="noopener"><?= ui_text('ดูสลิป', 'View slip') ?></a>
                                        <a class="button button-ghost" href="<?= e($paymentSlipPath) ?>" download="<?= e($paymentSlipName !== '' ? $paymentSlipName : 'payment-slip') ?>"><?= ui_text('ดาวน์โหลด', 'Download') ?></a>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>
    </aside>
</div>

<?php render_page_end(); ?>
