<?php
declare(strict_types=1);

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

require_permission($conn, 'booking');

ensure_order_branch_column($conn);
ensure_order_return_column($conn);
ensure_order_slide_send_column($conn);
ensure_order_service_at_column($conn);
ensure_order_source_column($conn);
ensure_order_split_deposit_columns($conn);
ensure_car_profile_columns($conn);

$oldInput = pull_old_input();
$lookupMessage = '';
$lookupState = '';
$matchedCustomerId = 0;
$matchedCarId = 0;
$isNewCustomerMode = isset($_GET['new_customer']);
$openBillCustomerId = (int) (filter_input(INPUT_GET, 'open_bill_customer_id', FILTER_VALIDATE_INT) ?: 0);
$openBillCarId = (int) (filter_input(INPUT_GET, 'open_bill_car_id', FILTER_VALIDATE_INT) ?: 0);

if (isset($_GET['lookup_customer'])) {
    $lookupKeys = array(
        'customer_name',
        'lookup_phone',
        'phone',
        'plate_number',
        'province',
        'vehicle_type',
        'brand',
        'model',
        'color',
        'branch_name',
        'scheduled_at',
        'slide_send_at',
        'service_at',
        'return_at',
        'total_price',
        'admin_deposit_amount',
        'admin_deposit_method',
        'branch_deposit_amount',
        'branch_deposit_method',
        'film_front_percent',
        'film_sunroof_percent',
        'film_front_side_percent',
        'film_rear_side_percent',
        'film_side_percent',
        'film_rear_percent',
        'film_front_service_id',
        'film_sunroof_service_id',
        'film_front_side_service_id',
        'film_rear_side_service_id',
        'film_rear_service_id',
        'film_notes',
        'notes',
    );

    foreach ($lookupKeys as $lookupKey) {
        if (isset($_GET[$lookupKey]) && !is_array($_GET[$lookupKey])) {
            $oldInput[$lookupKey] = trim((string) $_GET[$lookupKey]);
        }
    }

    if (!isset($_GET['lookup_phone']) && isset($_GET['phone']) && !is_array($_GET['phone'])) {
        $oldInput['lookup_phone'] = trim((string) $_GET['phone']);
    }

    if (isset($_GET['service_ids']) && is_array($_GET['service_ids'])) {
        $oldInput['service_ids'] = array_values(array_unique(array_filter(array_map('intval', $_GET['service_ids']))));
    }

    if (isset($_GET['service_notes']) && is_array($_GET['service_notes'])) {
        $oldInput['service_notes'] = array_map('strval', $_GET['service_notes']);
    }

    if (isset($_GET['package_usage']) && is_array($_GET['package_usage'])) {
        $oldInput['package_usage'] = array_map('strval', $_GET['package_usage']);
    }

    if (isset($_GET['service_group_choice']) && is_array($_GET['service_group_choice'])) {
        $oldInput['service_group_choice'] = array_map('strval', $_GET['service_group_choice']);
    }

    $lookupQuery = old_value($oldInput, 'lookup_phone', old_value($oldInput, 'phone'));

    if (normalize_phone($lookupQuery) === '' && normalize_plate($lookupQuery) === '') {
        $lookupMessage = ui_text('กรอกเบอร์โทรลูกค้าหรือทะเบียนรถแบบตรงตัวเพื่อค้นหา', 'Enter the exact customer phone number or plate number to search.');
        $lookupState = 'warning';
    } else {
        try {
            $matches = find_customer_matches($conn, $lookupQuery, $lookupQuery);

            if (empty($matches)) {
                $lookupMessage = ui_text('ไม่พบลูกค้าที่ตรงกับข้อมูลที่ค้นหา', 'No matching customer found.');
                $lookupState = 'warning';
            } else {
                $match = $matches[0];
                $matchedCustomerId = (int) ($match['customerId'] ?? 0);
                $matchedCarId = (int) ($match['carId'] ?? 0);
                $oldInput['customer_name'] = (string) ($match['customerName'] ?: old_value($oldInput, 'customer_name'));
                $oldInput['phone'] = (string) ($match['phone'] ?: old_value($oldInput, 'phone'));
                $oldInput['lookup_phone'] = (string) ($match['phone'] ?: old_value($oldInput, 'lookup_phone'));
                $oldInput['plate_number'] = (string) ($match['plateNumber'] ?: old_value($oldInput, 'plate_number'));
                $oldInput['province'] = (string) ($match['province'] ?: old_value($oldInput, 'province', 'Bangkok'));
                $oldInput['vehicle_type'] = (string) ($match['vehicleType'] ?: old_value($oldInput, 'vehicle_type'));
                $oldInput['brand'] = (string) ($match['brand'] ?: old_value($oldInput, 'brand'));
                $oldInput['model'] = (string) ($match['model'] ?: old_value($oldInput, 'model'));
                $oldInput['color'] = (string) ($match['color'] ?: old_value($oldInput, 'color'));
                $lookupMessage = count($matches) > 1
                    ? ui_text('โหลดข้อมูลลูกค้ารายการล่าสุดที่ตรงกันแล้ว', 'Loaded the most recent matching customer.')
                    : ui_text('โหลดข้อมูลลูกค้าแล้ว', 'Customer data loaded.');
                $lookupState = 'success';
            }
        } catch (Throwable $exception) {
            $lookupMessage = ui_text('ค้นหาลูกค้าไม่สำเร็จ', 'Customer lookup failed.');
            $lookupState = 'error';
        }
    }
}

if (
    !$isNewCustomerMode
    && !isset($_GET['lookup_customer'])
    && $openBillCustomerId > 0
    && $openBillCarId > 0
) {
    $prefillRecord = find_customer_record_by_ids($conn, $openBillCustomerId, $openBillCarId);

    if ($prefillRecord) {
        $matchedCustomerId = (int) ($prefillRecord['customerId'] ?? 0);
        $matchedCarId = (int) ($prefillRecord['carId'] ?? 0);
        $oldInput['customer_name'] = (string) ($prefillRecord['customerName'] ?? '');
        $oldInput['phone'] = (string) ($prefillRecord['phone'] ?? '');
        $oldInput['lookup_phone'] = (string) (($prefillRecord['plateNumber'] ?? '') !== '' ? $prefillRecord['plateNumber'] : ($prefillRecord['phone'] ?? ''));
        $oldInput['plate_number'] = (string) ($prefillRecord['plateNumber'] ?? '');
        $oldInput['province'] = (string) ($prefillRecord['province'] ?? old_value($oldInput, 'province', 'Bangkok'));
        $oldInput['vehicle_type'] = (string) ($prefillRecord['vehicleType'] ?? '');
        $oldInput['brand'] = (string) ($prefillRecord['brand'] ?? '');
        $oldInput['model'] = (string) ($prefillRecord['model'] ?? '');
        $oldInput['color'] = (string) ($prefillRecord['color'] ?? '');
        $lookupMessage = ui_text('โหลดข้อมูลลูกค้าจาก Open Bill แล้ว', 'Customer data loaded from Open Bill.');
        $lookupState = 'success';
    } else {
        $lookupMessage = ui_text('ไม่พบข้อมูลลูกค้าที่ส่งมาจาก Open Bill', 'Open Bill customer data was not found.');
        $lookupState = 'warning';
    }
}

$lookupQuery = old_value($oldInput, 'lookup_phone', old_value($oldInput, 'phone'));

if (!$isNewCustomerMode && $matchedCustomerId === 0 && (normalize_phone($lookupQuery) !== '' || normalize_plate($lookupQuery) !== '')) {
    try {
        $matches = find_customer_matches($conn, $lookupQuery, $lookupQuery, 1);

        if (count($matches) === 1) {
            $matchedCustomerId = (int) ($matches[0]['customerId'] ?? 0);
            $matchedCarId = (int) ($matches[0]['carId'] ?? 0);
        }
    } catch (Throwable $exception) {
        $matchedCustomerId = 0;
    }
}

if ($isNewCustomerMode && $lookupMessage === '') {
    $lookupMessage = ui_text('กรอกข้อมูลลูกค้าใหม่และข้อมูลรถด้านล่างได้เลย', 'Enter the new customer and vehicle details below.');
}

$services = service_catalog_rows($conn, array(
    'service_types' => array('main_service', 'sub_service', 'package'),
    'active_only' => true,
));
$serviceCatalog = service_selection_catalog($conn, array('active_only' => true));
$selectedServices = array_map('intval', old_array($oldInput, 'service_ids'));
$selectedGroupChoices = array();
foreach (old_array($oldInput, 'service_group_choice') as $mainServiceId => $groupId) {
    $selectedGroupChoices[(int) $mainServiceId] = (int) $groupId;
}
$selectedPackageUsage = array();
foreach (old_array($oldInput, 'package_usage') as $serviceId => $customerPackageItemId) {
    $selectedPackageUsage[(int) $serviceId] = (int) $customerPackageItemId;
}
$selectedServiceNotes = array();
foreach (old_array($oldInput, 'service_notes') as $serviceId => $serviceNote) {
    $serviceId = (int) $serviceId;
    $serviceNote = trim((string) $serviceNote);

    if ($serviceId > 0 && $serviceNote !== '') {
        $selectedServiceNotes[$serviceId] = $serviceNote;
    }
}

$currentProvince = old_value($oldInput, 'province', 'Bangkok');
$provinceOptions = vehicle_province_options($currentProvince);
$branchNames = authorized_order_branch_options($conn);
$oldBrand = old_value($oldInput, 'brand');
$hasFilmServices = false;
$packageServices = array();
$availablePackageBalanceMap = $matchedCustomerId > 0 ? service_customer_package_balance_map($conn, $matchedCustomerId, $matchedCarId) : array();
$bookingVehiclePhoto = ($matchedCustomerId > 0 && $matchedCarId > 0)
    ? find_customer_record_by_ids($conn, $matchedCustomerId, $matchedCarId)
    : null;
$hasLookupAttempt = isset($_GET['lookup_customer']);
$hasLookupQuery = normalize_phone($lookupQuery) !== '' || normalize_plate($lookupQuery) !== '';
$hasRegistrationDraft = false;

foreach (array(
    'customer_name',
    'province',
    'vehicle_type',
    'brand',
    'model',
    'color',
    'branch_name',
    'scheduled_at',
    'slide_send_at',
    'service_at',
    'return_at',
    'total_price',
    'admin_deposit_amount',
    'branch_deposit_amount',
    'film_notes',
    'notes',
) as $draftKey) {
    if (trim((string) old_value($oldInput, $draftKey)) !== '') {
        $hasRegistrationDraft = true;
        break;
    }
}

if (!$hasRegistrationDraft) {
    foreach (array('service_ids', 'service_notes', 'package_usage', 'service_group_choice') as $draftArrayKey) {
        if (!empty(old_array($oldInput, $draftArrayKey))) {
            $hasRegistrationDraft = true;
            break;
        }
    }
}

$showBookingFlow = $isNewCustomerMode || $matchedCustomerId > 0 || $hasRegistrationDraft || ($hasLookupAttempt && $hasLookupQuery);
$bookingFlowHelper = $isNewCustomerMode
    ? ui_text(
        'กรอกข้อมูลลูกค้าใหม่และรถ จากนั้นเลือกบริการและเปิดบิลต่อได้เลย',
        'Enter the new customer and vehicle details below, then continue to service selection and open the bill.'
    )
    : ($matchedCustomerId > 0
        ? ui_text(
            'โหลดข้อมูลลูกค้าแล้ว ตรวจสอบข้อมูลลูกค้าและรถด้านล่างก่อนเปิดบิล',
            'Customer data loaded. Review the customer and vehicle details below before opening the bill.'
        )
        : ui_text(
            'หากไม่พบลูกค้าที่ตรงกัน ให้กรอกข้อมูลลูกค้าและรถด้านล่าง แล้วค่อยเลือกบริการต่อ',
            'If no matching customer is found, register the customer and vehicle details below and then continue to service selection.'
        ));
$scheduledAtParts = array(
    'date' => old_value($oldInput, 'scheduled_at_date'),
    'time' => old_value($oldInput, 'scheduled_at_time'),
);
if ($scheduledAtParts['date'] === '' && $scheduledAtParts['time'] === '') {
    $scheduledAtParts = datetime_form_parts(old_value($oldInput, 'scheduled_at'));
}

$slideSendAtParts = array(
    'date' => old_value($oldInput, 'slide_send_at_date'),
    'time' => old_value($oldInput, 'slide_send_at_time'),
);
if ($slideSendAtParts['date'] === '' && $slideSendAtParts['time'] === '') {
    $slideSendAtParts = datetime_form_parts(old_value($oldInput, 'slide_send_at'));
}

$serviceAtParts = array(
    'date' => old_value($oldInput, 'service_at_date'),
    'time' => old_value($oldInput, 'service_at_time'),
);
if ($serviceAtParts['date'] === '' && $serviceAtParts['time'] === '') {
    $serviceAtParts = datetime_form_parts(old_value($oldInput, 'service_at'));
}

$returnAtParts = array(
    'date' => old_value($oldInput, 'return_at_date'),
    'time' => old_value($oldInput, 'return_at_time'),
);
if ($returnAtParts['date'] === '' && $returnAtParts['time'] === '') {
    $returnAtParts = datetime_form_parts(old_value($oldInput, 'return_at'));
}

foreach ($services as $service) {
    $isFilmService = service_row_is_film($service);
    $serviceId = (int) $service['service_id'];
    $serviceType = (string) ($service['service_type'] ?? 'sub_service');

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

    if ($serviceType === 'package') {
        $packageServices[] = $service;
    }
}

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

$renderSelectableService = static function (array $service) use ($selectedServices, $selectedPackageUsage, $selectedServiceNotes, $availablePackageBalanceMap, $serviceItemNoteLabel, $serviceItemNotePlaceholder): void {
    $serviceId = (int) ($service['service_id'] ?? 0);
    $serviceType = (string) ($service['service_type'] ?? 'sub_service');
    $checked = in_array($serviceId, $selectedServices, 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';
    ?>
    <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
};

$filmFrontServiceId = (int) old_value($oldInput, 'film_front_service_id', '0');
$filmSunroofServiceId = (int) old_value($oldInput, 'film_sunroof_service_id', '0');
$filmFrontSideServiceId = (int) old_value($oldInput, 'film_front_side_service_id', '0');
$filmRearSideServiceId = (int) old_value($oldInput, 'film_rear_side_service_id', '0');
$filmRearServiceId = (int) old_value($oldInput, 'film_rear_service_id', '0');
$filmNotes = old_value($oldInput, 'film_notes');
$windowFilmGroups = array();

foreach ($serviceCatalog 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;
        }
    }
}

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

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

$rememberedBranchName = trim((string) ($_SESSION['booking_branch_name'] ?? ''));
if (old_value($oldInput, 'branch_name') === '') {
    if ($rememberedBranchName !== '' && in_array($rememberedBranchName, $branchNames, true)) {
        $oldInput['branch_name'] = $rememberedBranchName;
    } elseif (count($branchNames) === 1) {
        $oldInput['branch_name'] = $branchNames[0];
    }
}

$paymentMethods = quick_service_payment_methods();
$canCollectAdminDeposit = can_access($conn, 'booking_deposit_admin');
$canCollectBranchDeposit = can_access($conn, 'booking_deposit_branch');

$rememberedAdminDepositMethod = trim((string) ($_SESSION['booking_admin_payment_method'] ?? $_SESSION['booking_payment_method'] ?? 'cash'));
if (!array_key_exists($rememberedAdminDepositMethod, $paymentMethods)) {
    $rememberedAdminDepositMethod = 'cash';
}

$rememberedBranchDepositMethod = trim((string) ($_SESSION['booking_branch_payment_method'] ?? 'cash'));
if (!array_key_exists($rememberedBranchDepositMethod, $paymentMethods)) {
    $rememberedBranchDepositMethod = 'cash';
}

if (old_value($oldInput, 'admin_deposit_method') === '') {
    $oldInput['admin_deposit_method'] = $rememberedAdminDepositMethod;
}

if (old_value($oldInput, 'branch_deposit_method') === '') {
    $oldInput['branch_deposit_method'] = $rememberedBranchDepositMethod;
}

if (!$canCollectAdminDeposit) {
    $oldInput['admin_deposit_amount'] = '';
    $oldInput['admin_deposit_method'] = 'cash';
}

if (!$canCollectBranchDeposit) {
    $oldInput['branch_deposit_amount'] = '';
    $oldInput['branch_deposit_method'] = 'cash';
}

$selectedBookingBranchName = trim((string) old_value($oldInput, 'branch_name'));
$qrAvailable = quick_service_qr_available($selectedBookingBranchName, 'booking_deposit_admin')
    || quick_service_qr_available($selectedBookingBranchName, 'booking_deposit_branch')
    || quick_service_qr_available('', 'booking_deposit_admin')
    || quick_service_qr_available('', 'booking_deposit_branch')
    || quick_service_qr_available($selectedBookingBranchName, 'quick_service')
    || quick_service_qr_available();

$adminDepositSlipVisible = (float) old_value($oldInput, 'admin_deposit_amount', '0') > 0
    && payment_method_supports_slip((string) old_value($oldInput, 'admin_deposit_method', 'cash'));
$branchDepositSlipVisible = (float) old_value($oldInput, 'branch_deposit_amount', '0') > 0
    && payment_method_supports_slip((string) old_value($oldInput, 'branch_deposit_method', 'cash'));

$pageTitle = ui_text('เปิดบิล', 'Booking');
$pageHeading = ui_text('เปิดบิลใหม่', 'New booking');
$pageDescription = ui_text('สร้างลูกค้า รถ รายการบริการ และคิวงานได้ในขั้นตอนเดียว', 'Create a customer, vehicle, service order and queue number in one flow.');
$backToDashboardLabel = ui_text('กลับไปแดชบอร์ด', 'Back to dashboard');
$noActiveServicesLabel = ui_text('ยังไม่มีบริการที่เปิดใช้งานอยู่ เพิ่มบริการอย่างน้อย 1 รายการก่อนเปิดบิล', 'No active services are available. Add at least one service before creating bookings.');
$addServiceLabel = ui_text('เพิ่มบริการ', 'Add service');
$searchCustomerLabel = ui_text('ค้นหาลูกค้าด้วยเบอร์โทรหรือทะเบียนรถ', 'Search customer by phone or plate');
$searchCustomerHelperLabel = ui_text('ค้นหาได้เฉพาะเบอร์โทรลูกค้าหรือทะเบียนรถที่ตรงกันเท่านั้น', 'Search works only with the exact customer phone number or exact plate number.');
$customerVehicleDetailsLabel = ui_text('ข้อมูลลูกค้าและรถ', 'Customer and vehicle details');
$customerNameLabel = ui_text('ชื่อลูกค้า', 'Customer name');
$phoneLabel = ui_text('เบอร์โทร', 'Phone');
$plateNumberLabel = ui_text('ทะเบียนรถ', 'Plate number');
$provinceLabel = ui_text('จังหวัด', 'Province');
$selectProvinceLabel = ui_text('เลือกจังหวัด', 'Select province');
$brandLabel = ui_text('ยี่ห้อ', 'Brand');
$brandPlaceholder = ui_text('เช่น Toyota, BMW, BYD', 'Toyota, BMW, BYD');
$modelLabel = ui_text('รุ่น', 'Model');
$colorLabel = ui_text('สี', 'Color');
$serviceSelectionLabel = ui_text('เลือกบริการ', 'Service selection');
$serviceSelectionHelperLabel = ui_text('เลือกบริการย่อยสำหรับรอบนี้ แล้วค่อยใช้สิทธิ์แพ็กเกจหากลูกค้ายังมีจำนวนคงเหลือ', 'Choose sub services for this visit, then apply package usage if the customer still has remaining balance.');
$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');
$noSubServicesLabel = ui_text('ยังไม่มีบริการย่อยในกลุ่มนี้', 'No sub services linked to this group yet.');
$packageOffersLabel = ui_text('ข้อเสนอแพ็กเกจ', 'Package offers');
$packageOffersHelperLabel = ui_text('เมื่อขายแพ็กเกจ ระบบจะเพิ่มสิทธิ์บริการย่อยให้ลูกค้าหลังบันทึกการจองนี้', 'Selling a package adds reusable sub service balances to the customer after this booking is saved.');
$availablePackagesLabel = ui_text('แพ็กเกจที่ใช้ได้', 'Available packages');
$noActivePackageBalanceLabel = ui_text('ไม่พบสิทธิ์แพ็กเกจที่ใช้งานได้สำหรับลูกค้าคนนี้', 'No active package balance found for this customer.');
$bookingSummaryLabel = ui_text('สรุปการเปิดบิล', 'Booking summary');
$serviceBranchLabel = ui_text('สาขาที่ให้บริการ', 'Service branch');
$selectBranchLabel = ui_text('เลือกสาขา', 'Select branch');
$selectedServicesLabel = ui_text('รายการที่เลือก', 'Selected services');
$coveredByPackageLabel = ui_text('ใช้สิทธิ์แพ็กเกจไป', 'Covered by package');
$serviceTotalLabel = ui_text('ยอดค่าบริการ', 'Service total');
$bookingTotalLabel = ui_text('ยอดรวมบิล', 'Booking total');
$depositAdminLabel = ui_text('มัดจำ @Admin', 'Deposit @Admin');
$depositBranchLabel = ui_text('มัดจำ @Branch', 'Deposit @Branch');
$depositAmountLabel = ui_text('จำนวนเงินมัดจำ', 'Deposit amount');
$paymentMethodLabel = ui_text('วิธีชำระเงิน', 'Payment method');
$qrPaymentLabel = ui_text('ชำระด้วย QR', 'QR payment');
$qrPaymentHintLabel = ui_text('สแกนเพื่อรับชำระเงิน', 'Scan to receive payment.');
$bookingAdminDepositQrLabel = ui_text('คิวอาร์มัดจำ Booking @Admin', 'Booking admin deposit QR');
$bookingBranchDepositQrLabel = ui_text('คิวอาร์มัดจำ Booking @Branch', 'Booking branch deposit QR');
$billNoteLabel = ui_text('หมายเหตุบิล', 'Bill note');
$billNotePlaceholder = ui_text('ระบุข้อมูลเพิ่มเติมสำหรับบิลนี้', 'Add extra information for this bill.');
$billNoteHelperLabel = ui_text('หมายเหตุนี้เป็นข้อมูลรวมของบิล หากต้องการหมายเหตุเฉพาะรายการให้ใส่ที่ช่องหมายเหตุรายบริการ', 'This note applies to the whole bill. Use item notes for service-specific details.');
$notesLabel = $billNoteLabel;
$createBookingLabel = ui_text('เปิดบิล', 'Create booking');

$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, 'booking', array('translation_buffer' => false));
?>

<section class="page-hero">
    <div>
        <h1><?= e($pageHeading) ?></h1>
        <p><?= e($pageDescription) ?></p>
    </div>
    <div class="hero-actions">
        <a class="button button-secondary" href="dashboard.php"><?= e($backToDashboardLabel) ?></a>
    </div>
</section>

<?php if (empty($services)): ?>
    <section class="empty-state">
        <?= e($noActiveServicesLabel) ?>
        <div class="actions" style="justify-content: center; margin-top: 14px;">
            <a class="button" href="services.php"><?= e($addServiceLabel) ?></a>
        </div>
    </section>
<?php else: ?>
    <form
        method="POST"
        action="../process/save_booking.php"
        enctype="multipart/form-data"
        data-booking-form
        data-positive-total-message="<?= e(ui_text('ยอดรวมบิลต้องมากกว่า 0 ก่อนเปิดบิล', 'Booking total must be greater than 0 before opening the bill.')) ?>"
        data-qr-available="<?= $qrAvailable ? '1' : '0' ?>"
        data-qr-endpoint="../process/quick_service_qr.php"
        data-qr-branch="<?= e($selectedBookingBranchName) ?>"
    >
        <?= csrf_input('booking_save') ?>
        <?php if (!$showBookingFlow): ?>
        <section class="card booking-lookup-card">
            <div class="form-grid booking-lookup-grid">
                <div class="field">
                    <label for="lookup_phone"><?= e($searchCustomerLabel) ?></label>
                    <input
                        id="lookup_phone"
                        name="lookup_phone"
                        type="text"
                        inputmode="text"
                        autocomplete="off"
                        value="<?= e(old_value($oldInput, 'lookup_phone', old_value($oldInput, 'phone'))) ?>"
                        placeholder="0971234567 / 1234 / 5ขฮ8154"
                    >
                    <p class="helper"><?= e($searchCustomerHelperLabel) ?></p>
                </div>
            </div>

            <div class="actions booking-lookup-actions">
                <button
                    class="button app-action-button"
                    type="submit"
                    name="lookup_customer"
                    value="1"
                    formmethod="GET"
                    formaction="booking.php"
                    formnovalidate
                    data-customer-lookup
                ><?= app_button_content('search', ui_text('ค้นหา', 'Search')) ?></button>
                <button
                    class="button button-accent app-action-button"
                    type="submit"
                    name="new_customer"
                    value="1"
                    formmethod="GET"
                    formaction="booking.php"
                    formnovalidate
                    data-new-customer-trigger
                ><?= app_button_content('user-plus', ui_text('ลูกค้าใหม่', 'New Customer')) ?></button>
                <a class="button button-ghost app-action-button" href="booking.php"><?= app_button_content('rotate-ccw', ui_text('รีเซ็ต', 'Reset')) ?></a>
            </div>

            <div class="form-grid booking-lookup-grid">
                <div class="lookup-feedback" data-lookup-feedback data-state="<?= e($lookupState) ?>" aria-live="polite"><?= e($lookupMessage) ?></div>
                <div class="lookup-results" data-lookup-results hidden></div>
            </div>
        </section>
        <?php endif; ?>

        <div class="content-grid booking-flow-grid" data-booking-flow <?= $showBookingFlow ? '' : 'hidden' ?>>
            <div class="grid">
                <section class="form-card">
                    <div class="section-head">
                        <div>
                            <h2 class="section-title"><?= e($customerVehicleDetailsLabel) ?></h2>
                            <p class="helper"><?= e($bookingFlowHelper) ?></p>
                        </div>
                    </div>

                    <div class="form-grid">
                        <?php if (is_array($bookingVehiclePhoto)): ?>
                            <div class="field">
                                <label><?= e(ui_text('รูปโปรไฟล์รถ', 'Vehicle profile photo')) ?></label>
                                <div class="vehicle-profile-inline">
                                    <?= car_profile_photo_html($bookingVehiclePhoto, 'vehicle-profile-photo vehicle-profile-photo--sm', 'vehicle-profile-photo-placeholder vehicle-profile-photo-placeholder--sm') ?>
                                    <span class="helper"><?= e(ui_text('รูปนี้ถูกดึงจากข้อมูลรถคันนี้', 'This photo comes from this vehicle record.')) ?></span>
                                </div>
                            </div>
                        <?php endif; ?>
                        <div class="field">
                            <label for="customer_name"><?= e($customerNameLabel) ?></label>
                            <input id="customer_name" name="customer_name" type="text" value="<?= e(old_value($oldInput, 'customer_name')) ?>" required>
                        </div>

                        <div class="field">
                            <label for="phone"><?= e($phoneLabel) ?></label>
                            <input
                                id="phone"
                                name="phone"
                                type="text"
                                inputmode="numeric"
                                autocomplete="tel"
                                value="<?= e(old_value($oldInput, 'phone')) ?>"
                                placeholder="0971234567"
                                required
                            >
                        </div>

                        <div class="field">
                            <label for="plate_number"><?= e($plateNumberLabel) ?></label>
                            <input id="plate_number" name="plate_number" type="text" value="<?= e(old_value($oldInput, 'plate_number')) ?>" required>
                        </div>

                        <div class="field">
                            <label for="province"><?= e($provinceLabel) ?></label>
                            <select id="province" name="province" data-default-value="Bangkok">
                                <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>
                            <input
                                id="brand"
                                name="brand"
                                type="text"
                                value="<?= e($oldBrand) ?>"
                                placeholder="<?= e($brandPlaceholder) ?>"
                            >
                        </div>

                        <div class="field">
                            <label for="model"><?= e($modelLabel) ?></label>
                            <input id="model" name="model" type="text" value="<?= e(old_value($oldInput, 'model')) ?>" placeholder="911 GT3, M4, Camry">
                        </div>

                        <div class="field">
                            <label for="color"><?= e($colorLabel) ?></label>
                            <input id="color" name="color" type="text" value="<?= e(old_value($oldInput, 'color')) ?>">
                        </div>
                    </div>
                </section>

                <section class="form-card">
                    <div class="section-head">
                        <div>
                            <h2 class="section-title"><?= e($serviceSelectionLabel) ?></h2>
                            <p class="helper"><?= e($serviceSelectionHelperLabel) ?></p>
                        </div>
                    </div>

                    <div class="service-options">
                        <?php if (empty($serviceCatalog)): ?>
                            <div class="empty-state"><?= e(ui_text('ยังไม่มีบริการที่เปิดใช้งานอยู่', 'No active services are available.')) ?></div>
                        <?php else: ?>
                            <?php foreach ($serviceCatalog as $category): ?>
                                <div class="service-group-head">
                                    <h3><?= e((string) ($category['category_name'] ?? ui_text('หมวดหมู่', 'Category'))) ?></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, $selectedServices, true);
                                    $selectedGroupId = (int) ($selectedGroupChoices[$mainServiceId] ?? 0);

                                    if ($selectedGroupId <= 0) {
                                        foreach ((array) ($mainService['groups'] ?? array()) as $groupRow) {
                                            foreach ((array) ($groupRow['sub_services'] ?? array()) as $subService) {
                                                if (in_array((int) ($subService['service_id'] ?? 0), $selectedServices, true)) {
                                                    $selectedGroupId = (int) ($groupRow['group_id'] ?? 0);
                                                    break 2;
                                                }
                                            }
                                        }
                                    }

                                    $hasSelectedChild = false;
                                    foreach ((array) ($mainService['direct_sub_services'] ?? array()) as $directSubService) {
                                        if (in_array((int) ($directSubService['service_id'] ?? 0), $selectedServices, 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), $selectedServices, true)) {
                                                    $hasSelectedChild = true;
                                                    break 2;
                                                }
                                            }
                                        }
                                    }

                                    $isOpen = $mainServiceChecked || $selectedGroupId > 0 || $hasSelectedChild;
                                    ?>
                                    <details class="service-flow-card" data-main-service-flow data-main-service-id="<?= $mainServiceId ?>" <?= $isOpen ? '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'] ?? ui_text('กลุ่มบริการ', 'Group'))) ?></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($noSubServicesLabel) ?></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($packageServices)): ?>
                        <div class="section-head" style="margin-top: 18px;">
                            <div>
                                <h3 class="section-title"><?= e($packageOffersLabel) ?></h3>
                                <p class="helper"><?= e($packageOffersHelperLabel) ?></p>
                            </div>
                        </div>
                        <div class="service-options">
                            <?php foreach ($packageServices as $service): ?>
                                <?php
                                $serviceId = (int) $service['service_id'];
                                $checked = in_array($serviceId, $selectedServices, 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="section-head">
                                <div>
                                    <h3 class="section-title">Window film details</h3>
                                    <p class="helper">Choose the sub service for each glass position from the selected service group.</p>
                                </div>
                            </div>

                            <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-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">กระจกหน้า</span>
                                    <span class="film-zone film-zone-side-front">ประตูข้างคู่หน้า</span>
                                    <span class="film-zone film-zone-side-rear">ประตูข้างคู่หลัง</span>
                                    <span class="film-zone film-zone-rear">กระจกหลัง</span>
                                </div>

                                <div class="form-grid">
                                    <div class="field">
                                        <label for="film_front_percent">กระจกหน้า</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">ประตูข้างคู่หน้า</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">ประตูข้างคู่หลัง</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">กระจกหลัง</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>

                            <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; ?>
                </section>
            </div>

            <aside class="grid summary-panel">
                <section class="card" data-package-summary-card <?= $matchedCustomerId > 0 ? '' : 'hidden' ?>>
                    <h2 class="section-title"><?= e($availablePackagesLabel) ?></h2>
                    <div data-package-summary>
                        <?php if (empty($availablePackageBalanceMap)): ?>
                            <p class="helper"><?= e($noActivePackageBalanceLabel) ?></p>
                        <?php else: ?>
                            <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>
                        <?php endif; ?>
                    </div>
                </section>

                <section class="card booking-summary-card">
                    <h2 class="section-title"><?= e($bookingSummaryLabel) ?></h2>
                    <div class="field branch-field">
                        <label for="branch_name"><?= e($serviceBranchLabel) ?></label>
                        <select id="branch_name" name="branch_name" required>
                            <option value=""><?= e($selectBranchLabel) ?></option>
                            <?php foreach ($branchNames as $branchName): ?>
                                <option value="<?= e($branchName) ?>" <?= old_value($oldInput, 'branch_name') === $branchName ? 'selected' : '' ?>>
                                    <?= e($branchName) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <p class="helper"><?= e($selectedServicesLabel) ?></p>
                    <p class="summary-total"><span data-selected-count>0</span> <?= e(ui_text('รายการ', 'item(s)')) ?></p>
                    <p class="helper"><?= e($coveredByPackageLabel) ?>: <strong data-selected-package-discount>0.00</strong> THB</p>
                    <p class="helper"><?= e($serviceTotalLabel) ?></p>
                    <p class="summary-total"><span data-selected-total>0.00</span> THB</p>
                    <div class="field summary-price-field">
                        <label for="total_price"><?= e($bookingTotalLabel) ?></label>
                        <input
                            id="total_price"
                            name="total_price"
                            type="number"
                            step="0.01"
                            min="0.01"
                            value="<?= e(old_value($oldInput, 'total_price')) ?>"
                            data-total-price-input
                        >
                        <p class="helper" data-booking-total-validation-message hidden></p>
                    </div>

                    <?php if ($canCollectAdminDeposit): ?>
                        <div class="stack">
                            <h3 class="section-title"><?= e($depositAdminLabel) ?></h3>
                            <div class="form-grid">
                                <div class="field">
                                    <label for="admin_deposit_amount"><?= e($depositAmountLabel) ?></label>
                                    <input
                                        id="admin_deposit_amount"
                                        name="admin_deposit_amount"
                                        type="number"
                                        step="0.01"
                                        min="0"
                                        value="<?= e(old_value($oldInput, 'admin_deposit_amount')) ?>"
                                    >
                                </div>

                                <div class="field">
                                    <label for="admin_deposit_method"><?= e($paymentMethodLabel) ?></label>
                                    <select
                                        id="admin_deposit_method"
                                        name="admin_deposit_method"
                                        data-deposit-method-select
                                        data-deposit-slip-target="admin"
                                    >
                                        <?php foreach ($paymentMethods as $paymentMethodValue => $paymentMethodLabel): ?>
                                            <option value="<?= e($paymentMethodValue) ?>" <?= old_value($oldInput, 'admin_deposit_method', 'cash') === $paymentMethodValue ? 'selected' : '' ?>>
                                                <?= e($paymentMethodLabel) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>

                            <div
                                class="field payment-slip-field"
                                data-deposit-slip-group="admin"
                                <?= $adminDepositSlipVisible ? '' : 'hidden' ?>
                            >
                                <label for="admin_deposit_slip_file"><?= ui_text('แนบสลิป / หลักฐานการชำระ', 'Payment slip / proof') ?></label>
                                <input
                                    id="admin_deposit_slip_file"
                                    name="admin_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>
                            </div>

                            <section
                                class="card quick-service-qr-panel"
                                data-deposit-qr-panel="admin"
                                <?= old_value($oldInput, 'admin_deposit_method', 'cash') === 'qr' && (float) old_value($oldInput, 'admin_deposit_amount', '0') > 0 ? '' : 'hidden' ?>
                            >
                                <h3 class="section-title"><?= e($qrPaymentLabel) ?></h3>
                                <p class="helper" data-deposit-qr-hint="admin"><?= e($qrPaymentHintLabel) ?></p>
                                <div class="quick-service-qr-preview">
                                    <img src="" alt="<?= e($bookingAdminDepositQrLabel) ?>" data-deposit-qr-image="admin">
                                </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="admin"
                                    ><?= app_button_content('download', ui_text('บันทึก QR', 'Save QR')) ?></a>
                                </div>
                            </section>
                        </div>
                    <?php endif; ?>

                    <?php if ($canCollectBranchDeposit): ?>
                        <div class="stack">
                            <h3 class="section-title"><?= e($depositBranchLabel) ?></h3>
                            <div class="form-grid">
                                <div class="field">
                                    <label for="branch_deposit_amount"><?= e($depositAmountLabel) ?></label>
                                    <input
                                        id="branch_deposit_amount"
                                        name="branch_deposit_amount"
                                        type="number"
                                        step="0.01"
                                        min="0"
                                        value="<?= e(old_value($oldInput, 'branch_deposit_amount')) ?>"
                                    >
                                </div>

                                <div class="field">
                                    <label for="branch_deposit_method"><?= e($paymentMethodLabel) ?></label>
                                    <select
                                        id="branch_deposit_method"
                                        name="branch_deposit_method"
                                        data-deposit-method-select
                                        data-deposit-slip-target="branch"
                                    >
                                        <?php foreach ($paymentMethods as $paymentMethodValue => $paymentMethodLabel): ?>
                                            <option value="<?= e($paymentMethodValue) ?>" <?= old_value($oldInput, 'branch_deposit_method', 'cash') === $paymentMethodValue ? 'selected' : '' ?>>
                                                <?= e($paymentMethodLabel) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>

                            <div
                                class="field payment-slip-field"
                                data-deposit-slip-group="branch"
                                <?= $branchDepositSlipVisible ? '' : 'hidden' ?>
                            >
                                <label for="branch_deposit_slip_file"><?= ui_text('แนบสลิป / หลักฐานการชำระ', 'Payment slip / proof') ?></label>
                                <input
                                    id="branch_deposit_slip_file"
                                    name="branch_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>
                            </div>

                            <section
                                class="card quick-service-qr-panel"
                                data-deposit-qr-panel="branch"
                                <?= old_value($oldInput, 'branch_deposit_method', 'cash') === 'qr' && (float) old_value($oldInput, 'branch_deposit_amount', '0') > 0 ? '' : 'hidden' ?>
                            >
                                <h3 class="section-title"><?= e($qrPaymentLabel) ?></h3>
                                <p class="helper" data-deposit-qr-hint="branch"><?= e($qrPaymentHintLabel) ?></p>
                                <div class="quick-service-qr-preview">
                                    <img src="" alt="<?= e($bookingBranchDepositQrLabel) ?>" data-deposit-qr-image="branch">
                                </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="branch"
                                    ><?= app_button_content('download', ui_text('บันทึก QR', 'Save QR')) ?></a>
                                </div>
                            </section>
                        </div>
                    <?php endif; ?>
                </section>

                <section class="card" hidden>
                    <h2 class="section-title">วันเวลาและวันรับรถ</h2>
                    <div class="field">
                        <label for="scheduled_at">วันเวลา: สไลรับ</label>
                        <input id="legacy_scheduled_at" name="legacy_scheduled_at" type="datetime-local" value="<?= e(old_value($oldInput, 'scheduled_at')) ?>" disabled>
                    </div>

                    <div class="field">
                        <label for="return_at">ขอรับรถ: สไลส่ง</label>
                        <input id="legacy_return_at" name="legacy_return_at" type="datetime-local" value="<?= e(old_value($oldInput, 'return_at')) ?>" disabled>
                    </div>

                    <div class="field">
                        <label for="legacy_notes"><?= e($billNoteLabel) ?></label>
                        <textarea id="legacy_notes" name="legacy_notes" disabled><?= e(old_value($oldInput, 'notes')) ?></textarea>
                    </div>
                </section>

                <section class="card booking-due-card">
                    <h2 class="section-title"><?= e(ui_text('กำหนดวัน รับ/ส่งรถ และหมายเหตุบิล', 'Due dates, pickup/delivery and bill note')) ?></h2>
                    <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 class="field bill-note-field">
                        <label for="notes"><?= e($billNoteLabel) ?></label>
                        <textarea id="notes" name="notes" rows="4" placeholder="<?= e($billNotePlaceholder) ?>"><?= e(old_value($oldInput, 'notes')) ?></textarea>
                        <p class="helper"><?= e($billNoteHelperLabel) ?></p>
                    </div>

                    <div class="booking-submit-wrap">
                        <button class="button button-accent button-full" type="submit"><?= e($createBookingLabel) ?></button>
                    </div>
                </section>

            </aside>
        </div>
    </form>
<?php endif; ?>

<?php render_page_end(); ?>
